我需要在应用程序启动时初始化一个 bean,所以我在 applicationContext.xml
中进行了初始化。但是现在我需要将该 bean 注入(inject)到一个在运行时创建的对象中。示例:
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 已经被声明 - 然后在 Handler bean 中 Autowiring ProfileManager 如果你在你的应用程序中使用注释,或者在内部使用注释 @Autowired applicationContext.xml。 如何在 xml 中执行此操作的示例可能是:
<bean id="profileManager" class="pckg.ProfileManager" />
<bean id="handler" class="pckg.Handler" >
<property name="pm" ref="profileManager" />
</bean>
如果您不想将 Handler 注册为 bean,请像您一样实例化它,并从 spring 的 ApplicationContext 中获取 pm 实例。显示了一种如何在 Web 应用程序中获取 ApplicationContext 的方法 here
关于java - Spring - 如何将一个 bean 注入(inject)到在运行时多次创建的类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6842477/