xml中映射的Filter实现中的春季注入

xml中映射的Filter实现中的春季注入

本文介绍了在web.xml中映射的Filter实现中的春季注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

web.xml:

<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>com.mypackage.MyFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/myFilterPattern/*</url-pattern>
</filter-mapping>

MyFilter:

public class MyFilter implements Filter {

    @Autowired
    InjectedBean someInjectedBean;

但是,当拦截/myFilterPattern/*请求时,MyFilter.doFilter(...)中的someInjectedBean仍然为空,这意味着它尚未被注入.在web.xml中未引用的其他上下文组件中,可以很好地注入相同的bean(InjectedBean).

However, when intercepting /myFilterPattern/* requests, someInjectedBean in MyFilter.doFilter(...) is still null, meaning it has not been injected. The same bean (InjectedBean) is injected fine in other context components that are not referenced in web.xml.

是因为容器过滤发生在Spring上下文之外吗?有什么办法可以在web.xml中映射过滤器实现中的Spring注入?

推荐答案

由于Filter不是Spring bean(它是一个Web组件),因此注入将无法在其中进行. Springs不会注入Web组件内部.

Since Filter is not a spring bean(it is a web component) the injections won't work inside them. Springs wont inject inside web component.

使用DelegatingFilterProxy,这是一个过滤器实现,它以springbean名称作为初始参数,并将过滤器请求委托给该bean.

use a DelegatingFilterProxy, this is a filter implementation that takes a springbean name as init param and delegates the filter request to that bean.

<filter>
  <filter-name>myFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  <init-param>
    <param-name>targetBeanName</param-name>
    <param-value>myFilterBean</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>myFilter</filter-name>
  <url-pattern>/myFilterPattern/*</url-pattern>
</filter-mapping>

并在您的spring上下文中创建一个名为myFilterBean的Bean.

And create a Bean with name myFilterBean in your spring context.

public class MyFilter extends GenericFilterBean {

    @Autowired
    InjectedBean someInjectedBean;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }
}

这篇关于在web.xml中映射的Filter实现中的春季注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 09:38