filter加载springbean
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了filter加载springbean相关的知识,希望对你有一定的参考价值。
tomcat容器初始化顺序监听器–>过滤器–>servlet,因此springMVCservlet初始化之前,过滤器就已经初始化过了,如果在过滤器中需要注入spring容器管理的bean是注入不进去的,因此需要在spring监听器中初始化需要注入的bean,才能在过滤器中注入,而且过滤器的定义需要使用spring定义的DelegatingFilterProxy来实现,web.xml部分代码如下
<filter>
<filter-name>testFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>testFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
其余部分只需要在spring容器中加载testFilter就行了,例子testFilter如下:
注意此处的filter必须为实现javax.Filter的类,而且初始化需要放在spring监听器中,即必须在过滤器初始化之前初始化
@Component
public class TestFilter implements Filter
{
private static final Logger logger = LogManager.getLogger(TestFilter.class);
@Autowired
private UserService userService;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException
{
logger.info(JSONArray.fromObject(userService.list()));
filterChain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig)
throws ServletException
{
logger.info("初始化filter");
}
@Override
public void destroy()
{
logger.info("destroyfilter");
}
}
如果要保留Filter原有的init,destroy方法的调用,还需要配置初始化参数targetFilterLifecycle为true,该参数默认为false,代码例子如下:
<filter>
<filter-name>testFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>testFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
以上是关于filter加载springbean的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot脚手架项目002-004.Spring IOC_权限管理系统_Spring:什么是IOCSpring Bean注入SpringBean的注解bean的加载流程