Spring - 如何将bean注入到在运行时多次创建的类中?
我需要在应用程序启动时初始化一个 bean,因此我在 applicationContext.xml
中执行此操作。但现在我需要将该 bean 注入到运行时创建的对象中。示例:
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
}
}
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);
}
...
Handler
public class Handler {
ProfileManager pm; // I need to inject this ???
Handler(Request request) {
handleRequest(request);
}
void handleRequest(Request request) {
pm.getProfile(); // example
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更好的方法是将 Handler 也声明为 Bean - 假设 ProfileManager 已经声明 - 然后在 Handler bean 中自动装配 ProfileManager,如果您在应用程序中使用注释,则使用注释 @Autowired ,或者在 applicationContext 内。 xml。
如何在 xml 中执行此操作的示例如下:
如果您不想将 Handler 注册为 bean,请像您一样实例化它,并从 spring 的 ApplicationContext 中获取 pm 实例。 此处显示了如何在 Web 应用程序中获取 ApplicationContext 的方法
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:
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
将
Handler
和ProfileManager
声明为 spring bean ,并延迟初始化它们。并注入它们不要使用new Handler()
让 Spring 这样做Declare
Handler
andProfileManager
as a spring bean , initialize them lazily. and inject them don't usenew Handler()
let Spring do this首先,我想知道为什么“Handler”会被一遍又一遍地初始化。在此示例中,使用 bean 并在运行时多次调用方法似乎同样好。
除此之外,您还可以使用 bean 本身的方面。在那里注入 ProfileManager 并让 Aspect 来创建 Handler,设置 pm.
First of all, I wonder why "Handler" is intilialized over and over again. Using a bean and calling a method multiple times at runtime seems to be just as good in this example.
Apart from that, you can use an aspect that is a bean itself. Inject the ProfileManager there and let the Aspect work on creation of Handler, setting the pm.
我同意其他答案,指出您确实应该让 Spring 处理
Handler
的创建,但如果这不是一个选项,那么您可以将ProfileManager
注入Servlet
,然后在创建Handler
时将其传递到构造函数中。I agree with the other answers stating that you really should let Spring handle the creation of
Handler
but if that isn't an option then you could injectProfileManager
intoServlet
and then just pass it into the constructor when you createHandler
.