JAVA WEB 过滤器(Filter)中向容器 Spring 注入 bean

2022-11-25,,,,

  如果直接使用 @Autoware 获取 bean 会直接使该 bean 为 null,这是因为这种配置过滤器的方法无法在过滤器中使用 Spring bean,因为 Filter 比 bean 先加载,也就是 Spring 会先加载 Filter 指定的类到 Container 中,这样 Filter 中注入的 Spring bean 就为 null 了。

解决方法:  

  1. 直接在 init() 初始化方法中手动配置 bean。

  (1)开始的声明

 MenuService menuService = null;
ApplicationContext applicationContext = null;

  (2)初始化方法

 @Override
public void init(FilterConfig filterConfig) throws ServletException {
// 手动配置 bean
ServletContext servletContext = filterConfig.getServletContext();
applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
menuService = (MenuService) applicationContext.getBean("menuService");
}

  (3)doFilter() 方法的使用

 menuService.getOwnMenuByUserId(userId.toString(), loginType.toString());

  2. 代理 —— DelegatingFilterProxy 类。

配置过滤器:

 <filter>
<filter-name>permission</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

在 Spring 的配置文件中配置:

 <bean id="permission" class="com.my.myfilter">  

DelegatingFilterProxy 类遵循 filter-name-bean 的原则,会根据 web.xml 中 filter-name 的值查找到 spring 配置文件中 id 与 filter-name 相同的值,然后把接受到的处理信息传递给相对应的类处理。如果想自定义 filter 处理的 bean,可以在 filter 配置中添加下面一段:

 <init-param>
<param-name>targetBeanName</param-name>
<param-value>Spring-bean-name</param-value>
</init-param>

这句话会指定该 filter 使用 Spring-bean-name 去处理该请求。这时候你会发现 Filter.init() 和 Filter.destory() 无法使用 spring bean,这是因为默认 filter 的生命周期是有 tomcat 这类服务器管理的,在配置:

 <init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>

这时候就是由 spring 管理 filter 的生命周期,这样就可以在 init() 和 destory() 使用 spring bean 了。

还有一个重要的事情,有时候你会发现在请求 filter 处理的 url 的时候程序会报错 —— No WebApplicationContext found: no ContextLoaderListener registered?

出现这个的原因是因为:filter 会优于 servlet 先加载到容器里面,如果我们只是在 org.springframework.web.servlet.DispatcherServlet 中配置了 contextConfigLocation,指定了 spring 配置文件位置的话,程序会无法访问 spring bean,解决方法很简单,在 web.xml 配置上:

 <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/conf/web-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

这样让 spring bean 第一时间加载到容器里面,这样就不会有 No WebApplicationContext found: no ContextLoaderListener registered? 这个错误了。

以上第一个方法亲测完全可以实现,第二种方法暂未测试,第二种方法来源地址:

http://blog.csdn.net/godha/article/details/13025099

JAVA WEB 过滤器(Filter)中向容器 Spring 注入 bean的相关教程结束。

《JAVA WEB 过滤器(Filter)中向容器 Spring 注入 bean.doc》

下载本文的Word格式文档,以方便收藏与打印。