获取Spring的上下文环境ApplicationContext请注意!!

Web项目中发现有人如此获得Spring的上下环境:

public class SpringUtil {

       public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
       public static Object getBean(String serviceName){
             return context.getBean(serviceName);
       }
}

在web项目中这种方式非常不可取!!!
在web项目中,系统一旦启动,web服务器会初始化Spring的上下文的,我们可以很优雅的获得Spring的ApplicationContext对象。
如果使用new ClassPathXmlApplicationContext("applicationContext.xml");
相当于重新初始化一遍!!也就是说所有bean会再被创建一次!!就会有两个bean,如果有些bean是用来执行定时任务的,则就会有多个线程执行定时任务,造成重复执行!!

正确的做法是:

 

@Component
public class SpringContextUtil implements ApplicationContextAware {

         private static ApplicationContext applicationContext; // Spring应用上下文环境

         /*

          * 实现了ApplicationContextAware 接口,必须实现该方法;

          *通过传递applicationContext参数初始化成员变量applicationContext

          */

         public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
               SpringContextUtil.applicationContext = applicationContext;
         }

         public static ApplicationContext getApplicationContext() {
                return applicationContext;
         }

          @SuppressWarnings("unchecked")
          public static <T> T getBean(String name) throws BeansException {
                     return (T) applicationContext.getBean(name);
           }

}
注意:这个地方使用了Spring的注解@Component,如果不是使用annotation的方式,而是使用xml的方式管理Bean,记得写入配置文件
<bean id="springContextUtil" class="com.ecdatainfo.util.SpringContextUtil" singleton="true" />

其实,
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
这种方式获取Sping上下文环境,最主要是在测试环境中使用,比如写一个测试类,系统不启动的情况下手动初始化Spring上下文再获取对象!


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值