Spring Boot - 一个 bean 引用自身来在同一个类中触发 AOP @Async,但不起作用
我想在我自己的 Bean 内部调用一个方法,该方法有自己的 @Async 和 @Transactional 代理,但它不起作用。
public class MyClass {
private MyClass _selfWithProxy;
@PostConstruct
public void postContruct() {
_selfWithProxy = applicationContext.getBean(MyClass.class);
}
void myMethodA() {
_selfWithProxy.myMethodB()
}
@Async
@Transactinal
void myMethodB() {
//do stuff
}
但是,当我从另一个 Bean 调用 myMethodA 时,对 myMethodB 的调用不会被异步拦截器拦截。我可以看到 _selfWithProxy 是一个代理 bean,并且代理激活,但链中没有异步拦截器。
当我从另一个 bean 调用 myMethodB 时,@Async 起作用,所以我知道它设置正确
I want to within my own Bean call a method within itself which has its own @Async and @Transactional proxies but it isnt working.
public class MyClass {
private MyClass _selfWithProxy;
@PostConstruct
public void postContruct() {
_selfWithProxy = applicationContext.getBean(MyClass.class);
}
void myMethodA() {
_selfWithProxy.myMethodB()
}
@Async
@Transactinal
void myMethodB() {
//do stuff
}
However when I call myMethodA from another Bean the call to myMethodB does not intercept with an Async interceptor. I can see _selfWithProxy is a proxy bean, and the proxy activates but there are is no Async interceptor in the chain.
When I call myMethodB from another bean the @Async works, so I know it is setup correctly
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
自调用不适用于@Async。我相信这是因为代理(你的代码+AOP建议)对象在目标对象(只是你的代码)上调用你的方法A,然后目标对象调用它自己的方法B,这是AOP不建议的。一般来说,我不建议让 spring bean 方法调用同一 bean 的其他方法。
“@Async 有两个限制:
它必须仅应用于公共方法。
自调用(从同一个类中调用异步方法)将不起作用。
原因很简单:该方法需要公开,以便可以被代理。并且自调用不起作用,因为它绕过代理并直接调用底层方法。”
https:// /www.baeldung.com/spring-async
Self invocation won't work for @Async. I believe that is because the proxy (your code + AOP advice) object calls your methodA on the target object (just your code) which then calls it's own methodB which isn't advised by AOP. In general I would not advise having spring bean methods call other methods of the same bean.
"@Async has two limitations:
It must be applied to public methods only.
Self-invocation — calling the async method from within the same class — won't work.
The reasons are simple: The method needs to be public so that it can be proxied. And self-invocation doesn't work because it bypasses the proxy and calls the underlying method directly."
https://www.baeldung.com/spring-async