Spring / Spring Retry Interview Questions
What is the RetryCallback interface in Spring Retry?
RetryCallback is a functional interface that wraps the operation to be retried when using RetryTemplate programmatically. It represents the unit of work that may fail and should be retried.
@FunctionalInterface public interface RetryCallback<T, E extends Throwable> { T doWithRetry(RetryContext context) throws E; }
The generic type T is the return type of the operation, and E is the exception type it may throw. The context parameter gives access to retry count, last exception, and custom attributes.
Usage with lambda:
String result = retryTemplate.execute((RetryCallback<String, IOException>) context -> { log.info("Attempt #" + (context.getRetryCount() + 1)); return remoteService.fetchData(); });
When using the two-argument form of execute(), the second argument is a RecoveryCallback — a companion interface that defines the fallback to invoke when all retry attempts are exhausted:
String result = retryTemplate.execute( ctx -> remoteService.fetchData(), // RetryCallback ctx -> "default-value" // RecoveryCallback );
The RecoveryCallback receives the same RetryContext, which includes getLastThrowable() so you can log or inspect the final failure reason.
More Related questions...