1.在springboot的Application类使用@EnableAsync开启异步
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @SpringBootApplication public class SpringbootSecurityApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSecurityApplication.class, args); } }
2.在Service层需要异步的方法上使用@Async注解
package com.peng; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AnService { @Async public void AnSleep() throws InterruptedException { Thread.sleep(5000); System.out.println("ok>>>>>>>>>>>>>>>>>>>success"); } }
3.在controller层直接调用即可实现
package com.peng.controller; import com.peng.AnService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class AnController { AnService anService; @Autowired public void setAnService(AnService anService) { this.anService = anService; } @ResponseBody @RequestMapping("/hello") public String hello() throws InterruptedException { anService.AnSleep(); return "hello"; } }
4.最终实现现在页面输出hello,5秒之后在控制台输出ok>>>>>>>>>>>>>>>>>>>success