Spring-手动创建组件时@Async不起作用 [英] Spring - @Async not working when the component is manually created
问题描述
我在组件上使用 @Async
注释,该组件使用 AutowireCapableBeanFactory
在另一个类中手动实例化:
I'm using the @Async
annotation on a component that I manually instantiate in another class using the AutowireCapableBeanFactory
:
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean(object);
factory.initializeBean(object, "MyObject");
我的问题是,在 object
上调用异步方法的类是手动创建Spring上下文,这意味着我无法在其中自动连接 object
和在这种情况下,@ Async
注释似乎不起作用.
My issue is that the class calling the asynchronous method on object
is manually creating the Spring context and it means I cannot autowire object
in it, and the @Async
annotation doesn't seem to work in this case.
这是我的spring上下文实例化:
Here's my spring context instantiation :
@Component
@Scope("prototype")
@ComponentScan({ "com.package.my" })
public class Application {
private static ApplicationContext applicationContext;
public Application() {
if (applicationContext == null) {
applicationContext = new AnnotationConfigApplicationContext(Application.class);
}
}
}
我通过使用一个 Proxy
类解决了这个问题,该类中自动连接了我的对象,因为使用 AutowireCapableBeanFactory
时 @Autowired
可以正常工作
I solved the issue by using a Proxy
class that has my object autowired in it since @Autowired
is working fine when using the AutowireCapableBeanFactory
.
也就是说,我对这个解决方案并不满意,因为它要求我创建一个没有其他用途的中间类,而且我很确定可以创建 @Async
手动创建对象时进行批注工作.
That said, I'm not really satisfied with this solution as it requires me to create an intermediate class that has no other use, and I'm pretty sure it's possible to make the @Async
annotation work when manually creating the object.
有更好的方法吗?
谢谢.
推荐答案
如果您真的没有选择,也无法从 ApplicationContext
声明或检索bean,那么您可以询问 ApplicationContext
来准备对象,就好像它是一个bean.
If you really don't have a choice and can't declare or retrieve the bean from the ApplicationContext
, then you can ask the ApplicationContext
to prepare your object as if it was a bean.
您所使用的 initializeBean
方法实际上返回一个值,该值本身就是经过Spring处理的版本.例如,如果Spring在对象之上应用自己的代理,它将返回代理. javadoc 状态
The initializeBean
method you were using actually returns a value that is meant to be the Spring processed version of itself. For example, if Spring applies its own proxying on top of the object, it would return the proxy. The javadoc states
返回:要使用的bean实例,无论是原始的还是包装好的
Returns: the bean instance to use, either the original or a wrapped one
因此捕获其返回值并使用该值
So capture its return value and use that
object = factory.initializeBean(object, "MyObject");
这篇关于Spring-手动创建组件时@Async不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!