问题说明
在标注了 @Async 注解的方法内使用 AopContext.currentProxy() 会报错:
Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available,and ensure that AopContext.currentProxy() is invoked in the same thread as the AOP invocation context.
问题原因
报错提示:确保在AOP调用上下文的同一线程中调用AopContext.currentProxy()方法
标注了 @Async 的方法会在新的线程中执行,而AopContext.currentProxy() 方法的作用是获取当前代理对象,它只能在当前线程的AOP调用链中使用。
解决方法
可以在程序启动时获取代理对象并存入属性中
示例:
@Service
public class MyServiceImpl implements MyService {
@Autowired
private ApplicationContext applicationContext;
private MyService proxy;
@PostConstruct
public void init() {
this.proxy = this.applicationContext.getBean(MyService.class);
}
@Async
public void executeAsync() {
this.proxy.doSomething();
}
public void doSomething() {
//...
}
}