将Spring引导服务注入doFiler

时间:2018-10-23 11:06:40

标签: java spring-boot

我正在尝试向Filter-

注入身份验证服务
@Autowired
AuthRequestService authService;

并以doFiler方法使用它-

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    System.out.println("SAPServiceFilter: "+ req.getRequestURI());
    //TODO - create auth sender
    authService.isAuthnticate((HttpServletRequest)request); //null
    chain.doFilter(request, response);
}

我的@SpringBootApplication类的子包中的过滤器类,并带有@service-

注释
@Service
public class AuthRequestService {

    @PostConstruct
    public void init() {
        System.out.println("AuthRequestService @PostConstruct");
    }

    public boolean isAuthnticate(HttpServletRequest request) {
        System.out.println("isAuthnticate");
        return true;
    }
}

使用-列出我所有的豆子时,该类也会出现

for (String name : applicationContext.getBeanDefinitionNames()) {
    System.out.println(name);
}

在调试authService为null时,仍然在FilterRegistrationBean中注册了过滤器的最后一件事-

FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter());

2 个答案:

答案 0 :(得分:1)

您可以使用构造函数注入。假设您的过滤器注册bean位于一个组件中,并且可以访问该服务,您可以在其中自动装配并传递给构造函数

@Autowired  
AuthRequestService authRequestService;

[...]

FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter(authRequestService));

答案 1 :(得分:0)

您的过滤器不受弹簧控制。这就是为什么不自动插入依赖项的原因。

在过滤器初始化代码中添加以下行:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,getServletContext());

但是还有更多其他方法可以在spring上下文中注册servlet过滤器: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans