Recently I stumbled upon the task to implement a ServletFilter in our Spring MVC web application. The filter should use one of the services we defined as bean, so it was natural to find a way to implement a servletFilter as a Spring bean so DI can be leveraged.
I got lucky, as I stumbled on this post in German, detailing what has to be done. Basically there are three things to do:
- Implement the filter (implementing the javax.servlet.Filter interface)
- Define it as a Spring bean either through annotation, XML or Java configuration
- Use
org.springframework.web.filter.DelegatingFilterProxy
as the filter class in your web.xml. The filter-name must match the name of your bean.
If your filter implements an init or destroy method, which actually do something, you also have to specify the init-param targetFilterLifecycle with the value true, to force the proxy to call these methods on the underlying bean.
<init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> That's it.