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