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.".
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);
}
}