本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
Spring Boot 提供了许多注解,这些注解使得开发者能够快速地配置和集成 Spring 应用程序。以下是一些常用的 Spring Boot 注解:
1、@SpringBootApplication
这是一个组合注解,包含了 @SpringBootConfiguration、@EnableAutoConfiguration 和 @ComponentScan。包含三者的功能。
举例:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
源代码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
//省略其他代码,详情参考具体源码
}
2、@SpringBootConfiguration
这个注解包含了 @Configuration,@Configuration 里面又包含了一个 @Component 注解,也就是说,这个注解标注在哪个类上,就表示当前这个类是一个配置类,而配置类也是 spring 容器中的组件。
源代码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
3、@EnableAutoConfiguration
开启自动配置的功能。
源代码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
//省略其他代码,详情参考具体源码
}
4、@ComponentScan
启用组件扫描(可以设置扫描路径),允许 Spring Boot 发现和注册控制器、服务等组件。
源代码:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
//省略其他代码,详情参考具体源码
}
5、@RestController
这是一个组合注解,等同于 @Controller 和 @ResponseBody。用于创建返回 JSON、XML 等内容作为响应主体的 REST 控制器。用于将 JSON 等内容数据返回,数据不走视图处理器,直接写入到输入流中。
举例(在访问地址输入 “/hello” 后生成一个临时页面输出 "Hello, SpringBoot"):
@RestController
public class DemoController {
@RequestMapping("/hello")
public String hello(){
return "Hello, SpringBoot";
}
}
6、@Controller
用于标记在一个类上,使用它标记的类就是一个 SpringMVC Controller 对象。用于将返回的数据返回到一个页面,数据走视图处理器。
举例(在访问地址输入 “/show” 后,通过 ModelMap 向 index 页面传输 msg,在页面可以通过 msg 获取对应的值):
@Controller
public class Demo2Controller {
@RequestMapping("/show")
public String show(ModelMap map){
map.put("msg","这是来自控制器的一条信息");
return "index";
}
}
7、@ResponseBody
将 Controller 的方法返回的对象,通过适当的转换器转换为指定的格式之后,写入到 response 对象的 body 区,通常用来返回 JSON 数据或者是 XML 数据。一般作用在方法上。
举例(不会跳转到 success 页面,而是直接显示 “success” 字符串):
@Controller
public class Demo2Controller {
@ResponseBody
@RequestMapping("/test")
public String test(){
return "success";
}
}
8、@RequestMapping
处理请求访问地址映射的注解,可用于映射一个请求或一个方法,可以用在类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法。类上可以不用。
举例(要使用 show 方法,必须访问地址 “/demo2/show”, 类上的映射地址和方法上的映射地址都必须写上):
@Controller
@RequestMapping("/Demo2")
public class Demo2Controller {
@RequestMapping("/show")
public String show(ModelMap map){
map.put("msg","这是来自控制器的一条信息");
return "index";
}
}
9、@GetMapping、@PostMapping、@PutMapping、@DeleteMapping
功能和 @RequestMapping 类似,用于处理特别的请求,分别用于处理 GET、POST、PUT、DELETE 请求。
举例:
@RestController
public class Demo3Controller {
@GetMapping("/get")
public String get(){
return "get 请求数据信息";
}
@PostMapping("/post")
public String post(){
return "post 请求数据信息";
}
@PutMapping("/put")
public String put(){
return "put 请求数据信息";
}
@DeleteMapping("/delete")
public String delete(){
return "delete 请求数据信息";
}
}
10、@Configuration
用于标注配置类,替代 XML 配置。
举例(标注 DemoConfig 为配置类):
@Configuration
public class DemoConfig {
@Bean
public User test(){
return new User();
}
}
11、@Bean
用于将外部配置的值注入到 Bean 中。
举例(test 方法会创建 User 这样的 Bean):
@Configuration
public class DemoConfig {
@Bean
public User test(){
return new User();
}
}
12、@Component
标注 Spring 管理的 Bean,使用 @Component 注解在一个类上,表示将此类标记为 Spring 容器中的一个 Bean。基于 @Component 注解的有以下几个:
@Controller: controller 控制器层
@Service : service 服务层(或业务逻辑层)
@Repository : dao 持久层(或数据访问层)
举例:
@Component
public class User {
}
13、@Service
是 Spring Framework 中的一个注解,用于标识一个类为服务层(或业务逻辑层)组件。
举例:
@Service
public class UserService {
}
14、@Repository
是 Spring Framework 中的一个注解,用于标识一个类为数据访问层 (DAO 层) 组件。
@Repository
public class UserDao {
}
15、@Value
用于将外部配置的值注入到 Bean 中,一般将配置文件中的变量的值注入到当前类的成员变量中,也可以直接设置值。
举例(假设配置文件中已设置 user.name):
public class User {
@Value("${user.name}")
private String name;
@Value("xxx@qq.com")
private String email;
}
16、@ConfigurationProperties
用于绑定和验证来自外部源的配置属性。一般作用在类上。
举例(假设配置文件中已设置 user.name 和 user.email):
@ConfigurationProperties(prefix = "user")
public class User {
private String name;
private String email;
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
}
17、@RequestParam
用于将请求参数绑定到控制器的处理方法的参数上。
举例(从前端页面传入两个参数 username 和 password,可以使用 @RequestParam 将前端的 username 参数和后端方法的 name 参数进行映射对应传参,password 和 pwd 同理):
@RequestMapping("/login")
public String login(@RequestParam("username") String name, @RequestParam("password")String pwd){
if(name.equals("admin")&&pwd.equals("123456")){
return "index";
}else{
return "error";
}
}
18、@PathVariable
用于将 URI 模板变量映射到控制器处理方法的参数上。
举例(假设在 URL 输入:http://localhost:8080/showName/zhangsan, 可以获取到输入的 zhangsan):
@RequestMapping("/showName/{name}")
public String showName(@PathVariable("name") String name){
return name;
}
19、@EnableCaching
开启基于注解的缓存,一般用在主启动类或者配置类上。
举例:
@SpringBootApplication
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
20、@Cacheable
作用在方法或者类上。在方法执行之前,会先根据 key 查看缓存中是否有对应缓存数据,如果有,直接从缓存中取数据,不运行方法;如果没有,执行方法,并将方法的返回值存入缓存。
举例:
@Service
public class UserService {
@Autowired
UserDao userDao;
@Cacheable(value = "user",key = "#id")
public User getUserById(int id){
return userDao.getUserById(id);
}
}
21、@CachePut
作用在类或者方法上,在方法被调用的同时使得返回值被存入缓存。
举例:
@CachePut(value = "user",key = "#id")
public User updateUserById(int id){
return userDao.getUserById(id);
}
22、@CacheEvict
作用在类或者方法上,在方法执行后,删除 key 对应的缓存。
举例:
@CacheEvict(value = "user",key="#id")
public void deleteUserById(int id){
userDao.deleteUserById(id);
}
23、@CacheConfig
主要用于统筹管理类中所有的使用 @Cachable,@CachePut,@CacheEvict 标注的方法中的公告属性,例如缓存名等。
举例:
@Caching(
cacheable = {
@Cacheable(value = "emp",key = "#lastName")
},
put = {
@CachePut(value = "emp",key = "#result.id"),
@CachePut(value = "emp",key = "#result.email"),
}
)
24、@EnableScheduling
是 Spring Framework 提供的一个注解,用于启用定时任务功能。一般标注在启动类上。
举例:
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
25、@Scheduled
标注在方法上,创建一个定时任务方法,可以指定执行的时间间隔或时间点
举例:
@Scheduled(fixedRate = 5000) // 每隔 5 秒执行一次
public void performTask() {
// 执行定时任务的逻辑
System.out.println("定时任务执行中...");
}
26、@Transactional
@Transactional 可以作用在接口、类、类方法,用于声明事务
作用于类:当把 @Transactional 注解放在类上时,表示所有该类的 public 方法都配置相同的事务属性信息。
作用于方法:当类配置了 @Transactional,方法也配置了 @Transactional,方法的事务会覆盖类的事务配置信息。
作用于接口:不推荐这种使用方法,因为一旦标注在 Interface 上并且配置了 Spring AOP 使用 CGLib 动态代理,将会导致 @Transactional 注解失效。
举例:
@Transactional
public void transferAccount(int id,int account){
//省略代码
}
27、@Profiles
作用是指定类或方法在特定的 Profile 环境生效,任何@Component或@Configuration注解的类都可以使用@Profile注解。
举例(假设已经配置了 prod 环境):
@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public User changeData {
// 省略代码
}
}
以上是常用的 Spring Boot 注解。