简体   繁体   中英

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 . 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
    }
}

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>

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

Declare Handler and ProfileManager as a spring bean , initialize them lazily. and inject them don't use new Handler() let Spring do this

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时将其传递给构造函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM