MaxAttemptsRetryPolicy Example (using xml configuration)

In this post under Spring Retry, I will talk about MaxAttemptsRetryPolicy with example.

MaxAttemptsRetryPolicy allows us to configure Spring Retry to retry a failed operation for fixed number of times (including the initial attempt).

Below is the xml file showing how to configure MaxAttemptsRetryPolicy

XML code


1  <?xml version="1.0" encoding="UTF-8"?>
2  <beans xmlns="http://www.springframework.org/schema/beans"
3  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
5      <bean id="retryPolicy" class="org.springframework.retry.policy.MaxAttemptsRetryPolicy">
6          <property name="maxAttempts" value="5"/>
7      </bean>
8      
9      <bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
10         <property name="retryPolicy" ref="retryPolicy"/>
11     </bean>
12     
13     <bean id="service1" class="Service1"/>
14 </beans>

In the above xml code, at line 5 we create bean named “retryPolicy” for MaxAttemptsRetryPolicy class and set it “maxAttempts” property to 5. This says an instance of MaxAttemptsRetryPolicy to retry a
failed operation 5 times.

Below is the service class and main class for your reference.

Service class


public class Service1 {
    private int i = 0;
    private int j = 0;

    public void executeWithException() {
        i = i + 1;
        System.out.println("Executing method 'executeWithException' : " + i);
        throw new NullPointerException();
    }

    public void executeWithoutException() {
        j = j + 1;
        System.out.println("Executing method 'executeWithoutException' : " + j);
    }

    public String recovery() {
        return "Recovered";
    }
}

Main code


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.retry.support.RetryTemplate;

public class Example6 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Example6.xml");
        Service1 service1 = (Service1)context.getBean("service1");
        RetryTemplate retryTemplate =  (RetryTemplate)context.getBean("retryTemplate");

        retryTemplate.execute(retryContext -> { service1.executeWithException(); return null; });
    }
}

Note

Press like button if you like the post. Also share your opinion regarding posts through comments. Also mention what other framework you want me to cover through comments.

Leave a Reply