本文详解 spring `@retryable` 注解在单元测试中失效的典型原因,重点剖析代理机制限制、测试配置误区及 ide 干扰问题,并提供可立即验证的完整测试方案。
Spring 的 @Retryable 是一个强大且常用的声明式重试机制,但其底层依赖 Spring AOP 代理(默认为 JDK 动态代理或 CGLIB),这导致它仅对通过 Spring 容器注入的 Bean 调用生效——即必须满足“外部 Bean 调用目标 Bean 的 @Retryable 方法”这一前提。若直接在测试类中 new 实例、或通过非代理对象调用(如 this.accessorMethod()),重试逻辑将完全被绕过。
你当前的测试结构看似合理,但存在几个关键隐患:

你的测试方法中:
@Test
public void serviceMethodRetryTest() {
try {
this.myService.serviceMethod(this.parameter); // ✅ 正确:通过代理 Bean 调用
} catch (UncategorizedSQLException exception) {
log.error("Error while executing test: {}", exception.getMessage());
}
}表面看符合要求,但实际可能因以下原因失败:
@SpringBootTest(classes = {TestConfig.class})
@Import(TestRetryConfiguration.class)
class MyServiceTest {
@Autowired
private MyService myService;
@MockBean
private MyAccessor myAccessor; // 关键:Mock 出问题并控制行为
@Test
void serviceMethodRetryTest() {
// 模拟 accessorMethod 连续 2 次抛出 SQLException,第 3 次成功
given(myAccessor.accessorMethod("test"))
.willThrow(new SQLException("DB timeout")) // 第1次
.willThrow(new SQLException("DB timeout")) // 第2次
.willReturn("success"); // 第3次
String result = myService.serviceMethod("test");
assertThat(result).isEqualTo("success");
// 验证重试次数(需自定义 RetryListener 记录调用)
verify(myAccessor, times(3)).accessorMethod("test");
}
}@Retryable 失效绝大多数情况并非 Spring Bug,而是因:① 代理未生效(非 Spring Bean 调用);② 异常类型不匹配;③ 测试环境配置缺失;④ IDE 缓存污染。遵循“Spring Bean 间调用 + 显式异常抛出 + 合理 Mock + 清理 IDE 缓存”四步法,即可稳定验证重试逻辑。