user219882
user219882

Reputation: 15844

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

Upvotes: 1

Views: 1660

Answers (4)

gred
gred

Reputation: 537

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

Upvotes: 2

Caps
Caps

Reputation: 1523

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 inject ProfileManager into Servlet and then just pass it into the constructor when you create Handler.

Upvotes: 1

b.buchhold
b.buchhold

Reputation: 3896

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.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240908

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

Upvotes: 1

Related Questions