filter中注入Spring MVC bean

Author Avatar
ieayoio 11月 04, 2016
  • 在其它设备中阅读本文章

最近需要在filter中添加一些log,然而需要注入一些Sping mvc的bean,直接使用发现完全不起效果,根本没有注入,调用的对象一直为空,就研究了一下,起初一直不起作用,后来发现原来是没有指定contextConfigLocation,现将代码记录下来,以备用:

原本的filter如下:

1
2
3
4
5
6
7
8
9
<filter>
<filter-name>RequestFilter</filter-name>
<filter-class>cn.ieayoio.filter.RequestFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

现在要以Spring代理过滤器,代码替换为如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<filter>
<filter-name>requestFilter</filter-name> <!--过滤器的名字-->
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>requestFilter</param-value> <!--自己定义的bean-->
</init-param>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>requestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

然后需要在Spring配置文件加入这个bean,class指向原过滤器的类名:

1
2
<beans:bean id="requestFilter" class="cn.ieayoio.filter.RequestFilter">
</beans:bean>

最后还需要在xml中添加contextConfigLocation

1
2
3
4
5
6
7
8
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/conf/mvc-dispatcher-servlet.xml, <!--添加在这里-->
classpath*:/WEB-INF/conf/mybatis-config.xml,
classpath*:/WEB-INF/conf/my.properties
</param-value>
</context-param>

这样就可以在filter中注入bean了:

1
2
@Autowired
private UserMapper userMapper;

参考链接:http://blog.csdn.net/godha/article/details/13025099


该博文来自于ieayoio的博客:ieayoio’s blog

本文链接:http://www.ieayoio.com/2016/11/04/filter中注入Spring-MVC的bean/