java SpringBoot注解@Async不生效的解决方法
作者:LiuBai.
大家好,本篇文章主要讲的是java SpringBoot注解@Async不生效的解决方法,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
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容器。。。。。。这点很重要,也是经常遇到的
到此这篇关于java SpringBoot注解@Async不生效的解决方法的文章就介绍到这了,更多相关SpringBoot注解@Async不生效内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
