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上下文再獲取對象!