Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Framework filter, bean not injected

There are 2 entries for a Servlet Filter, one in web.xml and one in Spring applicationContext.xml

I added the filter into applicationContext.xml because I wanted to inject creditProcessor bean into it.

The only problem is that the entry in web.xml got picked up by JBoss and then used, so creditProcessor is null.

Do I have to use Spring's delegatingFilterProxy or similar so I can inject stuffs into the bean, or can I tweak the web.xml?

web.xml:

<filter>
    <filter-name>CreditFilter</filter-name>
    <filter-class>credit.filter.CreditFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CreditFilter</filter-name>
    <url-pattern>/coverage/*</url-pattern>        
</filter-mapping>

Spring-applicationContext.xml:

<bean id="creditFilter" class="credit.filter.CreditFilter" >
      <property name="creditProcessor" ref="creditProcessor"/>
</bean>
like image 996
Lydon Ch Avatar asked Oct 02 '10 20:10

Lydon Ch


1 Answers

You can't make a Filter spring managed like this. With your setup it is instantiated once by spring, and once by the servlet container. Instead, use DelegatingFilterProxy:

  1. declare the filter proxy as a <filter> in web.xml
  2. Set the targetBeanName init-param of the filter definition to specify the bean that should actually handle the filtering:

    <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>creditFilter</param-value>
    </init-param>
    
like image 56
Bozho Avatar answered Sep 19 '22 01:09

Bozho