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.
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...
