獲取Spring的上下文環境ApplicationContext的方式

Web項目中發現有人如此得到Spring的上下環境:java

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");
至關於從新初始化一遍!!!!
也就是說,重複作啓動時候的初始化工做,第一次執行該類的時候會很是耗時!!!!!web

正確的作法是:
方法一:在初始化時保存ApplicationContext對象
代碼:
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
說明:這種方式適用於採用Spring框架的獨立應用程序,須要程序經過配置文件手工初始化Spring的狀況。spring

方法二:經過Spring提供的工具類獲取ApplicationContext對象
代碼:
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
說明:
這種方式適合於採用Spring框架的B/S系統,經過ServletContext對象獲取ApplicationContext對象,而後在經過它獲取須要的類實例。
上面兩個工具方式的區別是,前者在獲取失敗時拋出異常,後者返回null。
其中 servletContext sc 能夠具體 換成 servlet.getServletContext()或者 this.getServletContext() 或者 request.getSession().getServletContext(); 另外,因爲spring是注入的對象放在ServletContext中的,因此能夠直接在ServletContext取出 WebApplicationContext 對象: WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);服務器

方法三:繼承自抽象類ApplicationObjectSupport
說明:抽象類ApplicationObjectSupport提供getApplicationContext()方法,能夠方便的獲取到ApplicationContext。
Spring初始化時,會經過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入。session

方法四:繼承自抽象類WebApplicationObjectSupport
說明:相似上面方法,調用getWebApplicationContext()獲取WebApplicationContextapp

方法五:實現接口ApplicationContextAware
說明:實現該接口的setApplicationContext(ApplicationContext context)方法,並保存ApplicationContext 對象。
Spring初始化時,會經過該方法將ApplicationContext對象注入。框架

在web項目裏還有一種比較簡單的方法,經過Servlet上下文來獲取spring的上下文:工具

public void sessionDestroyed(HttpSessionEvent event) {
    ServletContext sc = event.getSession().getServletContext();
    CountRepository countRepository = 
                   (CountRepository)WebApplicationContextUtils.getWebApplicationContext(sc).getBean("countRepository");
}
相關文章
相關標籤/搜索