大家都知道@Async注解是通过aop代理实现的,而我们调用自己类的异步方法时,绕过了aop代理从而导致其异步失效,知道原因后就好解决了,我们可以从spring上下文中取得代理对象,继而调用其异步方法。代码如下:
@Service
public class HelloService {
@Autowired
ApplicationContext applicationContext;
public String testAsync() throws InterruptedException {
//获取HelloService代理对象
HelloService bean = applicationContext.getBean(HelloService.class);
System.out.println("当前对象是否是代理对象:" + AopUtils.isAopProxy(bean));
System.out.println("是否是cglib代理对象:" + AopUtils.isCglibProxy(bean));
System.out.println("是否是jdk代理对象:" + AopUtils.isJdkDynamicProxy(bean));
System.out.println(bean == this);
//调用代理对象的异步方法
bean.Async();
return "s";
}
@Async
//不能声明为private
public void Async() throws InterruptedException {
Thread.sleep(10000);
System.out.println("睡眠结束");
}
}