Software Development

Using Spring Retry API

Did a method just throw an Exception? Well, we could re-invoke it a few times more before giving up using Spring’s Retry API. Last time we touched on BackOff and related interfaces and classes which is used in this API.


Stuff used in this post.

  • Spring Boot 1.5.4.RELEASE
  • spring-retry
    • we require this Maven dependency in our pom.xml
  • Java 8


Although there is this declarative option, we’ll not cover that here. It’s usage may be more related to Spring Batch as we are unable to override that annotation’s attributes. For instance, setting maxAttempts  like in the codes below don’t work and @Retryable  defaults to maxAttemptes = 3 .


Using the Retry API

There are essentially 4 things to consider when using this API:

  1. A method invocation that may fail.
  2. A method invocation to recover from a failure after n  retries.
  3. Methods’ return values
  4. Using RetryTemplate  class

Our Sample Codes

This is our service class. It has several methods for test with the API.

  1. Methods with return value
    • getAllCodes_ThrowException
      • Always throws an Exception
    • getAllCodes_Recovery
      • Recovery method
    • getAllCodes_Ok
      • Does not throw Exceptions
      • Always works and returns a list of String objects
  2. Methods with void return type
    • updateCode_ThrowException
      • Always throws an Exception
    • updateCode_Recovery
      • Recovery method
    • updateCode_Ok
      • Does not throw Exceptions


Next is our @Configuration  class. Notice I commented out stuff related to FixedBackOffPolicy and used ExponentialBackOffPolicy. Either one can be used interchangeably depending on our requirements.


Lastly, our main class. We’ll place the actual codes to test between /** Start **/  and /** End **/


With Return Value, Exception and Recovery method


With Return Value, Recovery Method, No Exception


Void Return Type, Exception, and Recovery Method


Void Return Type, Recovery Method, No Exception



Download the Codes

You Might Also Like