Spring injection in Filter implementation mapped in web.xml

一曲冷凌霜 提交于 2020-07-16 09:21:21

问题


web.xml:

<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>com.mypackage.MyFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/myFilterPattern/*</url-pattern>
</filter-mapping>

MyFilter:

public class MyFilter implements Filter {

    @Autowired
    InjectedBean someInjectedBean;

However, when intercepting /myFilterPattern/* requests, someInjectedBean in MyFilter.doFilter(...) is still null, meaning it has not been injected. The same bean (InjectedBean) is injected fine in other context components that are not referenced in web.xml.

Is it because container filtering takes place outside the Spring context? Is there any way to have Spring injection in Filter implementation mapped in web.xml?


回答1:


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.

<filter>
  <filter-name>myFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  <init-param>
    <param-name>targetBeanName</param-name>
    <param-value>myFilterBean</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>myFilter</filter-name>
  <url-pattern>/myFilterPattern/*</url-pattern>
</filter-mapping>

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);
    }
}


来源:https://stackoverflow.com/questions/43769781/spring-injection-in-filter-implementation-mapped-in-web-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!