
Spring Retry 的 @Retryable 注解中 maxAttempts 不生效(如设为3却执行9次),根本原因在于 @EnableRetry 被错误地添加到了含 @Bean 方法的配置类中,导致 Spring 创建了多个 RetryTemplate 实例或代理冲突;正确做法是仅在纯 @Configuration 类上声明 @EnableRetry,且不定义任何 @Bean 方法。
spring retry 的 `@retryable` 注解中 `maxattempts` 不生效(如设为3却执行9次),根本原因在于 `@enableretry` 被错误地添加到了含 `@bean` 方法的配置类中,导致 spring 创建了多个 `retrytemplate` 实例或代理冲突;正确做法是仅在纯 `@configuration` 类上声明 `@enableretry`,且不定义任何 `@bean` 方法。
在 Spring Boot 项目中,@Retryable 表面配置简洁,但其底层依赖 RetryAnnotationBeanPostProcessor 的单例注册与 AOP 代理链完整性。一旦 @EnableRetry 所在的配置类同时声明了 @Bean(例如你代码中的 retryConfiguration()),Spring 容器可能因配置类的“角色混淆”而重复初始化重试基础设施——典型表现为 RetryTemplate 被多次创建、RetryContext 状态错乱,最终导致重试计数器(count)异常复位或叠加,出现 maxAttempts=3 却执行 9 次的“指数级重试”现象。
✅ 正确配置方式(推荐):
@Configuration
@EnableRetry // ✅ 唯一且纯净:仅启用重试,不混入@Bean定义
public class RetryConfig {
// 无需@Bean方法;所有重试策略应通过@Retryable注解或自定义RetryTemplate Bean显式配置
}
⚠️ 错误模式(即你原始代码的问题根源):
@Configuration
@EnableRetry // ❌ 危险!此注解与@Bean共存时,可能触发多次RetryAnnotationBeanPostProcessor注册
public class RetryConfig {
@Bean // ❌ 导致容器对同一配置类进行多阶段处理,破坏重试上下文一致性
public RetryConfiguration retryConfiguration() {
return new RetryConfiguration();
}
}
? 日志佐证分析:
观察你提供的日志片段,可清晰看到 Retry: count=0 多次重复出现(如 18:15:42.297, 18:15:45.309, 18:15:48.314),且每次 count=0 后都紧跟着新一轮 count=1→2→3。这表明重试上下文被反复重置,而非连续计数——正是 @EnableRetry 配置污染引发的典型症状。
? 补充关键注意事项:
-
调用必须走 Spring 代理:确保
checkMethod()是通过@Autowired注入的 Bean 调用,而非this.checkMethod()或手动new实例,否则 AOP 代理失效,重试完全不触发; -
异常类型需精确匹配:
@Retryable(retryFor = DatabaseOperationException.class)仅对该异常及其子类重试;若抛出的是其父类(如RuntimeException),需调整retryFor或使用include; -
避免在 Controller 层直接调用重试方法:Controller 应专注请求编排,重试逻辑应下沉至 Service 层,并确保 Service 是 Spring 管理的
@Service或@ComponentBean; -
如需自定义重试模板,应在独立配置类中定义
@Bean,并与@EnableRetry分离:@Configuration public class RetryTemplateConfig { @Bean public RetryTemplate retryTemplate() { RetryTemplate template = new RetryTemplate(); template.setRetryPolicy(new SimpleRetryPolicy(3)); // 显式控制次数 template.setBackOffPolicy(new FixedBackOffPolicy(100)); return template; } }
? 总结:Spring Retry 的稳定性高度依赖配置的“单一职责”。@EnableRetry 是开关,不是容器;它必须独占一个纯净的 @Configuration 类。修复后,maxAttempts=3 将严格执行 3 次(含首次调用),日志中 Retry: count 会线性递增至 count=2 后终止,并由 @Recover(如有)接管最终兜底逻辑。










