首页 文章

Spring Framework过滤器,bean没有注入

提问于
浏览
6

Servlet过滤器有2个条目,一个在web.xml中,另一个在Spring applicationContext.xml中

我将过滤器添加到applicationContext.xml中,因为我想将creditProcessor bean注入其中 .

唯一的问题是web.xml中的条目被JBoss拾取然后使用,因此creditProcessor为null .

我是否必须使用Spring的delegingFilterProxy或类似的东西,以便我可以将东西注入bean中,或者我可以调整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>

1 回答

  • 12

    你不能像这样管理过滤 spring . 使用您的设置,它将由spring实例化一次,并由servlet容器实例化一次 . 相反,使用DelegatingFilterProxy

    • 在web.xml中将过滤器代理声明为 <filter>

    • 设置过滤器定义的 targetBeanName init-param以指定应该实际处理过滤的bean:

    <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>creditFilter</param-value>
    </init-param>
    

相关问题