[英]Spring - how to inject a bean into class which is created many times at runtime?
I needed to initialize a bean at the application startup so I did that in applicationContext.xml
. 我需要在应用程序启动时初始化bean,所以我在
applicationContext.xml
进行了初始化。 But now I need to inject that bean into an object which is created at runtime. 但是现在我需要将该bean注入到在运行时创建的对象中。 Example:
例:
Servlet
...
void doPost(...) {
new Handler(request);
}
...
Handler
public class Handler {
ProfileManager pm; // I need to inject this ???
Handler(Request request) {
handleRequest(request);
}
void handleRequest(Request request) {
pm.getProfile(); // example
}
}
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. 更好的方法是也将Handler声明为Bean(假设已声明ProfileManager),然后(如果您在应用程序中使用注解)或在applicationContext中使用@Autowired注解在Handler bean中自动装配ProfileManager。 xml。 An example of how to do it in the xml could be:
如何在xml中执行此操作的示例可能是:
<bean id="profileManager" class="pckg.ProfileManager" />
<bean id="handler" class="pckg.Handler" >
<property name="pm" ref="profileManager" />
</bean>
If you do NOT want to register Handler as bean instantiate it as you do and take the pm instance from spring's ApplicationContext. 如果您不想将Handler注册为bean实例化,请从spring的ApplicationContext中获取pm实例。 A way of how to get ApplicationContext inside a web app is shown here
此处显示了一种如何在Web应用程序中获取ApplicationContext的方法
Declare Handler
and ProfileManager
as a spring bean , initialize them lazily. 将
Handler
和ProfileManager
声明为spring bean,然后将它们延迟初始化。 and inject them don't use new Handler()
let Spring do this 并注入它们不要使用
new Handler()
让Spring做到这一点
First of all, I wonder why "Handler" is intilialized over and over again. 首先,我想知道为什么一遍又一遍地介绍“ Handler”。 Using a bean and calling a method multiple times at runtime seems to be just as good in this example.
在此示例中,使用bean并在运行时多次调用方法似乎同样有效。
Apart from that, you can use an aspect that is a bean itself. 除此之外,您可以使用一个bean本身的方面。 Inject the ProfileManager there and let the Aspect work on creation of Handler, setting the pm.
在此处注入ProfileManager,并让Aspect在创建Handler时工作,设置pm。
我同意其他答案,说明您确实应该让Spring处理Handler
的创建,但是如果不是这样,则可以将ProfileManager
注入Servlet
,然后在创建Handler
时将其传递给构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.