How to insert a bean class into a class that is created many times at runtime?

I needed to initialize the bean when the application started, so I did this in applicationContext.xml . But now I need to enter a bean into the object that 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 } } 
+1
source share
4 answers

The best approach would be to declare the handler as a Bean, since it is assumed that the ProfileManager is already declared - and then the autowire ProfileManager in the Handler Bean, either with the @Autowired annotation if you use annotations in your application or inside applicationContext.xml. An example of how to do this in xml might 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 the Handler as a Bean, create it the same way you do and grab the pm instance from spring ApplicationContext. The way to get ApplicationContext in a web application is shown here.

+2
source

Declare Handler and ProfileManager as spring bean, initialize them lazily. and enter them, don't use new Handler() let spring do it

+1
source

First of all, I wonder why the โ€œhandlerโ€ is misleading over and over again. Using a bean and calling the method several times at runtime seems to be just as good in this example.

Alternatively, you can use the bean aspect. Add a ProfileManager to it and let Aspect work on creating the Handler by setting pm.

+1
source

I agree with the other answers that you really should let Spring handle Handler creation, but if that is not an option, you can insert the ProfileManager in the Servlet and then just pass it to the constructor when creating the Handler .

+1
source

Source: https://habr.com/ru/post/1382900/


All Articles