Background: In our web program, we use spring to manage individual instances (beans), and sometimes in a program to use a bean that has already been instantiated, this code is often used:
[Java]View PlainCopy
- ApplicationContext AppContext =
- New Classpathxmlapplicationcontext ("Classpath:meta-inf/spring/applicationcontext-common.xml");
- ApplicationContext Appcontext=appcontextutil.getcontext ();
- Projectservicefacade projectservicefacade= (Projectservicefacade) Appcontext.getbean (" Biz.projectservicefacade ");
The code above poses a problem: because it reloads the applicationcontext-common.xml and instantiates the context bean, if some of the thread configuration classes are in this configuration file, then the threads that do the same work will be restarted two times. One is started when the Web container is initialized, and the other is instantiated once by the code shown above. This is to be avoided in business.
Workaround: Do not use a new Classpathxmlapplicationcontext ()-like method to get the instantiated bean from the existing spring context.
Steps: 1) Add a Applicationcontextutil class to get the context ApplicationContext
[Java]View PlainCopy
- Public class Applicationcontextutil implements Applicationcontextaware {
- private ApplicationContext context; //Declare a static variable to save
- @Override
- public void Setapplicationcontext (ApplicationContext applicationcontext)
- throws Beansexception {
- This.context=applicationcontext;
- }
- Public ApplicationContext GetContext () {
- return context;
- }
- }
2) Add spring configuration to the Applicationcontextutil class, let spring complete the loading of this tool class and complete the injection of the ApplicationContext context ; The applicationcontext-common.xml is configured as follows:
[Java]View PlainCopy
[Java]View PlainCopy
- Initializes the Appliationutil class and completes the ApplicationContext injection
[Java]View PlainCopy
- <bean id="Applicationcontextutil" class="Com.service.utils.ApplicationContextUtil" ></ bean>
[Java]View PlainCopy
- Injecting Applicationcontextutil instances into the business class
[Java]View PlainCopy
- <bean id="Worksigncheckjob" class="Com.service.tools.quartz.WorkSignCheckJob" >
- <property name="Appcontextutil" ref="Applicationcontextutil"/>
- </bean>
3) The business class calling code is as follows:
[Java]View PlainCopy
- ApplicationContext Appcontext=appcontextutil.getcontext ();
- Projectservicefacade projectservicefacade= (Projectservicefacade) Appcontext.getbean (" Biz.projectservicefacade ");
- Worksignservice worksignservice= (Worksignservice) Appcontext.getbean ("Biz.worksignservice");
Considerations for new Classpathxmlapplicationcontext () in the program