时间:2022-07-06 10:16:42 | 栏目:JAVA代码 | 点击:次
SpringBoot 注解@Async不生效的解决方法

这里虽然加了
@EnableAsync和@Async,但是异步请求依然没有生效
方法一:
同一个类中调用需要先获取代理对象,也就是手动获取对象
@Service
@EnableAsync
public class DemoService {
public void add(){
DemoService bean = SpringUtil.getBean(DemoService.class);
System.out.println("开始");
bean.sendToKafka();
System.out.println("结束");
}
@Async
public void sendToKafka() {
try {
Thread.sleep(10000);
System.out.println("我睡醒了!!!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
方法二:
不同的类调用,直接注入即可
AsyncHandle.java (异步处理类)
@Service
@EnableAsync
public class AsyncHandle {
@Async
public void sendToKafka() {
try {
Thread.sleep(10000);
System.out.println("我睡醒了!!!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
DemoService.java (业务类)
@Service
public class DemoService {
@Autowired
private AsyncHandle asyncHandle;
public void add(){
System.out.println("开始");
asyncHandle.sendToKafka();
System.out.println("结束");
}
}
1、在需要用到的@Async注解的类上加上@EnableAsync,或者直接加在springboot启动类上
2、异步处理方法(也就是加了@Async注解的方法)只能返回的是void或者Future类型
3、同一个类中调用异步方法需要先获取代理类,因为@Async注解是基于Spring AOP (面向切面编程)的,而AOP的实现是基于动态代理模式实现的。有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器。。。。。。这点很重要,也是经常遇到的