Order 3rd party spring filters at bean creation time

Viewed 270

I know filters can be annotated with @Order() but if the filters are all included from different 3rd party libraries can I order them when I create the bean?

@Bean(Ordered.HIGHEST_PRECEDENCE) // Illegal!!!, just an example
SomeFilter someFilter() {
   // this runs before someOtherFilter
   return new SomeFilter();
}

@Bean(Ordered.LOWEST_PRECEDENCE) // Illegal!!!, just an example
SomeOtherFilter someOtherFilter() {
   // this runs after someFilter
   return new SomeOtherFilter();
}
1 Answers

Since you cannot add the @Order annotation on filters, you can still use FilterRegistrationBean like this:

    @Bean
    public FilterRegistrationBean someFilter()
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        SomeFilter filter = new SomeFilter();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns("/bla/*");
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registrationBean;
    }
Related