原文鏈接:http://blog.sina.com.cn/s/blog_534f69a001011lkj.html
1.WebApplicationContext的研究
ApplicationContext是spring的核心,Context通常解釋為上下文環境,用“容器”來表述更容易理解一些,ApplicationContext則是“應用的容器了”了。
spring把bean放在這個容器中,在需要的時候,用getBean()方法取出,在web應用中,會用到webApplicationContext,繼承自ApplicationContext
在web.xml初始化WebApplicationContext:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
或者用ContextLoaderServlert亦可(加<load-on-startup>1</load-on-startup>)
2.ServletContext詳解
ServletContext 是Servlet與Servlet容器之間直接通信的接口,Servlet容器在啟動一個web應用時,會為它創建一個ServletContext對 象,每個web應用有唯一的ServletContext對象,同一個web應用的所有Servlet對象共享一個 ServletContext,Servlet對象可以通過它來訪問容器中的各種資源
存取共享數據方法:
setAttribute(String name,Object obj)
getAttribute(String name)
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
DataSource ds= ctx.getBean(DataSource.class);
jRExportService.setDataSource(ds)
這里得到了spring 的webApplicationContext ,spring的bean都放在里面,然后直接getBean就可以得到了