SpringBoot how to set filter order without annotation

I am trying to insert (in 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 fine I can check this by setting a breakpoint in spring ServletHandler.java where there is a line

chain=getFilterChain(baseRequest, target, servlet_holder);

I'm just wondering if I want to not use @Componenent and @Orderand instead define the context of the bean application. How to set the order of filters?

+1
source share
2 answers

See an example: In your ServletInitializer class:

@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();
 }

my filter name is "requestLogFilter"

: @Component .

+4

corsFilter, , , springSecurityFilterChain , errorPageFilter spring , . CORS , . :

@Configuration
public class MyConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(Integer.MIN_VALUE);
        return bean;
    }
}

bean.setOrder(Integer.MIN_VALUE) , . , errorPage , Integer.MIN_VALUE (-2147483648).

+3

Source: https://habr.com/ru/post/1655512/


All Articles