Configuring ExponentialBackOffPolicy (using annotations)

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

For our example we will use the below service class

Service class


1  package defaultPackage;
2  
3  import java.util.Date;
4  
5  import org.springframework.retry.annotation.Backoff;
6  import org.springframework.retry.annotation.Retryable;
7  import org.springframework.stereotype.Service;
8  
9  @Service
10 public class Service15 {
11     private int i = 0;
12 
13     @Retryable(backoff = @Backoff(delay = 100, maxDelay = 300000, multiplier = 1200))
14     public void executeWithException() {
15         i = i + 1;
16         System.out.println("Executing method 'executeWithException' : " + i + " at " + new Date());
17         throw new NullPointerException();
18     }
19 }

As you can see in the above code, the method which has to be retried is annotated with “Retryable” annotation.

The “Retryable” annotation itself has “backoff” attribute which can be used to configure ExponentialBackOffPolicy.

We use another annotation “Backoff” to set the “backoff” attribute.

We need to set three attributes of “Backoff” annotation, which is “delay”, “maxDelay”, and “multiplier” as shown at line 13.

The value of “delay” and “maxDelay” will be in ms. The value of “multiplier” is simple integer.

In this way we can configure ExponentialBackOffPolicy using annotations.

Below is the main method which calls the above service class.

Main Class


package defaultPackage;

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;

@Configuration
@EnableRetry
public class Example36 {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Example36.class);
        Service15 service15 = (Service15) context.getBean("service15");

        try {
            service15.executeWithException();
        } catch(Exception excep) {
            excep.printStackTrace();
        }
    }

    @Bean(name="service15")
    public Service15 getService() {
        return new Service15();
    }
}

Leave a Reply