【发布时间】:2019-05-27 20:07:35
【问题描述】:
我的库必须处理以任意顺序指定的多个 bean(拦截器)(因为它们分布在多个配置文件中)。
在我可以应用它们之前,我必须按它们的优先级对它们进行排序。我为此使用AnnotationAwareOrderComparator.sort(beans)。只要在该拦截器的类级别上添加了@Order 注释,这就会很好地工作。
但是当我尝试在@Bean 方法的@Configuration 类中使用它时它不起作用:
@Configuration
public class Config {
@Bean
@Order(1)
public ServerInterceptor exceptionTranslatingServerInterceptor() {
return ...;
}
@Bean
@Order(2)
public ServerInterceptor authenticatingServerInterceptor() {
return ...;
}
@Bean
@Order(3)
public ServerInterceptor authorizationCheckingServerInterceptor() {
return ...
}
}
但如果我添加这样的测试:
@Test
void testOrderingOfTheDefaultInterceptors() {
List<ServerInterceptor> expected = new ArrayList<>();
expected.add(applicationContext.getBean(ExceptionTranslatingServerInterceptor.class));
expected.add(applicationContext.getBean(AuthenticatingServerInterceptor.class));
expected.add(applicationContext.getBean(AuthorizationCheckingServerInterceptor.class));
List<ServerInterceptor> actual = new ArrayList<>(this.registry.getServerInterceptors());
assertEquals(expected, actual); // Accidentally passes
// System.out.println(actual);
Collections.shuffle(actual);
AnnotationAwareOrderComparator.sort(actual);
assertEquals(expected, actual); // Fails
// System.out.println(actual);
}
那么测试将失败。
从我的调试中我知道AnnotationAwareOrderComparator.findOrder(Object) 总是为这些bean 的顺序返回null(未指定)。可能是因为 bean 实例没有被代理,因此在它们的类级别上既没有实现 order 也没有 order 注释。是否有我必须启用的 BeanPostProcessor 或配置选项?
我如何告诉 spring 保留带注释的顺序或使用应用程序上下文的 bean 定义对 bean 进行适当的排序?
【问题讨论】:
标签: java spring sorting configuration