Spring-如何将Bean注入在运行时创建多次的类中? [英] Spring - how to inject a bean into class which is created many times at runtime?
问题描述
我需要在应用程序启动时初始化bean,因此我在 applicationContext.xml
中进行了初始化。但是现在我需要将该bean注入到在运行时创建的对象中。示例:
I needed to initialize a bean at the application startup so I did that in applicationContext.xml
. But now I need to inject that bean into an object which is created at runtime. Example:
Servlet
...
void doPost(...) {
new Handler(request);
}
...
处理程序
public class Handler {
ProfileManager pm; // I need to inject this ???
Handler(Request request) {
handleRequest(request);
}
void handleRequest(Request request) {
pm.getProfile(); // example
}
}
推荐答案
更好的方法是也将Handler声明为Bean(假设已声明ProfileManager),然后如果在应用程序中使用批注,则使用注释@Autowired自动将Handler Bean中的ProfileManager进行连线,或者在应用程序内部applicationContext.xml。
如何在xml中执行此操作的示例可能是:
Better approach would be to declare the Handler as Bean as well - assuming that the ProfileManager is already declared - and then autowire the ProfileManager in the Handler bean either with the annotation @Autowired if you are using annotations in your apps, or inside the applicationContext.xml. An example of how to do it in the xml could be:
<bean id="profileManager" class="pckg.ProfileManager" />
<bean id="handler" class="pckg.Handler" >
<property name="pm" ref="profileManager" />
</bean>
如果您不想像Bean那样注册Handler实例化,则从中获取pm实例春天的ApplicationContext。在此处
If you do NOT want to register Handler as bean instantiate it as you do and take the pm instance from spring's ApplicationContext. A way of how to get ApplicationContext inside a web app is shown here
这篇关于Spring-如何将Bean注入在运行时创建多次的类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!