方法一:在初始化時儲存ApplicationContext對象
代碼:
ApplicationContext ac = new FileSystemXmlApplicationContex("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 對象注入。
以上方法適合不同的情況,請根據具體情況選用相應的方法。
這裡值得提一點的是,系統中用到上述方法的類實際上就於Spring架構緊密耦合在一起了,因為這些類是知道它們是運行在Spring架構上的,因此,系統中,應該盡量的減少這類應用,使系統儘可能 的獨立於當前運行環境,盡量通過DI的方式擷取需要的服務提供者。
方法六:
通過源碼發現
public class ContextLoaderListener extends ContextLoader implements ServletContextListener
在ContextLoader中
public static WebApplicationContext getCurrentWebApplicationContext() {ClassLoader ccl = Thread.currentThread().getContextClassLoader();if (ccl != null) {WebApplicationContext ccpt = currentContextPerThread.get(ccl);if (ccpt != null) {return ccpt;}}return currentContext;}
WebApplicationContext webctx=ContextLoader.getCurrentWebApplicationContext();
String path=webctx.getServletContext().getRealPath("xls");
TPoiService tp=webctx.getBean("poiservice", TPoiService.class);
轉自:http://www.blogjava.net/wuhen86/articles/315472.html