Mastering Spring Retry: Using @Retryable and @Recover for Robust Java Applications

This article explains how to handle common failure scenarios in Spring Boot by using the spring-retry library, detailing the @Retryable and @Recover annotations, their parameters, configuration steps, code examples, and important considerations for building resilient backend services.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Mastering Spring Retry: Using @Retryable and @Recover for Robust Java Applications

Preface

In real‑world development, retrying failed operations is a frequent requirement, such as when sending a message fails, a remote service call fails, or a lock acquisition fails. These errors are often caused by temporary network glitches, and a simple retry after a short wait can succeed.

Typical code uses try/catch or a while loop, but this approach lacks consistency and adds boilerplate. The spring-retry module provides annotation‑based retry handling without intruding on business logic.

What is @Retryable?

The Spring spring-retry module offers a utility for standardised retry handling. All configuration is driven by simple annotations.

Usage Steps

POM Dependency

<dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
</dependency>

Enable @Retryable

@EnableRetry
@SpringBootApplication
public class HelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }
}

Add @Retryable to a Method

import com.mail.elegant.service.TestRetryService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalTime;

@Service
public class TestRetryServiceImpl implements TestRetryService {
    @Override
    @Retryable(value = Exception.class, maxAttempts = 3,
               backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public int test(int code) throws Exception {
        System.out.println("test called, time: " + LocalTime.now());
        if (code == 0) {
            throw new Exception("Invalid condition!");
        }
        System.out.println("test succeeded!");
        return 200;
    }
}

The annotation parameters have the following meanings: value: the exception types that trigger a retry. include: same as value; if both include and exclude are empty, all exceptions are retried. exclude: exception types that should not be retried. maxAttempts: maximum number of retry attempts (default 3). backoff: retry back‑off strategy; @Backoff defines the delay and multiplier. The default delay is 1000 ms; in the example it is set to 2000 ms with a multiplier of 1.5, resulting in delays of 2 s, 3 s, and 4.5 s for successive attempts.

When all retries are exhausted, Spring Retry can delegate control to a RecoveryCallback or use the @Recover annotation to define a fallback method.

@Recover
@Recover
public int recover(Exception e, int code) {
    System.out.println("Recovery method executed!");
    // log to database or perform alternative actions
    return 400;
}

The recovery method must have a first parameter of type Throwable (usually the same exception type specified in @Retryable) and a return type that matches the original method. It should reside in the same class as the retryable method.

Important Notes

Because Spring Retry is based on AOP, self‑invocation within the same class will not trigger retries.

If a retry fails and you need custom handling, the retryable method must return void and the logic should be placed in the @Recover method.

Do not use try/catch inside the retryable method; let exceptions propagate.

The @Recover method’s parameters must align with the exception type declared in @Retryable.

Summary

This article introduced the use of Spring Boot’s @Retryable annotation, its typical scenarios, configuration steps, and key considerations. When you need to automatically retry failed operations, Spring Retry provides a clean, annotation‑driven solution.

Spring Retry illustration
Spring Retry illustration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootRetryannotationsSpring Retry
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.