Spring injection in Filter implementation mapped in web.xml

前端 未结 1 615
Happy的楠姐
Happy的楠姐 2021-01-27 13:48

web.xml:


    myFilter
    com.mypackage.MyFilter


         


        
1条回答
  •  青春惊慌失措
    2021-01-27 14:23

    Since Filter is not a spring bean(it is a web component) the injections won't work inside them. Springs wont inject inside web component.

    use a DelegatingFilterProxy, this is a filter implementation that takes a springbean name as init param and delegates the filter request to that bean.

    
      myFilter
      org.springframework.web.filter.DelegatingFilterProxy
      
        targetBeanName
        myFilterBean
      
    
    
    
      myFilter
      /myFilterPattern/*
    
    

    And create a Bean with name myFilterBean in your spring context.

    public class MyFilter extends GenericFilterBean {
    
        @Autowired
        InjectedBean someInjectedBean;
     
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
          FilterChain chain) throws IOException, ServletException {
            chain.doFilter(request, response);
        }
    }
    

    0 讨论(0)
提交回复
热议问题