如何使用Spring手动自动装配bean?
我有一个bean B
我必须自己创建(使用 new B()
) @Autowire
和 @PostConstruct
注释。
I have a bean B
which I have to create myself (using new B()
) and which has @Autowire
and @PostConstruct
annotations.
如何做我在Spring中处理这些注释来自我的bean A
?
How do I make Spring process these annotations from my bean A
?
相关问题:
- In Spring, can I autowire new beans from inside an autowired bean?
Aaron,我相信你的代码是正确的,但我使用了以下内容:
Aaron, I believe that your code is correct but I used the following:
B bean = new B();
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean( bean );
factory.initializeBean( bean, "bean" );
第一种方法将处理 @Autowire
字段和方法(但不是经典属性)。第二种方法将调用后处理( @PostConstruct
和任何已定义的 BeanPostProcessor
)。
The first method will process @Autowire
fields and methods (but not classic properties). The second method will invoke post processing (@PostConstruct
and any defined BeanPostProcessor
s).
如果实现 ApplicationContextAware
接口,则可以在bean中获取应用程序上下文。
Application context can be obtained in a bean if it implements ApplicationContextAware
interface.