我在用 spring boot 做 spring-retry 時發(fā)現(xiàn)了一個問題。類實現(xiàn)接口時,超過最大重試次數(shù)后無法進入@recover方法。但是當(dāng)我注入一個普通的類時,我可以進入這個方法。您的及時幫助和善意的建議將不勝感激,謝謝!當(dāng)我這樣做時,我可以進入@Recover 方法@Servicepublic 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; }}但是一旦類實現(xiàn)了另一個接口,它就不起作用了@Servicepublic 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; }}
2 回答

猛跑小豬
TA貢獻1858條經(jīng)驗 獲得超8個贊
Spring-Retry 使用 AOP 來實現(xiàn)@Retry
. 使用 AOP 時,默認使用 JDK 動態(tài)代理。JDK 動態(tài)代理是基于接口的。
這意味著您將獲得一個動態(tài)創(chuàng)建的類,該類偽裝成 aTestServiceI
但它不是TestService
. 代理不包含該recover
方法(因為它不在接口上),因此 Spring Retry 無法檢測到它。
要解決此問題,您需要通過將proxyTargetClass
屬性設(shè)置@EnableRetry
為true
( 請參閱javadoc )來為 Spring Retry 啟用基于類的代理。
@EnableRetry(proxyTargetClass=true)

aluckdog
TA貢獻1847條經(jīng)驗 獲得超7個贊
標(biāo)記 proxyTargetClass=true: @EnableRetry(proxyTargetClass = true)
@Recover 方法必須返回與原方法相同的類型;
添加回答
舉報
0/150
提交
取消