標籤:spring tar 環境 export xtu blog 研究 介面 ice
1.WebApplicationContext的研究
ApplicationContext是spring的核心,Context通常解釋為上下文環境,用“容器”來表述更容易理解一些,ApplicationContext則是“應用的容器了”了。
spring把bean放在這個容器中,在需要的時候,用getBean()方法取出,在web應用中,會用到webApplicationContext,繼承自ApplicationContext
在web.xml初始化WebApplicationContext:
1 <context-param> 2 3 <param-name>contextConfigLocation</param-name> 4 5 <param-value>/WEB-INF/applicationContext.xml</param-value> 6 7 </context-param> 8 9 <listener>10 11 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>12 13 </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)
1 WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()) 2 DataSource ds= ctx.getBean(DataSource.class);3 jRExportService.setDataSource(ds)
這裡得到了spring 的webApplicationContext ,spring的bean都放在裡面,然後直接getBean就可以得到了
上下文——webApplicationContext 與servletContext