Configuring FixedBackOfPolicy (using annotations)

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

For our example we will use the below service class

Service class


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

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 FixedBackOffPolicy.

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

The “Backoff” annotation has “delay” attribute which has to be set to literal value in ms.

In this way we can configure FixedBackOfPolicy using annotations.

Below is the main method which calls the above service class

Main class


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 Example34 {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Example34.class);
        Service13 service13 = (Service13) context.getBean("service13");

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

    @Bean(name="service13")
    public Service13 getService() {
        return new Service13();
    }
}

Leave a Reply