0
0
Spring Bootframework~5 mins

@EnableAsync annotation in Spring Boot

Choose your learning style9 modes available
Introduction

The @EnableAsync annotation tells Spring Boot to run certain methods in the background, so your app can do other things without waiting.

When you want to send emails without making the user wait.
When you need to process files or data in the background.
When calling slow web services and you don't want to block the main app.
When you want to improve app responsiveness by running tasks in parallel.
Syntax
Spring Boot
@EnableAsync
@Configuration
public class AppConfig {
}
Place @EnableAsync on a configuration class to activate async support.
Use @Async on methods you want to run asynchronously.
Examples
Basic setup to enable async processing in your Spring Boot app.
Spring Boot
@EnableAsync
@Configuration
public class AsyncConfig {
}
Mark the sendEmail method with @Async to run it in the background.
Spring Boot
@Service
public class EmailService {

  @Async
  public void sendEmail(String to) {
    // send email logic
  }
}
Sample Program

This example shows how @EnableAsync activates async support. The sendEmail method runs in the background, so the main thread does not wait 2 seconds before printing "sendEmail called.".

Spring Boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

@SpringBootApplication
@EnableAsync
public class AsyncExampleApplication {

  public static void main(String[] args) {
    var context = SpringApplication.run(AsyncExampleApplication.class, args);
    EmailService emailService = context.getBean(EmailService.class);
    System.out.println("Calling sendEmail...");
    emailService.sendEmail("friend@example.com");
    System.out.println("sendEmail called.");
  }
}

@Service
class EmailService {

  @Async
  public void sendEmail(String to) {
    try {
      Thread.sleep(2000); // simulate delay
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
    System.out.println("Email sent to " + to);
  }
}
OutputSuccess
Important Notes

Remember to add @Async on methods you want to run asynchronously.

Async methods should return void or Future types for better control.

Spring uses a thread pool to run async methods, so heavy use may need tuning.

Summary

@EnableAsync turns on background method running in Spring Boot.

Use @Async on methods to run them without blocking the main flow.

This helps apps stay fast and responsive by doing slow tasks in the background.