一、测试@Async是否生效
1.1、调用方法:
public void xxx(String userId){
// 此处省略若干代码
System.out.println(1);
xxxService.xxxAsync(userId);
System.out.println(2);
}
1.2、xxxServiceImpl类
@Async // 注:一般会放在xxxServiceImpl类中
void xxxAsync(String userId);
1.3、被调用方法(xxxService类)
public void xxxAsync(String userId){
System.out.println(3);
// 此处省略若干代码
System.out.println(4);
}
1.4、如上所述,如果@Async生效,打印顺序必定是 1/2/3/4 ;反之失效
二、失效的情况和解决办法
失效情况:如果调用方法和被调用方法都在AService中,则不生效
失效原因:同一个类中一个方法调用另一个方法(该方法带着@Async)注解不生效的原因,其实是调用方法是对象本身,这个和bean的生命周期有关,aop的作用对象是代码类。
据说:可以通过 Spring上下文 解决这个问题,但是测试后好像没用(以下是测试代码,请各位大佬指教)
WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
UserxxxService userxxxService = (UserxxxService) ac.getBean("userxxxService");
userxxxService.xxxAsync(userId);
解决办法:将@Async注解的方法,移到其它类中,运行顺序肯定是 1/2/3/4
注:@Transactional注解也会出现以上问题,这是为什么呢?求指教
奶奶的CSDN,做博客的系统,编辑器问题既然一大堆,第一遍保存没成功,写的东西全丢了,以上是第二遍写的,非常反胃[吐]