Spring / Spring Retry Interview Questions
What is RetryTemplate and how does it differ from annotation-based retry?
RetryTemplate is the programmatic API for Spring Retry. It allows you to define retry behavior as code rather than annotations, giving you full control over when, how, and around which blocks of code retry logic is applied — including lambda expressions or any non-Spring-managed code.
When using @Retryable, the retry logic is applied by AOP proxies at method call interception time. This means the annotated method must be called through a Spring bean proxy — calling it from within the same class bypasses the proxy and the retry logic entirely. RetryTemplate has no such limitation because it wraps an explicit callback, not a method invocation through a proxy.
Example:
RetryTemplate retryTemplate = RetryTemplate.builder()
.maxAttempts(3)
.fixedBackoff(2000)
.retryOn(HttpServerErrorException.class)
.build();
String result = retryTemplate.execute(context -> {
return restTemplate.getForObject(url, String.class);
}, context -> {
return "fallback-response"; // recovery callback
});The first lambda is the retryable operation; the second is the recovery callback invoked if all attempts fail. This pattern is useful in service classes where you want retry logic around a specific block that is not easily isolated into its own method.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
