如果使用 FilterRegistrationBean,为什么 Autowired 不能在 Filter 内部工作?

Why Autowired is not working inside Filter if using FilterRegistrationBean?

如果使用 FilterRegistrationBean,为什么 Autowired 不能在 Filter 内部工作? 如果我评论@Bean 然后@Autowired 工作。 到底是怎么回事? 我应该如何更改我的代码?

@Component
public class MyFilter1 extends OncePerRequestFilter {

  //PROPERTIES
  @Autowired MyService myService;

  //===================================================================
  // DO FILTER INTERNAL
  //===================================================================
  @Override
  public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    //MyService myService = new MyService();
    System.out.println("myService = " + myService);
    String result = myService.hello();  //Null Pointer Exception when using @Bean
    System.out.println(result);
    chain.doFilter(request, response);
  }

  //===================================================================
  // FILTER REGISTRATION BEAN
  //===================================================================
  @Bean
  public FilterRegistrationBean<MyFilter1> regFilter1(){

    //CREATE REGISTRATION BEAN
    FilterRegistrationBean<MyFilter1> registrationBean = new FilterRegistrationBean<>();
                                      registrationBean.setFilter(new MyFilter1());

    //RETURN REGISTRATION BEAN
    return registrationBean;

  }

}

感谢您的回答。 我已将 @Bean 移动到配置文件中,但问题仍然存在。 我使用 FilterRegistrationBean 的原因是能够使用 addUrlPatterns("/Filtered") ,这不能仅通过注释来完成。

@Configuration
public class FilterConfiguration {

  //===================================================================
  // FILTER REGISTRATION BEAN
  //===================================================================
  @Bean
  public FilterRegistrationBean<MyFilter1> regFilter1(){

    //CREATE REGISTRATION BEAN
    FilterRegistrationBean<MyFilter1> registrationBean = new FilterRegistrationBean<>();
                                      registrationBean.setFilter(new MyFilter1());
                                     registrationBean.addUrlPatterns("/Filtered"); //Apply to specific URL
                                     registrationBean.setOrder(0);                 //To order Filters

    //RETURN REGISTRATION BEAN
    return registrationBean;

  }

}

当您 new 创建 MyFilter1 的实例时,您绕过了 Spring 因此自动装配将不起作用。将 FilterConfiguration class 修改为如下所示:

@Configuration
public class FilterConfiguration {

  @Bean
  public FilterRegistrationBean<MyFilter1> regFilter1(MyFilter1 myFilter){
    FilterRegistrationBean<MyFilter1> registrationBean = new FilterRegistrationBean<>();
    registrationBean.setFilter(myFilter);
                                 
    registrationBean.addUrlPatterns("/Filtered");
    registrationBean.setOrder(0);

    return registrationBean;
  }
}