This post will discuss how to create custom filters in a Spring Boot application that can apply to all URLs or only to certain URL patterns.

There are several ways to register a filter class in the Spring Boot application.

1. Implement the Filter interface

To create a custom filter, we can implement the Filter interface and annotate the filter with one of the Spring stereotypes, such as @Component for Spring to recognize it.

 
We can also extend the abstract class OncePerRequestFilter and annotate the filter with @Component. This is demonstrated below:

2. Register a @Bean of type FilterRegistrationBean

The above filter applies to all requests. If we want our filter to only apply to certain URL patterns, we can remove the @Component annotation from our filter class definition and register a @Bean of type FilterRegistrationBean in Spring @Configuration.

For example, the following filter applies to URLs that match the /execute/* pattern.

3. Using Servlet’s @WebFilter annotation

We can also use Servlet annotation @WebFilter to declare a filter that accepts only certain URL patterns. Since @WebFilter is not a Spring’s annotation, we need to use @ServletComponentScan annotation to register it, which can be added along with @SpringBootApplication annotation in the Main class.

That’s all about creating filters in Spring Boot.