案头见蠹鱼,犹胜凡俦侣。这篇文章主要讲述在程序中用new ClassPathXmlApplicationContext()的注意事项相关的知识,希望能为你提供帮助。
问题背景:在我们的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");
解决方法:不用类似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
- //初始化appliationUtil类,并完成ApplicationContext的注入
- < bean id="applicationContextUtil" class="com.service.utils.ApplicationContextUtil"> < /bean>
- //对业务类注入ApplicationContextUtil实例
- < bean id="workSignCheckJob" class="com.service.tools.quartz.WorkSignCheckJob" >
- < property name="appContextUtil" ref="applicationContextUtil" />
- < /bean>
[java] view plain copy
- ApplicationContext appContext=appContextUtil.getContext();
- ProjectServiceFacade projectServiceFacade=(ProjectServiceFacade)appContext.getBean("biz.projectServiceFacade");
-
WorkSignService
workSignService=(WorkSignService)appContext.getBean("biz.workSignService");
推荐阅读
- Android Studio设置背景色
- android 混淆基本知识
- Android更新带进度条的通知栏
- [LeetCode] 407. Trapping Rain Water II
- android中怎么将桌面较长的图标名称显示完整
- What happens when a SQL Query runs?
- Android学习笔记之ProgressBar案例分析
- Android之怎样设置文本改变监听
- 移动终端软件开发2017-2018秋学期教材《Android移动应用设计与开发(第2版)——基于Android Studio开发环境》