Search code examples
springfilterspring-bootannotations

SpringBoot how to set order of Filter without annotation


I'm trying to insert (at first position) a simple custom Cors filter inside the spring filter chain.

If I do it like this

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

it works perfectly I can verify it by putting a breakpoint in Spring's ServletHandler.java where there the line

chain=getFilterChain(baseRequest, target, servlet_holder);

I was just wondering if I wish not to use @Componenent and @Order and instead defining the Filter bean the Application context. How can I set the order of the filters ?


Solution

  • See example: In your class ServletInitializer:

    @Bean
     public FilterRegistrationBean requestLogFilter() {
            final FilterRegistrationBean reg = new FilterRegistrationBean(createRequestLogFilter());
            reg.addUrlPatterns("/*");
            reg.setOrder(1); //defines filter execution order
            return reg;
     }
    
     @Bean
     public RequestLogFilter createRequestLogFilter(){
            return new RequestLogFilter();
     }
    

    the name of my filter is "requestLogFilter"

    Warning: Don't use @Component annotation at the class Filter.