How can I get a Spring bean in a servlet filter?

There are three ways:

  1. Use WebApplicationContextUtils:

    public void init(FilterConfig cfg) { 
        ApplicationContext ctx = WebApplicationContextUtils
          .getRequiredWebApplicationContext(cfg.getServletContext());
        this.bean = ctx.getBean(YourBeanType.class);
    }
    
  2. Using the DelegatingFilterProxy – you map that filter, and declare your filter as bean. The delegating proxy will then invoke all beans that implement the Filter interface.

  3. Use @Configurable on your filter. I would prefer one of the other two options though. (This option uses aspectj weaving)

Leave a Comment