Spring Framework 过滤器,未注入 bean [英] Spring Framework filter, bean not injected
问题描述
Servlet 过滤器有 2 个条目,一个在 web.xml 中,一个在 Spring applicationContext.xml 中
There are 2 entries for a Servlet Filter, one in web.xml and one in Spring applicationContext.xml
我将过滤器添加到 applicationContext.xml 中,因为我想将 creditProcessor bean 注入其中.
I added the filter into applicationContext.xml because I wanted to inject creditProcessor bean into it.
唯一的问题是 web.xml 中的条目被 JBoss 拾取然后使用,所以 creditProcessor 为空.
The only problem is that the entry in web.xml got picked up by JBoss and then used, so creditProcessor is null.
我是否必须使用 Spring 的 delegatingFilterProxy 或类似工具才能将内容注入 bean,或者是否可以调整 web.xml?
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:
Spring-applicationContext.xml:
<bean id="creditFilter" class="credit.filter.CreditFilter" >
<property name="creditProcessor" ref="creditProcessor"/>
</bean>
推荐答案
你不能像这样管理一个过滤器弹簧.通过您的设置,它由 spring 实例化一次,由 servlet 容器实例化一次.相反,使用 DelegatingFilterProxy
:
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
:
- 在 web.xml 中将过滤器代理声明为
设置过滤器定义的
targetBeanName
init-param 以指定应该实际处理过滤的 bean:
- declare the filter proxy as a
<filter>
in web.xml 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>
这篇关于Spring Framework 过滤器,未注入 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!