If you are using Spring Boot, @WebFilter can get automatically instantiated by the Spring Boot Server without relying on Beans definition. The way I found to solve the issue is to register my own filter in the Spring Boot before the @WebFilter is identified by the embedded Tomcat Server. On that way, the @WebFilter is already registered before and the embedded server does not overwrite yours.
In order to achieve that, you need to register the filter before it is found by the server. I did register my filter and made the changes as follows:
/**
* Creates the Bean. Observe that @WebFilter is not registered as a Bean.
*/
@Bean
public SomeFilter someFilter() {
return new SomeFilter();
}
Secondly, you need to register with the same name. It is important to find the name the server is using to register your filter. Usually, if not provided by the @WebFilter tag, it is going to be the complete name of your class
/**
* It is important to keep the same name; when Apache Catalina tries to automatically register the filter,
* it will check that is has already been registered.
* @param filter SomeFilter
* @return
*/
@Bean
public FilterRegistrationBean registration(SomeFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(true);
registration.setAsyncSupported(true);
registration.setName("some.class.path.for.some.filter.SomeFilter");
registration.setUrlPatterns(Lists.<String>newArrayList("/some-url-does-not-exist/*"));
return registration;
}
In my scenario, I had to enable async=true, so I have added that line as well.