🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 引入 spring-boot-starter-web** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` <br/> **2. 在启动类上标注注解`@EnableAsync`开启异步支持** ```java @EnableAsync @SpringBootApplication public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } } ``` <br/> **3. 在类或方法上标注注解`@Async`创建异步任务** ```java @Slf4j @Service public class AsyncService { @Async public void asyncSendEmail() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("[asyncSendEmail]"); } } ``` <br/> **4. 在其他类的方法中调用异步方法** ```java @Slf4j @RestController @RequiredArgsConstructor public class AsyncController { final AsyncService asyncService; @GetMapping("/v1/asyncSendEmail") public void asyncSendEmail() { log.info("[asyncSendEmail|start]"); //调用异步方法 asyncService.asyncSendEmail(); log.info("[asyncSendEmail|end]"); } } ``` ``` ///日志打印顺序如下,说明异步方法已经异步执行了 2023-06-02 16:59:04 ...: [asyncSendEmail|start] 2023-06-02 16:59:04 ...: [asyncSendEmail|end] -- 等待 5s 后输出 2023-06-02 16:59:09 ...: [asyncSendEmail] ```