简体   繁体   中英

How to inject a property value into a filter?

My question is simple. I'm trying to inject a property value into a filter. In my controller class, I used the following code and I could inject the property successfully:

@Controller
public class StatementController {
    @Value("${xapi.version}")
    private String version;
...
}

but when I use the same code in a custom filter,I get a null value in version property. This is the code:

public class HeaderFilter extends OncePerRequestFilter {

    @Value("${xapi.version}")
    private String version;
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
logger.error(version==null);
...

I'm using springframework 4.0.9 and this is a fragment of my filter configuration in web.xml:

<filter>
        <filter-name>header</filter-name>
        <filter-class>com.application.HeaderFilter</filter-class>
    </filter>
<filter-mapping>
        <filter-name>header</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Spring @Value injection works for bean managed by spring container (like your controller).

Here your filter is not managed by spring container but by your Java EE container.

You can recover your property in the init method :

WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext()).getEnvironment().getProperty("xapi.version");

You must use a DelegatingFilterProxy to allow your filter to be managed by Spring. It is a special proxy that does all the low level tasks of finding the root application context get the bean and relay all requests to it. Extract from the javadoc:

web.xml will usually contain a DelegatingFilterProxy definition, with the specified filter-name corresponding to a bean name in Spring's root application context. 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 Filter interface.

So you must have a bean of class HeaderFilter to which you give a name (say header ) and you change the filter declaration in your web.xml file to:

@Component

<filter>
    <filter-name>header</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>header</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM