在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的方式。

<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>

      ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。

       如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml",在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数。

private static ApplicationContext ctx = null;
 public Object getBean(String name) {
      if (ctx == null) {
             ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext);
      }
      return ctx.getBean(name);
 }

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

原文地址

转载于:https://my.oschina.net/sskxyz/blog/714616