栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

无法在Spring中自动连接我的身份验证筛选器中的服务

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

无法在Spring中自动连接我的身份验证筛选器中的服务

你不能使用开箱即用的过滤器中的依赖项注入。尽管你正在使用GenericFilterBean,但是Servlet过滤器不是由spring管理的。如javadocs所指出的

This generic filter base class has no dependency on the Spring org.springframework.context.ApplicationContext concept. Filters usually don't load their own context but rather access service beans from the Spring root application context, accessible via the filter's ServletContext (see org.springframework.web.context.support.WebApplicationContextUtils).

用简单的英语来说,我们不能指望spring注入服务,但是我们可以在第一次调用时就懒惰设置它。例如

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {    private MyServices service;    @Override    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {        if(service==null){ ServletContext servletContext = request.getServletContext(); WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); service = webApplicationContext.getBean(MyServices.class);        }        your pre ...        }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407865.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号