Why Autowired is not working inside Filter if using FilterRegistrationBean? If I comment @Bean then @Autowired works. What is going on? How should I change my code?
@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;
}
}