Spring初始化時,沒注入時獲取注入,對象webapplicationcontext

ApplicationContext appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
  securityService = (SecurityService) appCtx.getBean("securityService");

轉自:http://www.blogjava.net/Todd/archive/2009/09/15/295112.html
方法一:在初始化時保存ApplicationContext對象
代碼:
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
說明:這種方式適用於採用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 對象注入。

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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章