获取Spring的上下文环境ApplicationContext的方式

来源:互联网 发布:打印机网络共享设置 编辑:程序博客网 时间:2024/04/30 05:03

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

 

public class SpringUtil {

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

 

 

在web项目中这种方式非常不可取!!!

分析:

首先,主要意图就是获得Spring上下文;

其次,有了Spring上下文,希望通过getBean()方法获得Spring管理的Bean的对象;

最后,为了方便调用,把上下文定义为static变量或者getBean方法定义为static方法;

 

但是,在web项目中,系统一旦启动,web服务器会初始化Spring的上下文的,我们可以很优雅的获得Spring的ApplicationContext对象。

如果使用

new ClassPathXmlApplicationContext("applicationContext.xml");
相当于重新初始化一遍!!!!

也就是说,重复做启动时候的初始化工作,第一次执行该类的时候会非常耗时!!!!!

 

正确的做法是:

 

@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上下文再获取对象!
0 0
原创粉丝点击