To enable Spring retry one can either enable retry in Java annotation: @EnableRetry within Configuration or specify retry in an XML configuration file:
<context:annotation-config />
<aop:aspectj-autoproxy />
<bean class="org.springframework.retry.annotation.RetryConfiguration" />
Both specification are based on …annotation.RetryConfiguration that started only from the version 1.1.2. How to enable retry in XML configuration in the previous versions? Due to compatibility issues I cannot use version 1.1.2. The retry configuration is as follows:
<aop:config>
<aop:pointcut id="retrySave"
expression="execution( * sfweb.service.webServiceOrders.WsOrderCreationServiceImpl.saveLedger(..))" />
<aop:advisor pointcut-ref="retrySave" advice-ref="retryAdvice"
order="-1" />
</aop:config>
<bean id="retryAdvice"
class="org.springframework.retry.interceptor.RetryOperationsInterceptor">
</bean>
Spring Retry 1.0.3 did not have AspectJ based AOP support. Therefore, aspect-style retries will not work with that version. Instead, retryable code needs to be wrapped inside an instance of a RetryCallback
. The generic approach is as follows:
1. Create a
RetryTemplate
SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(maxAttempts);
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(backOffPeriod);
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
retryTemplate.setRetryPolicy(simpleRetryPolicy);
2. Wrap the retryable code in a
RetryCallback
class FailureProneOperation implements RetryCallback<Void> {
public void doWithRetry(RetryContext context) throws Exception {
...
}
}
3. Execute the retryable code
retryTemplate.execute(new FailureProneOperation())