SpringBoot Question : @Async
2022-07-19 本文已影响0人
七喜丶
失效原因 (待补充)
1.@SpringBootApplication启动类当中没有添加@EnableAsync注解
2.两个方法都在同一个类里面,只是一个方法调用另一个异步方法
public void handData() throws InterruptedException {
System.out.println("方法1");
asyneTask();
System.out.println("运行结束");
}
@Async
public void asyneTask() throws InterruptedException {
Thread.sleep(1000);
System.out.println("方法2");
}
3.注解的方法使用static
总结:
- 启动类是否开启异步服务
- 在定义异步方法的同一个类中,调用带有@Async注解方法,该方法则无法异步执行
- 注解的方法必须是public方法,不能是static
- 没有走Spring的代理类。因为@Transactional和@Async注解的实现都是基于Spring的AOP,而AOP的实现是基于动态代理模式实现的。那么注解失效的原因就很明显了,有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器管理
- 和@Transactional有些类似,需要在调用类之外才生效,所以Async的方法最好单独建了一个类