您的位置:首页 > 移动开发

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

2014-11-30 20:47 316 查看


获取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项目中这种方式非常不可取!!!

分析:

首先,主要意图就是获得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应用上下文环境

/*

* 实现了[b]ApplicationContextAware 接口,必须实现该方法;[/b]

*通过传递[b]applicationContext参数初始化成员变量applicationContext[/b]

*/

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上下文再获取对象!

转自:http://blog.csdn.net/yang123111/article/details/32099329
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: