2016-10-28 5 views
1

SimpleRetryPolicy/RetryTemplateを使用して、単純なJavaクラスでSpringリトライフレームワークを試しました。それは正常に働いた。だから私は注釈でも同じことをやっていると思った。注釈は私のために働いたことはありません。オンラインで多くのヘルプを見つけられませんでした。次のコードは、通常のJavaプログラムのように、最初の試行で例外をスローしていましたが、これは期待される動作ではありません。例外を投げたり回復したりする前に、少なくとも5回は試してみたはずです。どこが間違っているのか分かりません。これを行うには、XML/AOPの設定を行う必要がありますか?どのようにそれはAnnotationが動作しないSpringリトライフレーム

import org.springframework.context.annotation.Configuration; 
import org.springframework.retry.annotation.EnableRetry; 

@EnableRetry 
@Configuration 
public class App { 
    public static void main(String[] args) throws Exception { 
     Parentservice p = new SpringRetryWithHystrixService(); 
     String status = p.getStatus(); 
     System.out.println(status); 
    } 
} 

import org.springframework.retry.annotation.Retryable; 
public interface Parentservice { 
    @Retryable(maxAttempts=5) 
    String getStatus() throws Exception; 
} 


import org.springframework.retry.annotation.Recover; 
public class SpringRetryWithHystrixService implements Parentservice{ 

    public static int i=0; 

    public String getStatus() throws Exception{ 
     System.out.println("Attempt:"+i++); 
     throw new NullPointerException(); 
    } 

     @Recover 
     public static String getRecoveryStatus(){ 
      return "Recovered from NullPointer Exception"; 
     } 
    } 

だろう、私はどんな違いがありませんでしたインタフェースと実装の上に@Retryable(maxAttempts = 5)を試してみました。

答えて

4

アプリケーション春によって管理する必要がある、あなただけのnew ...

Parentservice p = new SpringRetryWithHystrixService(); 

を使用することはできませんここでは春のブートアプリだ...

@SpringBootApplication 
@EnableRetry 
public class So40308025Application { 

    public static void main(String[] args) throws Exception { 
     ConfigurableApplicationContext context = SpringApplication.run(So40308025Application.class, args); 
     System.out.println(context.getBean(SpringRetryWithHystrixService.class).getStatus()); 
     context.close(); 
    } 

} 


@Component 
public class SpringRetryWithHystrixService { 

    public static int i = 0; 

    @Retryable(maxAttempts = 5) 
    public String getStatus() throws Exception { 
     System.out.println("Attempt:" + i++); 
     throw new NullPointerException(); 
    } 

    @Recover 
    public static String getRecoveryStatus() { 
     return "Recovered from NullPointer Exception"; 
    } 

} 

結果:

Attempt:0 
Attempt:1 
Attempt:2 
Attempt:3 
Attempt:4 
Recovered from NullPointer Exception 

何らかの理由でSpring Bootを使いたくない場合は、

@Configuration 
@EnableRetry 
public class So40308025Application { 

    public static void main(String[] args) throws Exception { 
     ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(So40308025Application.class); 
     System.out.println(context.getBean(SpringRetryWithHystrixService.class).getStatus()); 
     context.close(); 
    } 

    @Bean 
    public SpringRetryWithHystrixService service() { 
     return new SpringRetryWithHystrixService(); 
    } 

} 
+0

ありがとうございました。それが私の問題を解決しました。 – karthik

関連する問題