You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

spring-retry中@Recover方法的触发时机:是否在全部重试失败后调用?

Spring Retry: When Does @Recover Get Called?

Hey there! Let’s break this down plainly so you’ve got no confusion left:

  • The @Recover annotated method will only be triggered when two conditions are met:
    1. The associated @Retryable method has used up all its configured retry attempts (e.g., if you set maxAttempts = 3, it will run 3 total times)
    2. The final attempt of the @Retryable method still ends in failure (throws an exception that’s specified in the @Retryable configuration)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:55:10