In a nutshell — Spring Retry

Udayabharathi Thiagarajan
2 min readJul 19, 2020

Spring Retry — Overview:

Spring Retry provides an ability to automatically re-invoke a failed operation. This is helpful to overcome transient errors (like a network glitch or a momentary issue with external system). It provides customizable, declarative control of the retry process and policy based behavior which is easy to extend. This works with the help of Spring’s AOP.

Implementation:

Implementation is pretty straight forward and it won’t require a lot of effort. Follow the steps for understanding.

  1. Add the following dependencies in your pom.xml/build.gradle file.

Maven (pom.xml):

<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>

Gradle (build.gradle):

compile group: 'org.springframework.retry', name: 'spring-retry'compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop', version: '2.3.1.RELEASE'

2. Add the following annotation in your Main/Configuration class.

@SpringBootApplication
@EnableRetry
public BlahBlahApplication {

public static void main(String[] args) {
SpringApplication.run(BlahBlahApplication.class, args);
}

}

3. Add the following annotation on top of the method which has to retry on a specific exception.

@Retryable(value = {BlahException.class}, maxAttempts = 3, backoff = @Backoff(delay = 5000))
public BlahBlahType blahBlahMethod(BlahBlahType blahBlahParam) {
...
}

Things to make sure before development:

  1. Exception should not be thrown from the method in which you’re retrying. If you throw the exception which you gave under @Retryable then Retry will not execute. Spring Retry will automatically throw the exception after max retries.
  2. Retryable Method should be public and calls to that method should be from external class (not even child class) for Retry to work.

References:

  1. Guide to Spring Retry by Baeldung
  2. Using @Retryable in methods define in spring bean’s base class are not retried

--

--