Sunday, February 8, 2009

Standard injection into Servlet/Filter - Spring

I understood that spring dependency injection for beans which
implements standard servlet 2.3 Filter innterface, declared in applicationContext.xml is not working in usual manner. For this one, I had to involve DelegatingFilterProxy class which is delegating to a Spring-managed bean that implements the Filter interface. I have a filter class called 'PDAFilter' which implements standard Filter interface and have a bean entry in the applicationContext.xml file fallows.
<bean id="pdaFilter" class="com.axiohelix.pda.main.PDAFilter">
   <property name="hibernateUtil" ref="hibernateUtil" />
</bean>

PDAFilter implements Filter.init(), Filter.doFilter() and Filter.destroy() methods. While creating PDAFilter instance,I needed to inject instance of HibernateUtil class into it. Usual injection always results in null HibernateUtil object. Spring's DelegatingFilterProxy class can be used for this kind of injection. We have to add the fallowing entry into web.xml file.

<filter>
  <filter-name>pdaFilter</filter-name>
     <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
  <init-param>
     <param-name>targetFilterLifecycle</param-name>
     <param-value>true</param-value>
</init-param>
</filter>
All calls to the filter proxy will then be delegated to that bean in the Spring context, which is required to implement the standard Servlet 2.3 Filter interface. The lifecycle methods defined by Filter interface will not be invoked by this kind of implementation. The servlet api expects in from spring context. But spring context is not handling licecyle methods. To force servlet api to invoke the licecyle methods, I have set 'targetFilterLifecyle' to 'true'.
Share

Widgets