在bean创建时订购第三方弹簧过滤器

时间:2018-11-12 11:05:49

标签: java spring spring-boot

我知道过滤器可以使用@Order()进行注释,但是如果所有过滤器都来自不同的第三方库,那么在创建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 个答案:

答案 0 :(得分:1)

由于无法在过滤器上添加@Order批注,因此您仍可以像这样使用FilterRegistrationBean

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