webApplicationContext 與servletContext

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就可以得到了
項目中的應用:
//獲取實例,方法1
ServletContext sc = ServletActionContext.getRequest().getSession().getServletContext();
WebApplicationContext wac = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//方法2
//WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());

PersonService personService = (PersonService) wac.getBean("personServiceBean");//Spring 控制反轉
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章