Loading... # Spring Boot 常用注解速查与最佳实践(精炼落地版) > 目标:一页掌握 @SpringBootApplication、@ConfigurationProperties、@RestController、@Transactional、@EnableScheduling/@Scheduled、@EnableCaching/@Cacheable、测试相关注解,配可复制代码与解释。🙂 ## 一、全局脑图(vditor 支持) ```mindmap * Spring Boot 注解速查 * 启动与装配 * @SpringBootApplication * @Configuration @Bean * 配置绑定 * @ConfigurationProperties * @ConfigurationPropertiesScan * Web/MVC * @RestController @Controller * @RequestMapping/@GetMapping... * @PathVariable @RequestParam @RequestBody * @Validated + jakarta.validation * 数据与事务 * @Transactional * 计划任务 * @EnableScheduling @Scheduled * 缓存 * @EnableCaching @Cacheable @CacheEvict * 测试 * @SpringBootTest @MockBean(迁移提示) ``` --- ## 二、启动与装配 🚀 ```java // 入口类 @SpringBootApplication public class App { public static void main(String[] args){ org.springframework.boot.SpringApplication.run(App.class, args); } } ``` **解释** * @SpringBootApplication 组合了 **@EnableAutoConfiguration + @ComponentScan + @Configuration**,一键开启自动装配与组件扫描,简化启动类编写。([Home](https://docs.spring.io/spring-boot/reference/using/using-the-springbootapplication-annotation.html?utm_source=chatgpt.com "Using the @SpringBootApplication Annotation")) * Spring Boot 3 基于 **Spring Framework 6**,要求 **Java 17**,大量 API 迁移到 **jakarta.\*** 命名空间(如校验、Servlet)。([InfoQ](https://www.infoq.com/news/2022/11/spring-6-spring-boot-3-launch/?utm_source=chatgpt.com "Spring Boot 3 and Spring Framework 6 Use Java 17 ..."), [GitHub](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide?utm_source=chatgpt.com "Spring Boot 3.0 Migration Guide")) --- ## 三、配置绑定(类型安全配置)🧩 ```java // 1) 类型安全配置 @org.springframework.boot.context.properties.ConfigurationProperties(prefix="app") @org.springframework.validation.annotation.Validated public record AppProps(@jakarta.validation.constraints.NotBlank String name, @jakarta.validation.constraints.PositiveOrZero int workers){} // 2) 扫描注册:可放在入口类 @org.springframework.boot.context.properties.ConfigurationPropertiesScan class ScanMarker {} ``` **解释** * @ConfigurationProperties 将 `app.*` 前缀配置**绑定**到类字段,支持校验;record 适合不可变配置。([Home](https://docs.spring.io/spring-boot/3.4.4/api/java/org/springframework/boot/context/properties/ConfigurationProperties.html?utm_source=chatgpt.com "ConfigurationProperties (Spring Boot 3.4.8 API)")) * @ConfigurationPropertiesScan 自动发现带注解的配置类;如不扫描,也可通过 `@EnableConfigurationProperties(AppProps.class)` 显式启用。([Home](https://docs.spring.io/spring-boot/how-to/properties-and-configuration.html?utm_source=chatgpt.com "Properties and Configuration :: Spring Boot")) * Boot 3 统一使用 **jakarta.validation** 注解(例如 `@NotBlank`),迁移时注意包名变化。([GitHub](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide?utm_source=chatgpt.com "Spring Boot 3.0 Migration Guide")) --- ## 四、Web/MVC(控制器与参数绑定)🌐 ```java @RestController @RequestMapping("/api/user") public class UserController { @GetMapping("/{id}") public UserDTO find(@PathVariable Long id){ /* 查询并返回 */ return new UserDTO(id, "Alice"); } @PostMapping(consumes="application/json") public UserDTO create(@Validated @RequestBody CreateUserCmd cmd){ /* 校验并创建 */ return new UserDTO(1L, cmd.name()); } public record CreateUserCmd(@jakarta.validation.constraints.Size(min=2,max=32) String name){} } ``` **解释** * @RestController = `@Controller + @ResponseBody`,方法返回值直接序列化为 JSON。([Baeldung on Kotlin](https://www.baeldung.com/spring-controller-vs-restcontroller?utm_source=chatgpt.com "The Spring @Controller and @RestController Annotations")) * @RequestMapping/@GetMapping/@PostMapping 用于 URL 与方法映射;`@GetMapping` 是 `@RequestMapping(method=GET)` 的简洁形式。([Home](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html?utm_source=chatgpt.com "Mapping Requests :: Spring Framework"), [Stack Overflow](https://stackoverflow.com/questions/39077787/difference-between-the-annotations-getmapping-and-requestmappingmethod-requ/39077941?utm_source=chatgpt.com "Difference between the annotations @GetMapping and ...")) * @PathVariable/@RequestBody/@Validated 组合完成路径参数与请求体绑定并触发 **Jakarta Bean Validation** 校验。([Home](https://docs.spring.io/spring-framework/reference/core/validation/beanvalidation.html?utm_source=chatgpt.com "Java Bean Validation")) --- ## 五、事务(读写分离与边界清晰)💾 ```java @Service public class OrderService { @Transactional(readOnly = true) public Order findById(Long id){ /* 只读查询,避免不必要的写事务 */ return ...; } @Transactional(timeout = 5, rollbackFor = Exception.class) public void place(PlaceCmd cmd){ /* 下单:写事务,含回滚策略与超时 */ } @Transactional(propagation = Propagation.REQUIRES_NEW) public void logAudit(Audit a){ /* 新事务:与主业务隔离 */ } } ``` **解释** * @Transactional 声明式事务:`readOnly` 优化只读场景;`timeout/rollbackFor` 精细控制;`propagation` 决定逻辑/物理事务边界(如 `REQUIRES_NEW` 独立提交)。([Home](https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/tx-propagation.html?utm_source=chatgpt.com "Transaction Propagation :: Spring Framework")) * 牢记**传播行为**与**隔离级别**会影响并发一致性与锁持有时间。([Home](https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/tx-propagation.html?utm_source=chatgpt.com "Transaction Propagation :: Spring Framework")) --- ## 六、计划任务(定时与速率)⏱️ ```java @EnableScheduling @Configuration class SchedulerConfig {} @Component class ReportJob { @Scheduled(cron="0 0/5 * * * ?") // 每5分钟执行 public void cronReport(){ /* 生成报表 */ } @Scheduled(fixedRate=10_000) // 上次开始10秒后再触发 public void rateTask(){ /* 拉取指标 */ } } ``` **解释** * @EnableScheduling 开启调度能力;@Scheduled 支持 `cron`、`fixedRate`、`fixedDelay` 等多种触发方式。([Home](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html?utm_source=chatgpt.com "Annotation Interface EnableScheduling"), [Home](https://spring.io/guides/gs/scheduling-tasks?utm_source=chatgpt.com "Getting Started | Scheduling Tasks")) * 任务方法通常**无参数且返回值忽略**,推荐幂等并增加超时保护。([Baeldung on Kotlin](https://www.baeldung.com/spring-scheduled-tasks?utm_source=chatgpt.com "The @Scheduled Annotation in Spring")) --- ## 七、缓存(开箱即用的性能杠杆)⚡ ```java @EnableCaching @Configuration class CacheConfig {} @Service class ProductService { @Cacheable(cacheNames="prod", key="#id") public Product find(long id){ /* 首次查库,结果进入缓存;后续命中 */ return ...; } @CacheEvict(cacheNames="prod", key="#p.id") public void update(Product p){ /* 更新后清理缓存,防止脏读 */ } } ``` **解释** * @EnableCaching 打开缓存抽象;@Cacheable 读缓存,@CacheEvict 写后清理;支持多实现(Caffeine/Redis 等)。([Home](https://docs.spring.io/spring-boot/reference/io/caching.html?utm_source=chatgpt.com "Caching :: Spring Boot")) * 生产中务必定义**一致的 key** 与**过期策略**,避免雪崩与穿透。 --- ## 八、测试(上下文与替身)🧪 ```java @SpringBootTest class UserApiTest { @org.springframework.boot.test.mock.mockito.MockBean // Boot 3.4 标注:未来由 @MockitoBean 接替 private UserService userService; @Test void ok(){ when(userService.greet()).thenReturn("hi"); // 断言控制器返回等... } } ``` **解释** * @SpringBootTest 启动完整应用上下文,适合集成测试;如仅测 MVC 层可选 `@WebMvcTest`。([Medium](https://medium.com/simform-engineering/testing-spring-boot-applications-best-practices-and-frameworks-6294e1068516?utm_source=chatgpt.com "Testing Spring Boot Applications: Best Practices")) * @MockBean 向容器注册 Mockito 替身;**Boot 3.4 起计划在 4.0 移除**,迁移至 `@MockitoBean`(同语义)。([Home](https://docs.spring.io/spring-boot/api/java/org/springframework/boot/test/mock/mockito/MockBean.html?utm_source=chatgpt.com "Annotation Interface MockBean")) --- ## 九、快捷对照表(vditor 支持) | 场景 | 核心注解 | 要点/陷阱 | | ---- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 启动 | @SpringBootApplication | 组合注解,自动装配与扫描一次到位。([Home](https://docs.spring.io/spring-boot/reference/using/using-the-springbootapplication-annotation.html?utm_source=chatgpt.com "Using the @SpringBootApplication Annotation")) | | 配置 | @ConfigurationProperties | 类型安全 + 校验;Boot 3 用**jakarta.validation**。([Home](https://docs.spring.io/spring-boot/3.4.4/api/java/org/springframework/boot/context/properties/ConfigurationProperties.html?utm_source=chatgpt.com "ConfigurationProperties (Spring Boot 3.4.8 API)"),[GitHub](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide?utm_source=chatgpt.com "Spring Boot 3.0 Migration Guide")) | | MVC | @RestController / @GetMapping | 简化返回 JSON;方法映射有快捷注解。([Home](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html?utm_source=chatgpt.com "Mapping Requests :: Spring Framework")) | | 事务 | @Transactional | readOnly/传播/隔离级别要清楚。([Home](https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/tx-propagation.html?utm_source=chatgpt.com "Transaction Propagation :: Spring Framework")) | | 调度 | @EnableScheduling/@Scheduled | cron 与 fixedRate/fixedDelay 区别。([Home](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html?utm_source=chatgpt.com "Annotation Interface EnableScheduling")) | | 缓存 | @EnableCaching/@Cacheable | 定义 key 与失效策略,避免脏数据。([Home](https://docs.spring.io/spring-boot/reference/io/caching.html?utm_source=chatgpt.com "Caching :: Spring Boot")) | | 测试 | @SpringBootTest/@MockBean | 关注 @MockBean 的未来替代。([Home](https://docs.spring.io/spring-boot/api/java/org/springframework/boot/test/mock/mockito/MockBean.html?utm_source=chatgpt.com "Annotation Interface MockBean")) | --- ## 十、请求到数据的工作流程(mermaid) ```mermaid flowchart LR A[HTTP 请求] --> B[@RestController 方法] B --> C[参数绑定 + @Validated] C --> D[@Transactional Service] D --> E[Repository/DB] D --> F[@Cacheable 命中?] F -->|是| G[直接返回] F -->|否| E --> H[回写缓存] --> G ``` > 小结:先把**启动/装配**与**Web/事务/计划/缓存**这 6 组注解熟练到肌肉记忆;Boot 3+ 全面使用 **jakarta.\***,并确保 Java 17 环境。以上示例与解释按 2025 年最新文档与指南编写,可直接套用到项目。([InfoQ](https://www.infoq.com/news/2022/11/spring-6-spring-boot-3-launch/?utm_source=chatgpt.com "Spring Boot 3 and Spring Framework 6 Use Java 17 ..."), [GitHub](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide?utm_source=chatgpt.com "Spring Boot 3.0 Migration Guide")) > 最后修改:2025 年 08 月 27 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏