15.SpringBoot注解指南
Spring Boot 注解指南 目录 点击展开目录 Spring Boot 注解指南 目录 核心注解 应用程序相关 组件注解 配置相关注解 配置属性 Bean配置 Web相关注解 请求映射 请求参数 响应处理 数据库相关注解 JPA注解 MyBatis注解 缓存相关注解 安全相关注解 测试相关注解 其他常用注解 依赖注入 切面编程 异步处理 定时任务 验证注解 并发与异步处理注解 异步执行 线程池配置 异步事件处理 重试机制 并发控制 异步任务配置示例 异步任务使用示例 最佳实践建议 注意事项 高级注解使用指南 条件注解 配置属性绑定 日志配置 参数验证 缓存注解 事务管理 安全注解 监控和度量 最佳实践建议 JPA注解详解 实体映射注解 关联关系注解 继承策略注解 查询注解 审计注解 验证注解 复合主键注解 二级缓存注解 最佳实践建议 核心注解 应用程序相关 @SpringBootApplication // 包含@Configuration、@EnableAutoConfiguration和@ComponentScan // 标记主类,Spring Boot应用程序的入口 @EnableAutoConfiguration // 启用Spring Boot的自动配置机制 @ComponentScan // 自动扫描并注册符合条件的组件 @Configuration // 标记配置类,通常与@Bean结合使用 组件注解 @Component // 通用组件注解,标记类为Spring组件 @Service // 标记服务层组件 @Repository // 标记数据访问层组件 @Controller // 标记控制器组件(Spring MVC) @RestController // @Controller和@ResponseBody的组合,用于RESTful Web服务 配置相关注解 配置属性 @ConfigurationProperties(prefix = "app") // 绑定外部配置到类属性 @Value("${property.name}") // 注入配置属性值 @PropertySource("classpath:custom.properties") // 指定配置文件位置 Bean配置 @Bean // 声明一个Bean,通常在@Configuration类中使用 @Scope("singleton") // 指定Bean的作用域(singleton/prototype/request/session) @Conditional // 条件化地创建Bean @Profile("dev") // 指定Bean在特定Profile下创建 Web相关注解 请求映射 @RequestMapping("/path") // 通用请求映射 @GetMapping("/path") // GET请求映射 @PostMapping("/path") // POST请求映射 @PutMapping("/path") // PUT请求映射 @DeleteMapping("/path") // DELETE请求映射 @PatchMapping("/path") // PATCH请求映射 请求参数 @RequestParam // 绑定请求参数 @RequestParam(value = "id", required = false, defaultValue = "0") private String id; @PathVariable // 绑定URL路径变量 @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) @RequestBody // 绑定请求体 @PostMapping("/users") public User createUser(@RequestBody User user) @RequestHeader // 绑定请求头 @CookieValue // 绑定Cookie值 响应处理 @ResponseBody // 将返回值序列化为响应体 @ResponseStatus(HttpStatus.OK) // 指定响应状态码 @ExceptionHandler(Exception.class) // 处理特定异常 @ControllerAdvice // 全局控制器增强,通常用于全局异常处理 数据库相关注解 JPA注解 @Entity // 标记JPA实体类 @Table(name = "users") // 指定数据库表名 @Id // 标记主键字段 @GeneratedValue // 主键生成策略 @Column // 指定列属性 @Transactional // 声明事务 MyBatis注解 @Mapper // 标记MyBatis映射器接口 @Select("SELECT * FROM users") // SQL查询语句 @Insert("INSERT INTO users(name) VALUES(#{name})") // SQL插入语句 @Update("UPDATE users SET name = #{name}") // SQL更新语句 @Delete("DELETE FROM users WHERE id = #{id}") // SQL删除语句 缓存相关注解 @Cacheable // 缓存方法返回值 @Cacheable(value = "users", key = "#id") public User getUser(Long id) @CacheEvict // 清除缓存 @CacheEvict(value = "users", allEntries = true) public void clearCache() @CachePut // 更新缓存 @CachePut(value = "users", key = "#user.id") public User updateUser(User user) @EnableCaching // 启用缓存支持 安全相关注解 @Secured("ROLE_ADMIN") // 基于角色的安全控制 @PreAuthorize("hasRole('ADMIN')") // 方法执行前的权限检查 @PostAuthorize("returnObject.username == authentication.name") // 方法执行后的权限检查 @RolesAllowed({"USER", "ADMIN"}) // 指定允许访问的角色 测试相关注解 @SpringBootTest // Spring Boot测试类 @Test // 测试方法 @MockBean // 模拟Bean @AutoConfigureMockMvc // 配置MockMvc @WebMvcTest // MVC测试 @DataJpaTest // JPA测试 其他常用注解 依赖注入 @Autowired // 自动注入依赖 @Qualifier("beanName") // 指定注入的Bean名称 @Resource // 按名称注入 @Inject // JSR-330依赖注入 切面编程 @Aspect // 声明切面 @Before("execution(* com.example.service.*.*(..))") // 前置通知 @After // 后置通知 @Around // 环绕通知 @AfterReturning // 返回通知 @AfterThrowing // 异常通知 异步处理 @EnableAsync // 启用异步处理 @Async // 标记异步方法 定时任务 @EnableScheduling // 启用定时任务 @Scheduled(fixedRate = 5000) // 定时执行,固定速率 @Scheduled(cron = "0 0 12 * * ?") // 使用cron表达式定时执行 验证注解 @Valid // 触发验证 @NotNull // 非空验证 @Size(min = 2, max = 30) // 字符串长度验证 @Email // 邮箱格式验证 @Pattern(regexp = "^[0-9]{10}$") // 正则表达式验证 并发与异步处理注解 异步执行 @EnableAsync // 在配置类上使用,启用异步功能 @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(25); executor.initialize(); return executor; } } @Async // 标记方法为异步执行 @Async public CompletableFuture<String> asyncMethod() { // 异步处理逻辑 return CompletableFuture.completedFuture("result"); } @Async("specificExecutor") // 指定使用特定的执行器 @Async("threadPoolTaskExecutor") public void asyncMethodWithExecutor() { // 使用指定执行器的异步处理 } 线程池配置 @EnableScheduling // 启用定时任务调度功能 @Scheduled // 配置定时任务 @Scheduled(fixedRate = 5000) // 固定速率执行 @Scheduled(fixedDelay = 5000) // 固定延迟执行 @Scheduled(initialDelay = 1000, fixedRate = 5000) // 初始延迟后固定速率执行 @Scheduled(cron = "0 0 12 * * ?") // 使用cron表达式 // 自定义线程池配置 @Configuration public class ThreadPoolConfig { @Bean public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); // 核心线程数 executor.setMaxPoolSize(20); // 最大线程数 executor.setQueueCapacity(200); // 队列容量 executor.setKeepAliveSeconds(60); // 线程空闲时间 executor.setThreadNamePrefix("async-"); // 线程名前缀 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略 executor.initialize(); return executor; } } 异步事件处理 @EventListener // 标记方法为事件监听器 @EventListener public void handleContextStart(ContextStartedEvent event) { // 处理事件 } @TransactionalEventListener // 在事务上下文中处理事件 @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void handleAfterCommit(CustomEvent event) { // 事务提交后处理事件 } @Async @EventListener // 异步事件处理 public void handleAsyncEvent(CustomEvent event) { // 异步处理事件 } 重试机制 @EnableRetry // 启用重试机制 @Configuration @EnableRetry public class RetryConfig { } @Retryable // 配置方法重试 @Retryable( value = {SQLException.class}, // 指定异常类型 maxAttempts = 3, // 最大重试次数 backoff = @Backoff(delay = 1000) // 重试延迟 ) public void retryableOperation() { // 可能失败的操作 } @Recover // 重试失败后的恢复方法 @Recover public void recover(SQLException e) { // 处理最终失败的情况 } 并发控制 @Lock // 分布式锁注解(需要集成相关实现,如Redisson) @Lock(key = "#userId", timeout = 10) public void processUserData(String userId) { // 需要加锁的处理逻辑 } // 自定义并发限制注解示例 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ConcurrencyLimit { int value() default 10; // 并发数限制 long timeout() default 1000; // 超时时间 } 异步任务配置示例 @Configuration public class AsyncTaskConfig { @Bean public AsyncTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程配置 executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(100); // 线程配置 executor.setThreadNamePrefix("Async-Task-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待任务完成配置 executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); return executor; } } 异步任务使用示例 @Service public class AsyncService { @Async public CompletableFuture<String> asyncMethodWithResult() { try { Thread.sleep(1000); return CompletableFuture.completedFuture("Async result"); } catch (InterruptedException e) { return CompletableFuture.failedFuture(e); } } @Async public void asyncMethodWithException() throws Exception { throw new Exception("Async method exception"); } // 异步方法组合示例 public CompletableFuture<String> combinedAsyncMethods() { CompletableFuture<String> future1 = asyncMethodWithResult(); CompletableFuture<String> future2 = asyncMethodWithResult(); return CompletableFuture.allOf(future1, future2) .thenApply(v -> future1.join() + " " + future2.join()); } } 最佳实践建议 // 1. 异常处理 @Async public CompletableFuture<String> asyncWithExceptionHandling() { try { // 异步处理逻辑 return CompletableFuture.completedFuture("result"); } catch (Exception e) { return CompletableFuture.failedFuture(e); } } // 2. 超时处理 @Async public CompletableFuture<String> asyncWithTimeout() { return CompletableFuture.supplyAsync(() -> { // 处理逻辑 return "result"; }).orTimeout(5, TimeUnit.SECONDS); } // 3. 异步任务进度跟踪 @Async public void asyncWithProgress(ProgressTracker tracker) { tracker.start(); // 处理逻辑 tracker.progress(50); // 更多处理 tracker.complete(); } 注意事项 @Async方法的返回类型: ...