Spring-Retry在实现接口时无法定位恢复方法

Aez*_*zio 4 java spring spring-retry spring-boot

我在用 spring boot 做 spring-retry 时发现了一个问题。类实现接口时,超过最大重试次数后无法进入@recover方法。但是当我注入一个普通的类时,我可以进入这个方法。您的及时帮助和善意的建议将不胜感激,谢谢!

当我这样做时,我可以进入@Recover 方法

@Service
public class TestService {

    @Retryable(Exception.class)
    public String retry(String c) throws Exception{
        throw new Exception();
    }

    @Recover
    public String recover(Exception e,String c) throws Exception{
        System.out.println("got error");
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是一旦类实现了另一个接口,它就不起作用了

@Service
public class TestService implements TestServiceI{

    @Override
    @Retryable(Exception.class)
    public String retry(String c) throws Exception{
        throw new Exception();
    }

    @Recover
    public String recover(Exception e,String c) throws Exception{
        System.out.println("got error");
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

M. *_*num 6

Spring-Retry 使用 AOP 来实现@Retry. 使用 AOP 时,默认使用 JDK 动态代理。JDK 动态代理是基于接口的。

这意味着您将获得一个动态创建的类,该类伪装成 aTestServiceI但它不是TestService. 代理不包含该recover方法(因为它不在接口上),因此 Spring Retry 无法检测到它。

要解决此问题,您需要通过将proxyTargetClass属性设置@EnableRetrytrue( 请参阅javadoc )来为 Spring Retry 启用基于类的代理。

@EnableRetry(proxyTargetClass=true) 
Run Code Online (Sandbox Code Playgroud)