spring-retry中@Recover方法的触发时机:是否在全部重试失败后调用?
Hey there! Let’s break this down plainly so you’ve got no confusion left:
- The
@Recoverannotated method will only be triggered when two conditions are met:- The associated
@Retryablemethod has used up all its configured retry attempts (e.g., if you setmaxAttempts = 3, it will run 3 total times) - The final attempt of the
@Retryablemethod still ends in failure (throws an exception that’s specified in the@Retryableconfiguration)
- The associated
To directly answer your second question: It’s not just after all retries are done—it’s only after all retries are done AND the method still fails on that last try. If at any point during the retries the @Retryable method succeeds (doesn’t throw the targeted exception), the @Recover method will never be called.
Here’s a quick code example to make this tangible:
@Service public class PaymentService { // Retry up to 2 more times (total 3 attempts) if a PaymentException is thrown @Retryable(value = PaymentException.class, maxAttempts = 3) public void processPayment(String orderId) { System.out.println("Processing payment for order: " + orderId); // Simulate a failing payment throw new PaymentException("Payment gateway unavailable"); } // This runs ONLY after 3 failed payment attempts @Recover public void handlePaymentFailure(PaymentException e, String orderId) { System.out.println("All retries exhausted for order " + orderId + ". Notifying customer..."); // Logic to send failure notification, log, etc. } }
In this case, processPayment() will execute 3 times (all throwing PaymentException), and then handlePaymentFailure() will kick in. If on the second or third attempt the payment went through without an exception, the recovery method would never run.
内容的提问来源于stack exchange,提问作者Michael Hegerich

