Unable to autowire the service inside my authentication filter in Spring

后端 未结 6 2170
无人及你
无人及你 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:40

    If your filter class extends GenericFilterBean you can get a reference to a bean in your app context this way:

    public void initFilterBean() throws ServletException {
    
    @Override
    public void initFilterBean() throws ServletException {
    
            WebApplicationContext webApplicationContext =
                WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            //reference to bean from app context
            yourBeanToInject = webApplicationContext.getBean(yourBeanToInject.class);
    
            //do something with your bean
            propertyValue = yourBeanToInject.getValue("propertyName");
    }
    

    And here is less explicit way for those who doesn't like hardcoding bean names or need to inject more than one bean reference into the filter:

    @Autowired
    private YourBeanToInject yourBeanToInject;
    
    @Override
    public void initFilterBean() throws ServletException{
    
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, getServletContext());
    
        //do something with your bean
        propertyValue = yourBeanToInject.getValue("propertyName");
    }
    

提交回复
热议问题