在c/s結構 我們可以通過ApplicationContext的getBean方法來獲取bean
例如:
寫道
ApplicationContext ctx= new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
Object obj = ctx.getBean("beanname");
而在b/s中我們可以通過WebApplicationContext來獲取bean:
實例:首先我們配置spring的log4j級別為DEBUG模式:
log4j.logger.org.springframework=DEBUG
在web.xml里面配加載項:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
啟動后我們會在控制臺看見如下信息:
Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT] Root WebApplicationContext: initialization completed in 1453 ms
也就是說spring將WebApplicationContext 作為ServletContext 得一個attrubute放在了ServletContext 理參數名為org.springframework.web.context.WebApplicationContext.ROOT。而ServletContext 是application(jvm)級別的,因此我們可以通過servlet的ServletContext 來得到它
而獲取WebApplicationContext 可以使用WebApplicationContextUtils的方法,此方法需要一個ServletContext 實例作為參數
public static WebApplicationContext getWebApplicationContext(ServletContext sc)
因此我們可以這樣獲得我們的bean
WebApplicationContext wb = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object obj = ctx.getBean("beanname");
跟蹤下spring代碼:
public static WebApplicationContext getWebApplicationContext(ServletContext sc) { return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);//實現如下: }
public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) { Assert.notNull(sc, "ServletContext must not be null"); Object attr = sc.getAttribute(attrName);
return (WebApplicationContext) attr;
end。