代码之家  ›  专栏  ›  技术社区  ›  Andreas Wederbrand

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

  •  2
  • Andreas Wederbrand  · 技术社区  · 6 年前

    我知道可以用@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 回复  |  直到 6 年前
        1
  •  1
  •   user10639668    6 年前

    由于不能在过滤器上添加@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;
        }