问题
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