1. Spring Boot 核心注解概述
Spring Boot 作为 Java 生态中最流行的应用框架之一,其核心注解体系是开发者必须掌握的基础知识。这些注解不仅仅是语法糖,更是框架设计思想的体现,能够显著提升开发效率和代码质量。
在 Spring Boot 项目中,合理使用注解可以:
- 简化配置,告别繁琐的 XML
- 实现依赖注入和控制反转
- 快速构建 RESTful API
- 自动化事务管理
- 便捷处理数据验证
2. 启动类与核心配置注解
2.1 @SpringBootApplication
这是 Spring Boot 应用的基石注解,通常标注在主启动类上。它实际上是三个核心注解的组合:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan public @interface SpringBootApplication { // ... }实际开发中,我们推荐这样使用:
@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }注意事项:在微服务架构中,如果启动类需要额外配置组件扫描路径,可以使用
@ComponentScan的basePackages属性明确指定包路径,避免扫描不必要的包。
2.2 配置相关注解
@Configuration
标识一个类为配置类,替代传统的 XML 配置方式:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }@Bean
用于配置类中声明 Spring Bean:
@Bean public DataSource dataSource() { return new HikariDataSource(); }@PropertySource
加载指定配置文件:
@Configuration @PropertySource("classpath:custom.properties") public class CustomConfig { // ... }3. 依赖注入相关注解
3.1 组件扫描注解
Spring 通过以下注解自动发现和注册 Bean:
| 注解 | 用途 | 层级 |
|---|---|---|
| @Component | 通用组件注解 | 无特定层级 |
| @Service | 标识服务层组件 | 业务逻辑层 |
| @Repository | 标识数据访问组件 | 持久层 |
| @Controller | 标识控制器组件 | 表现层 |
| @RestController | @Controller + @ResponseBody | REST API |
3.2 依赖注入注解
@Autowired
按类型自动注入:
@Service public class UserServiceImpl implements UserService { // ... } @RestController public class UserController { @Autowired private UserService userService; }@Qualifier
当存在多个同类型 Bean 时指定名称:
@Repository("userRepoA") public class UserRepositoryA implements UserRepository {} @Repository("userRepoB") public class UserRepositoryB implements UserRepository {} @Service public class UserService { @Autowired @Qualifier("userRepoA") private UserRepository userRepo; }@Primary
设置首选注入的 Bean:
@Primary @Repository("userRepoA") public class UserRepositoryA implements UserRepository {}@Resource
JSR-250 标准注解,默认按名称注入:
@Service public class UserService { @Resource(name = "userRepoA") private UserRepository userRepo; }4. Web 开发相关注解
4.1 控制器相关
@RestController
组合注解,相当于 @Controller + @ResponseBody:
@RestController @RequestMapping("/api/users") public class UserController { // ... }4.2 请求映射注解
| 注解 | HTTP 方法 | 示例 |
|---|---|---|
| @GetMapping | GET | @GetMapping("/{id}") |
| @PostMapping | POST | @PostMapping |
| @PutMapping | PUT | @PutMapping("/{id}") |
| @DeleteMapping | DELETE | @DeleteMapping("/{id}") |
| @PatchMapping | PATCH | @PatchMapping("/{id}") |
4.3 请求参数处理
@PathVariable
获取路径参数:
@GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { // ... }@RequestParam
获取查询参数:
@GetMapping("/users") public List<User> getUsers(@RequestParam(required = false) String name) { // ... }@RequestBody
接收请求体 JSON:
@PostMapping("/users") public User createUser(@RequestBody @Valid UserCreateDTO dto) { // ... }@RequestHeader
获取请求头:
@GetMapping("/info") public String getInfo(@RequestHeader("User-Agent") String userAgent) { // ... }5. 数据校验注解
Spring Boot 支持 JSR-380 (Bean Validation 2.0) 规范:
5.1 常用校验注解
| 注解 | 作用 |
|---|---|
| @NotNull | 非空 |
| @NotEmpty | 非空且非空字符串/集合 |
| @NotBlank | 非空且至少一个非空白字符 |
| @Size | 长度限制 |
| @Min/@Max | 数值范围 |
| @Pattern | 正则校验 |
| 邮箱格式 |
使用示例:
public class UserDTO { @NotBlank @Size(max = 50) private String username; @Email private String email; @Min(18) @Max(100) private Integer age; }5.2 分组校验
public interface UpdateGroup {} public interface CreateGroup {} public class UserDTO { @Null(groups = UpdateGroup.class) @NotNull(groups = CreateGroup.class) private Long id; // ... } @PostMapping public void create(@Validated(CreateGroup.class) @RequestBody UserDTO dto) { // ... }6. 数据持久化注解
6.1 JPA 实体注解
@Entity
标识 JPA 实体类:
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; // getters/setters }6.2 字段映射
@Column
配置列属性:
@Column(name = "user_name", nullable = false, length = 50) private String username;@Enumerated
枚举类型映射:
@Enumerated(EnumType.STRING) private Gender gender; // 存储枚举名称而非序号6.3 关联关系
一对一关系
@Entity public class User { @OneToOne private Profile profile; }一对多关系
@Entity public class Order { @ManyToOne private User user; }7. 事务管理注解
@Transactional
声明式事务管理:
@Service public class OrderService { @Transactional(rollbackFor = Exception.class) public void placeOrder(Order order) { // ... } }关键属性:
propagation: 事务传播行为isolation: 隔离级别timeout: 超时时间readOnly: 是否只读
8. 测试相关注解
8.1 单元测试
@SpringBootTest @ActiveProfiles("test") public class UserServiceTest { @Autowired private UserService userService; @Test @Transactional public void testCreateUser() { // ... } }8.2 Mock 测试
@WebMvcTest(UserController.class) public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test public void testGetUser() throws Exception { // ... } }9. 高级特性注解
9.1 异步处理
@Async public void asyncTask() { // 异步执行 } @EnableAsync @Configuration public class AsyncConfig { @Bean public Executor taskExecutor() { // 配置线程池 } }9.2 定时任务
@Scheduled(cron = "0 0 12 * * ?") public void dailyReport() { // 每天中午执行 } @EnableScheduling @SpringBootApplication public class MyApp { // ... }10. 自定义注解开发
Spring Boot 支持开发者创建自己的注解:
10.1 定义注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AuditLog { String action(); String module(); }10.2 实现处理逻辑
@Aspect @Component public class AuditLogAspect { @Around("@annotation(auditLog)") public Object around(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable { // 前置处理 Object result = joinPoint.proceed(); // 后置处理 return result; } }10.3 使用自定义注解
@RestController public class UserController { @AuditLog(action = "create", module = "user") @PostMapping("/users") public User createUser(@RequestBody User user) { // ... } }掌握这些核心注解后,开发者可以更高效地构建 Spring Boot 应用。实际开发中,建议根据项目需求选择合适的注解组合,并遵循一致的注解使用规范。