簡體   English   中英

Spring-Retry在實現接口時無法定位恢復方法

[英]Spring-Retry cannot locate recovery method when implement an interface

我在用 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;
    }
}

但是一旦類實現了另一個接口,它就不起作用了

@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;
    }
}

Spring-Retry 使用 AOP 來實現@Retry 使用 AOP 時,默認使用 JDK 動態代理。 JDK 動態代理是基於接口的。

這意味着您將獲得一個動態創建的類,它偽裝成TestServiceI但它不是TestService 代理不包括recover方法(因為它不在接口上),因此 Spring Retry 無法檢測到它。

要解決,你需要通過設置來啟用春重試基於類的代理proxyTargetClass的屬性@EnableRetrytrue (見的javadoc )。

@EnableRetry(proxyTargetClass=true) 
  1. 標記 proxyTargetClass=true: @EnableRetry(proxyTargetClass = true)
  2. @Recover 方法必須返回與原始方法相同的類型;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM