Spring Boot 相比 Spring 多了很多自动化配置和简化开发的注解,主要包括以下几类:
- Spring Boot 启动与自动配置相关
- Spring Boot 配置相关
- Spring Boot Web 相关
- Spring Boot 测试相关
- Spring Boot 条件装配相关
- Spring Boot 监控与 Actuator 相关
1. Spring Boot 启动与自动配置相关
| 注解 | 作用 |
|---|
@SpringBootApplication | Spring Boot 入口类,相当于 @Configuration + @EnableAutoConfiguration + @ComponentScan |
@EnableAutoConfiguration | 启用 Spring Boot 自动配置,根据类路径中的依赖自动配置 Bean |
@SpringBootConfiguration | 继承自 @Configuration,用于定义 Spring Boot 配置类 |
@ComponentScan | 组件扫描,默认扫描当前类所在的包及其子包 |
2. Spring Boot 配置相关
| 注解 | 作用 |
|---|
@ConfigurationProperties(prefix = "xxx") | 绑定外部配置,用于从 application.yml 或 application.properties 加载配置 |
@EnableConfigurationProperties | 使 @ConfigurationProperties 注解的类生效 |
@PropertySource("classpath:xxx.properties") | 引入额外的配置文件 |
@Value("${xxx}") | 注入配置值 |
@ImportResource("classpath:xxx.xml") | 引入 XML 配置文件 |
3. Spring Boot Web 相关
| 注解 | 作用 |
|---|
@RestController | @Controller + @ResponseBody,返回 JSON 数据的 RESTful API |
@GetMapping | @RequestMapping(method = RequestMethod.GET) 的简化版 |
@PostMapping | @RequestMapping(method = RequestMethod.POST) 的简化版 |
@PutMapping | @RequestMapping(method = RequestMethod.PUT) 的简化版 |
@DeleteMapping | @RequestMapping(method = RequestMethod.DELETE) 的简化版 |
@PatchMapping | @RequestMapping(method = RequestMethod.PATCH) 的简化版 |
@ResponseStatus(HttpStatus.OK) | 指定返回状态码 |
4. Spring Boot 测试相关
| 注解 | 作用 |
|---|
@SpringBootTest | Spring Boot 测试环境,会自动加载 Spring Boot 上下文 |
@TestConfiguration | 测试专用的 @Configuration,避免污染生产配置 |
@MockBean | 使用 Mockito 模拟 Bean,替换真实的 Bean |
@SpyBean | 对 Spring 容器中的 Bean 进行部分模拟 |
5. Spring Boot 条件装配相关
| 注解 | 作用 |
|---|
@ConditionalOnClass | 类存在时才生效 |
@ConditionalOnMissingClass | 类不存在时才生效 |
@ConditionalOnBean | 容器中存在某个 Bean 时才生效 |
@ConditionalOnMissingBean | 容器中不存在某个 Bean 时才生效 |
@ConditionalOnProperty(name="xxx", havingValue="true") | 指定配置项存在且等于指定值时才生效 |
@ConditionalOnExpression("${xxx} == true") | Spring EL 表达式条件判断 |
@ConditionalOnWebApplication | Web 环境下才生效 |
@ConditionalOnNotWebApplication | 非 Web 环境下才生效 |
6. Spring Boot 监控与 Actuator 相关
| 注解 | 作用 |
|---|
@EnableScheduling | 开启定时任务 |
@Scheduled(fixedRate = 5000) | 定义定时任务,每 5 秒执行一次 |
@EnableAsync | 开启异步任务 |
@Async | 异步执行方法 |
@EnableCaching | 开启缓存 |
@Cacheable("users") | 启用缓存 |
@CacheEvict("users") | 清除缓存 |
Spring Boot 比 Spring 多的注解总结
- 启动与自动配置相关:
@SpringBootApplication、@EnableAutoConfiguration - 配置相关:
@ConfigurationProperties、@EnableConfigurationProperties - Web 相关:
@RestController、@GetMapping、@PostMapping - 测试相关:
@SpringBootTest、@MockBean - 条件装配相关:
@ConditionalOnClass、@ConditionalOnMissingBean - 监控与 Actuator:
@EnableScheduling、@Async、@EnableCaching
Spring Boot 最大的区别在于“自动化配置”和“简化开发”,相比于 Spring,减少了大量 XML 配置,并且提供了很多便捷的注解来快速构建应用。