2015-12-17 40 views
0

我想設置一個非常簡單的測試,看看我是否可以得到彈簧重試API工作,但它似乎沒有按預期工作。以下是我的代碼/配置。我使用Spring 3.0春天重試不起作用

春重試版本中的pom.xml

<dependency> 
    <groupId>org.springframework.retry</groupId> 
    <artifactId>spring-retry</artifactId> 
    <version>1.1.2.RELEASE</version> 
</dependency> 

接口定義的類測試

public interface RetryTest 
{ 
    void test() throws Exception; 
} 

接口默認地將Impl

@Component("retryTest") 
@EnableRetry 
public class RetryTestImpl implements RetryTest 
{ 

    @Retryable(maxAttempts = 3) 
    public void test() throws Exception 
    { 
     System.out.println("try!"); 
     throw new Exception(); 
    } 
} 

JUnit類

public class TestIt 
{ 

    @Before 
    public void initSpringContext() 
    { 
     // Load the spring context 
     ApplicationContextUtil.initAppContext(MyConfig.class); 
    } 

    @Test 
    public void test_retryLogic() throws Exception 
    { 

     RetryTest retryTest = (RetryTest)ApplicationContextUtil.getApplicationContext().getBean(
      "retryTest"); 
     retryTest.test(); 
    } 

} 

控制檯輸出

Bean loaded: retryTest 
try! 

我期待的 「試試吧!」打印到控制檯3次。相反,拋出異常並且JUnit在那裏失敗。不應該重試運行3次?我在這裏錯過了什麼?

回答

1

您需要顯示您的MyConfig類。

@EnableRetry在您的@Configuration類之一上,而不是可重試目標。

查看Java文檔的批註:

* Global enabler for <code>@Retryable</code> annotations in Spring beans. If this is 
* declared on any <code>@Configuration</code> in the context then beans that have 
* retryable methods will be proxied and the retry handled according to the metadata in 
* the annotations.