Spring / Spring Retry Interview Questions
What is the @Recover annotation and when is it invoked?
The @Recover annotation marks a fallback method that Spring Retry calls when all retry attempts for a @Retryable method have been exhausted without success. It provides a graceful degradation path instead of allowing the exception to propagate to the caller.
Rules for a valid @Recover method:
- It must be in the same Spring bean as the
@Retryablemethod. - Its return type must match the
@Retryablemethod's return type. - Its first parameter must be the exception type being recovered from.
- It can optionally accept the same additional parameters as the
@Retryablemethod.
Example:
@Retryable(retryFor = RuntimeException.class, maxAttempts = 3) public String fetchData(String id) { return externalService.get(id); } @Recover public String recoverFetchData(RuntimeException ex, String id) { log.error("All retries failed for id: {}", id, ex); return "default-value"; }
If fetchData fails all 3 attempts, Spring Retry automatically routes execution to recoverFetchData. The exception is passed as the first argument so the recovery method can log or react to the specific failure. If no matching @Recover method is found, the final exception is re-thrown.
More Related questions...