Servlet filter with Spring injection

To use a standard java filter with Spring beans injected utilize Spring's DelegatingFilterProxy. Create a java class that implements Filter. Inject any spring beans that you require.

public class InitializeSessionContextFilter 
  implements javax.servlet.Filter {
  private MyInformation myInfo;
  private FilterConfig filterConfig = null;
  private static org.apache.log4j.Logger log = 
  public void init(FilterConfig filterConfig) 
      throws ServletException {
    this.filterConfig = filterConfig;
  public void destroy() {
    this.filterConfig = null;
  public void doFilter(ServletRequest request, 
      ServletResponse response, FilterChain chain) 
      throws IOException, ServletException {
    log.info("Service Name : " + myInfo.getServiceName());
    chain.doFilter(request, response);

Now just create the filter as a bean

<bean id="initializeSessionFilter"

The last step is to delare the filter in the web.xml. This is wehre the DelegatingFilterProxy is used.


Note that the filter name matches the bean name. This notifies the DelegatingFilterProxy class which bean to use. Now the filter will have access to all of the available beans.

1 comment

Vish, Wed, 05/18/2011 - 11:57

Thanks for this tip. BTW, this doesn't work for Portlets: Spring complains that the filte is not of type javax.servlet.Filter (it is actually of type javax.portlet.filter..). If you ever find out how to make that work, please post. Thanks- Vish.

Post new comment

Subscribe to Syndicate