'Spring injection in Filter implementation mapped in web.xml

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;

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.

Is it because container filtering takes place outside the Spring context? Is there any way to have Spring injection in Filter implementation mapped in web.xml?



Solution 1:[1]

One more solution if you are using spring security and extending the OncePerRequestFilter

@Component
public class CustomAuthorizationFilter extends OncePerRequestFilter{

    @Autowired
    ResourceConfig resourceConfig;

    public CustomAuthorizationFilter() {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }
//...your code

its important to pull the details from resourceConfig in doFilterInternal block only so you will get values else you may end up at null pointer exception.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1