码迷,mamicode.com
首页 > 编程语言 > 详细

filter加载springbean

时间:2017-09-14 13:31:41      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:object   autowired   保留   word   vbscrip   code   title   test   not   

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

标签:object   autowired   保留   word   vbscrip   code   title   test   not   

原文地址:http://www.cnblogs.com/sunys/p/7519733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!