您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

无法在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 code ...    
    }

}
Java 2022/1/1 18:16:12 有552人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶