在Servlet(或者Filter,或者Listener)中使用spring的IOC容器


       web.xml中的加載順序為:listener >> filter >> servlet >> spring。其中filter的執行順序是filter- mapping在web.xml中出現的先后順序。

       加載順序會影響對spring bean的調用。比如filter 需要用到bean ,但是加載順序是先加載filter 后加載spring,則filter中初始化操作中的bean為null。所以,如果過濾器中要使用到 bean,可以將spring 的加載改成Listener的方式。

1 <context-param>
2   <param-name>contextConfigLocation</param-name>
3   <param-value>classpath:applicationContext.xml</param-value>
4  </context-param>
5 <listener>   
6    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
7 </listener>

      ContextLoaderListener的作用就是啟動Web容器時,自動裝配ApplicationContext的配置信息。

       如果在web.xml中不寫任何參數配置信息,默認的路徑是"/WEB-INF/applicationContext.xml",在WEB-INF目錄下創建的xml文件的名稱必須是applicationContext.xml。如果是要自定義文件名可以在web.xml里加入contextConfigLocation這個context參數。

1  private static ApplicationContext ctx = null;
2  public Object getBean(String name) {
3       if (ctx == null) {
4              ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext);
5       }
6       return ctx.getBean(name);
7  }

在servlet或者filter或者Listener中使用spring的IOC容器的方法是:

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); 

由於spring是注入的對象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 對象:

WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

事實上WebApplicationContextUtils.getWebApplicationContext方法就是使用上面的代碼實現的,建議使用上面上面的靜態方法 

注意:在使用webApplicationContext.getBean("ServiceName")的時候,前面強制轉化要使用接口,如果使用實現類會報類型轉換錯誤。如:

LUserService userService = (LUserService) webApplicationContext.getBean("userService");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM