如何将依赖项注入 Spring 中的自实例化对象? [英] How to inject dependencies into a self-instantiated object in Spring?
问题描述
假设我们有一个类:
public class MyClass {
@Autowired private AnotherBean anotherBean;
}
然后我们创建了这个类的一个对象(或者其他一些框架已经创建了这个类的实例).
Then we created an object of this class (or some other framework have created the instance of this class).
MyClass obj = new MyClass();
是否仍然可以注入依赖项?类似的东西:
Is it possible to still inject the dependencies? Something like:
applicationContext.injectDependencies(obj);
(我认为 Google Guice 有这样的东西)
(I think Google Guice has something like this)
推荐答案
您可以使用 AutowireCapableBeanFactory
的 autowireBean()
方法来做到这一点.您将任意对象传递给它,Spring 会将其视为它自己创建的对象,并将应用各种自动装配的点点滴滴.
You can do this using the autowireBean()
method of AutowireCapableBeanFactory
. You pass it an arbitrary object, and Spring will treat it like something it created itself, and will apply the various autowiring bits and pieces.
要获得 AutowireCapableBeanFactory
,只需自动装配:
To get hold of the AutowireCapableBeanFactory
, just autowire that:
private @Autowired AutowireCapableBeanFactory beanFactory;
public void doStuff() {
MyBean obj = new MyBean();
beanFactory.autowireBean(obj);
// obj will now have its dependencies autowired.
}
这篇关于如何将依赖项注入 Spring 中的自实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!