Software Development, Spring, Spring Boot

Retry Operation at specific Exception using Spring Retry

Spring-Retry allows us to retry operations when the codes encounter exceptions. How do we limit the retries to specific exceptions only? For instance, we wouldn’t want to retry SOAP Web Service operations. The operations may throw exceptions due to invalid values or internal errors on the remote services. We would want to retry those operations just because of connectivity issues. We also want to retry operations because the server was busy, etc. This post shows how Spring can retry operations only for specific exceptions.

For Starters

Before we proceed, please go over these posts to better understand this post.

Retry Operation Only for Specific Exception

When we want to retry operations in Spring, we use the RetryTemplate, which we can use in a Java Configuration. Consider the following codes. They create an object of RetryTemplate with some attributes. For example, the backOffPeriod.

When we create a RetryTemplate object, it is important to set its retryPolicy. In our case, we have a custom retry policy to meet our needs – retry on a specific exception.

The class definition of a Retry Policy looks like the following. In the class, we define the number of maximum attempts and the triggering exception. When there is no exception, the codes use the NeverRetryPolicy, and there will be no retry of operations.

With these, the call to our remote services looks something like the following. We have a public method which is the entry point that has our retry logic implementation.

Within our public method, we call methods that may require trying.

Tested on

We tested the codes using the following items. The codes may need changing when using later versions of the Spring Framework and Spring Retry module.

  • Spring Framework 3.0.7.RELEASE
  • Spring Retry 1.0.3.RELEASE
  • Java 8


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like