问题背景:在我们的web程序中,用spring来管理各个实例(bean), 有时在程序中为了使用已被实例化的bean, 通常会用到这样的代码:
[java] view plain copy
- ApplicationContext appContext =
- new ClassPathXmlApplicationContext("classpath:META-INF/spring/applicationContext-common.xml");
- ApplicationContext appContext=appContextUtil.getContext();
- ProjectServiceFacade projectServiceFacade=(ProjectServiceFacade)appContext.getBean("biz.projectServiceFacade");
上述的代码会带来一个问题:因为它会重新装载applicationContext-common.xml并实例化上下文bean, 如果有些线程配置类也是在这个配置文件中,那么会造成做相同工作的的线程会被启两次。一次是web容器初始化时启动,另一次是上述代码显示的实例化了一次。这在业务上是要避免的。
解决方法:不用类似new ClassPathXmlApplicationContext()的方式,从已有的spring上下文取得已实例化的bean。
具体步骤:1)增加一个ApplicationContextUtil类,用来取得上下文ApplicationContext
[java] view plain copy
- public class ApplicationContextUtil implements ApplicationContextAware {
- private ApplicationContext context;//声明一个静态变量保存
- @Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- this.context=applicationContext;
- }
- public ApplicationContext getContext(){
- return context;
- }
- }
2) 对ApplicationContextUtil类增加 Spring配置,让Spring完成此工具类的装载并且完成applicationcontext上下文的注入;applicationContext-common.xml配置如下:
[java] view plain copy
[java] view plain copy
- //初始化appliationUtil类,并完成ApplicationContext的注入
[java] view plain copy
- <bean id="applicationContextUtil" class="com.service.utils.ApplicationContextUtil"></bean>
[java] view plain copy
- //对业务类注入ApplicationContextUtil实例
[java] view plain copy
- <bean id="workSignCheckJob" class="com.service.tools.quartz.WorkSignCheckJob" >
- <property name="appContextUtil" ref="applicationContextUtil" />
- </bean>
3)业务类调用代码如下:
[java] view plain copy
- ApplicationContext appContext=appContextUtil.getContext();
- ProjectServiceFacade projectServiceFacade=(ProjectServiceFacade)appContext.getBean("biz.projectServiceFacade");
- WorkSignService workSignService=(WorkSignService)appContext.getBean("biz.workSignService");
时间: 2024-10-01 02:28:01