I wonder, if there is any annotation for a Filter
class (for web applications) in Spring Boot? Perhaps @Filter
?
I want to add a custom filter in my project.
The Spring Boot Reference Guide mentioned about
FilterRegistrationBean
, but I am not sure how to use it.
If you use Spring Boot + Spring Security, you can do that in the security configuration.
In the below example, I'm adding a custom filter before the UsernamePasswordAuthenticationFilter (see all the default Spring Security filters and their order).
And the filter class
It's more an advice than answer, but if you are using a Spring MVC in your web application the good idea is to use Spring HandlerInterceptor instead of Filter
It can do the same job, but also - Can work with ModelAndView - Its methods can be called before and after request processing, or after request completion.
- It can be easily tested
1 Implement HandlerInterceptor interface and add a @Component annotation to your class
2 Configure your Interceptor
I saw answer by @Vasily Komarov. Similar approach, but using abstract HandlerInterceptorAdapter class instead of using HandlerInterceptor.
Here is an example...
You need to implement Filter and need to be annotated with @WebFilter(urlPatterns="/*")
And in Application or Configuration class you need to add @ServletComponentScan By this it your filter will get registered.
There isn't a special annotation to denote a servlet filter. You just declare a
@Bean
of typeFilter
(orFilterRegistrationBean
). An example (adding a custom header to all responses) is in Boot's own EndpointWebMvcAutoConfiguration;If you only declare a
Filter
it will be applied to all requests. If you also add aFilterRegistrationBean
you can additionally specify individual servlets and url patterns to apply.Note:
As of Spring Boot 1.4,
FilterRegistrationBean
is not deprecated and simply moved packages fromorg.springframework.boot.context.embedded.FilterRegistrationBean
toorg.springframework.boot.web.servlet.FilterRegistrationBean
There are three ways to add your filter,
@Component
@Bean
withFilter
type in Spring@Configuration
@Bean
withFilterRegistrationBean
type in Spring@Configuration
Either #1 or #2 will do if you want your filter applies to all requests without customization, use #3 otherwise. You don't need to specify component scan for #1 to work as long as you place your filter class in the same or sub-package of your
SpringApplication
class. For #3, use along with #2 is only necessary when you want Spring to manage your filter class such as have it auto wired dependencies. It works just fine for me to new my filter which doesn't need any dependency autowiring/injection.Although combining #2 and #3 works fine, I was surprised it doesn't end up with two filters applying twice. My guess is that Spring combines the two beans as one when it calls the same method to create both of them. In case you want to use #3 alone with authowiring, you can
AutowireCapableBeanFactory
. The following is an example,