Spring Retry无法正常工作

时间:2015-12-17 19:58:34

标签: junit spring-retry

我正在尝试设置一个非常简单的测试,看看我是否可以使Springs Retry API工作,但它似乎没有按预期工作。以下是我的代码/配置。我使用的是Spring 3.0

在POM.xml中定义的Spring Retry Version

<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 Class

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!

我期待&#34;尝试!&#34;要打印到控制台3次。而是抛出异常并且JUnit在那里失败。不应该重试3次?我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

您需要展示MyConfig课程。

@EnableRetry上有一个@Configuration类,而不是可重试的目标。

请参阅java doc以获取注释:

 * 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.