Spring boot- inject service into doFiler

后端 未结 2 983
挽巷
挽巷 2021-01-26 12:55

I am trying to inject a auth service to a Filter -

@Autowired
AuthRequestService authService;

And use it in doFiler

相关标签:
2条回答
  • 2021-01-26 13:04

    Your filter is not under the control of spring. That´s why the autowired dependencies are not being injected.

    In your filter init code add this line:

    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    

    or

    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,getServletContext());
    

    But there are more other ways to register a servlet filter in spring context: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans

    0 讨论(0)
  • 2021-01-26 13:15

    You could use constructor injection. Supposed your filter registration bean lives in a component and has access to the service you could autowire it there and pass it with the constructor

    @Autowired  
    AuthRequestService authRequestService;
    
    [...]
    
    FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
    filterRegBean.setFilter(new SAPServiceFilter(authRequestService));
    
    0 讨论(0)
提交回复
热议问题