Spring Retry: method annotated with @Recover not being called

I finally got the answer.

For a method annotated with @Recover to be invoked, it has to have the same method argument(plus the exception) and the same return type.

I tested it with different type of exception argument and methods are called if they have more specific exception type. If I have a method like this will be called than one with Exception argument. However, if I have multiple recover methods, only one with the more specific exception argument will be called.

@Recover
public String helpHere(ArithmeticException cause) {

Final code Example

package hello;

import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@Service
public class SomeService {

@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 3000))
public String getInfo() {
        try {
        System.out.println("How many time will this be printed?");
        return "Hello" + 4/0;
    } catch(Exception ex) {
            System.out.println("In the arthemetic Exception");
            throw new ArithmeticException();
    }   
}

@Recover
public String helpHere(ArithmeticException cause) {

        System.out.println("Recovery place! ArithmeticException");
        return "Hello";
}
@Recover
public String helpHere(Exception cause ) {

        System.out.println("Recovery place! Exception");
        return "Hello";
}

@Recover
public String helpHere() {
        System.out.println("Recovery place! Exception");
        return "Hello";
}

@Recover
public String helpHere(Throwable cause) {

        System.out.println("Recovery place! Throwable");
        return "Hello";
}

enter image description here


You should use try-catch to handle it. Here the example

@Retryable(value = ArithmeticException.class, maxAttempts = 5, backoff = @Backoff(delay = 3000))
    public String getInfo() {
        try {
            System.out.println("How many time will this be printed?");
            return "Hello" + 4 / 0;
        } catch (ArithmeticException ex) {
            // will be retried
            throw ex;
        }
    }

throw ex; is a must as it is telling Spring to apply retry handling. With @Recover we define a separate recovery method for ArithmeticException. This allows us to run special recovery code when a retryable method fails with ArithmeticException.

You may refer more on How to handle retry with Spring-Retry ?

Edit

Based on the latest exception,try provide version for spring-retry

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