Unable to autowire the service inside my authentication filter in Spring

后端 未结 6 2175
无人及你
无人及你 2020-11-29 23:11

I am trying to authenticate user by token, But when i try to auto wire one my services inside the AuthenticationTokenProcessingFilter i get null pointer excepti

6条回答
  •  旧巷少年郎
    2020-11-29 23:46

    It's an old enough question, but I'll add my answer for those who like me google this issue.

    You must inherit your filter from GenericFilterBean and mark it as a Spring @Component

    @Component
    public class MyFilter extends GenericFilterBean {
    
        @Autowired
        private MyComponent myComponent;
    
     //implementation
    
    }
    

    And then register it in Spring context:

    @Configuration
    public class MyFilterConfigurerAdapter extends WebMvcConfigurerAdapter {
    
        @Autowired
        private MyFilter myFilter;
    
        @Bean
        public FilterRegistrationBean myFilterRegistrationBean() {
            FilterRegistrationBean regBean = new FilterRegistrationBean();
            regBean.setFilter(myFilter);
            regBean.setOrder(1);
            regBean.addUrlPatterns("/myFilteredURLPattern");
    
            return regBean;
        }
    }
    

    This properly autowires your components in the filter.

提交回复
热议问题