在Servlet Filter中使用Spring容器

定义一个filter, 实现ApplicationContextAware接口:

public class CacheFilter implements Filter, ApplicationContextAware {
    private static ApplicationContext ctx; // 必须声明为static

@Override
    public void init(FilterConfig config) throws ServletException {
    }

@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

filterChain.doFilter(servletRequest, servletResponse);

}

@Override
    public void destroy() {

}

@Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CacheFilter.ctx = applicationContext; // 保存spring容器到static变量中
    }

然后,在spring配置文件中配置该filter,使之成为容器管理的bean:

<beans:bean />

最后,在web.xml中声明过滤器:

<filter>
        <filter-name>Cache Filter</filter-name>
        <filter-class>com.fh.taolijie.servlet.CacheFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Cache Filter</filter-name>
        <servlet-name>appServlet</servlet-name>
    </filter-mapping>

这时,我们就可以在doFilter()方法中直接通过ApplicationContext检索需要的bean了:

StringRedisTemplate redis = (StringRedisTemplate)ctx.getBean("redisTemplate");

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/a076ed05cf045854421fed1e759cf04e.html