ServletFilter with Spring Dependency Injection

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:

  1. Implement the filter (implementing the javax.servlet.Filter interface)
  2. Define it as a Spring bean either through annotation, XML or Java configuration
  3. 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.

Combining standalone application with Spring

When you are developing a standalone application, that you want to use with the SpringFramework, somewhere in your code you will have to load the application context. Potentially this results in chicken-egg problem, especially when you want to use a component in some class that is not a bean. This may have different causes:

  • It is the main class, that is used to start up the application
  • The constructor uses arguments that cannot be resolved with autowireing

There are different approaches to solve this, the most elegant one I will demonstrate. „Combining standalone application with Spring“ weiterlesen