Configuring Recovery Callback (using annotations)

In this post under Spring Retry, I will show with example how to configure a Recovery callback using annotations.

Spring Retry retries fail operations for fixed number of times. If the operations fails even after last attempt, we don’t have any other option but to recover from that failure.

Spring Retry provides an annotation that can be used to mark a method as recovery method and it will be executed when multiple retry operations fails.

Name of the annotation is “@Recover”.

Below is the Service class that uses the annotation


1  import org.springframework.retry.annotation.Recover;
2  import org.springframework.retry.annotation.Retryable;
3  import org.springframework.stereotype.Service;
5  @Service
6  public class Service10 {
7      private int i = 0;
9      @Retryable
10     public void executeWithException() {
11         i = i + 1;
12         System.out.println("Executing method 'executeWithException' : " + i);
13         throw new NullPointerException();
14     }
16     @Recover
17     public void recover() {
18         System.out.println("Recovered");
19     }
20 }

In the above service class, at line 16, we use the “@Recover” annotation on the method “recover”. As a result “recover” method is marked as recovery method.

In this way we can mark a method as recovery method using an annotation.

Below is the complete main class code that will call the above service class.

Main class

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;

public class Example31 {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Example31.class);
        Service10 service10 = (Service10) context.getBean("service10");

        try {
        } catch(Exception excep) {

    public Service10 getService() {
        return new Service10();

Below is the output for your reference


[INFO] AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7e6cbb7a: startup date [Sat Jun 18 09:01:48 IST 2022]; root of context hierarchy
Executing method 'executeWithException' : 1
Executing method 'executeWithException' : 2
Executing method 'executeWithException' : 3


Press like button if you like the post. Also share your opinion regarding posts through comments. Also mention what other framework you want me to cover through comments.

Leave a Reply