Using Servlet Filter as a Spring bean with DelegatingFilterProxy

[Last Updated: Jul 14, 2017]

DelegatingFilterProxy can be used as a proxy for a standard Servlet Filter.

DelegatingFilterProxy itself is a Servlet Filter which delegates to a specified Spring-managed bean that implements the Filter interface.

We need to set DelegatingFilterProxy's "targetBeanName" property as the target bean name (the bean which implements Filter interface).

Let's see an example how to use it.


A bean implementing Servlet Filter

public class MyFilter implements Filter {
  private MyService myService;
  public void init (FilterConfig filterConfig) throws ServletException {
  public void doFilter (ServletRequest request, ServletResponse response,
                        FilterChain chain)
            throws IOException, ServletException {
      System.out.println("-- In MyFilter --");
      HttpServletRequest req = (HttpServletRequest) request;
      chain.doFilter(request, response);
  public void destroy () {
public class MyService {

  public void doSomething (HttpServletRequest req) {
      System.out.println("In MyService: " + req.getRequestURI());

Java Config class

public class MyWebConfig {

Registering DelegatingFilterProxy

public class AppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {
  protected Filter[] getServletFilters () {
      DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
      return new Filter[]{filterProxy};

A Controller

public class MyController {
  public String handleRequest () {
      System.out.println("-- handling request in controller --");
      return "dummy response";


Output on server console:

-- In MyFilter --
In MyService: /app
-- handling request in controller --

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • spring-test 4.3.9.RELEASE: Spring TestContext Framework.
  • javax.servlet-api 3.1.0 Java Servlet API
  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Using Servlet Filter as Spring Bean Select All Download
  • servlet-filter-as-spring-bean
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also