Dainiel Viltre Dainiel Viltre - 6 months ago 9
Java Question

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>

Answer

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>