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注解。