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.
More Related questions...