1、在启动类上添加开启异步注解
@EnableAsync
@SpringBootApplication
public class SpringBoot04taskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot04taskApplication.class, args);
}
}
2、在Service层的方法上加上异步注解@Async
package com.laoxu.task.service.impl;
import com.laoxu.task.service.HelloService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class HelloServiceImpl implements HelloService {
@Override
@Async
public void sayHello() throws InterruptedException {
Thread.sleep(5000);
System.out.println("Hello World");
}
}
3、控制器调用Service层的方法
package com.laoxu.task.controller;
import com.laoxu.task.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String hello() throws InterruptedException {
helloService.sayHello();
return "success";
}
}
在5秒后打印Hello World