java - 从应用程序上下文中获取 bean 类型列表

标签 java spring

我有兴趣从 Spring ApplicationContext 获取 bean 列表。特别是,这些是 Ordered beans

 @Component
  @Order(value=2)

我在一些未启用 Spring 的遗留代码中,因此我创建了一个获取 ApplicationContext 的方法。对于 spring bean,我知道我可以做类似的事情:

@Bean
public SomeType someType(List<OtherType> otherTypes) {
    SomeType someType = new SomeType(otherTypes);
    return someType;
}

但是 ApplicationContext 只提供了一个返回无序映射的方法 getBeansOfType。我试过 getBeanNames(type) 但它也返回无序的东西。

我唯一能想到的是创建一个仅包含列表的虚拟类,为该虚拟类创建一个 bean 并检索有序列表:

public class DumbOtherTypeCollection {
    private final List<OtherType) otherTypes;
    public DumbOtherTypeCollection(List<OtherType) otherTypes) {
        this.otherTypes = otherTypes;
    }

    List<OtherType> getOrderedOtherTypes() { return otherTypes; }
}

@Bean 
DumbOtherTypeCollection wasteOfTimeReally(List<OtherType otherTypes) {
    return new DumbOtherTypeCollection(otherTypes);
}

....

applicationContext.getBean(DumbOtherTypeCollection.class).getOrderedOtherTypes();

只是希望我能做得更好。

最佳答案

Spring 可以将一个类型的所有 bean Autowiring 到列表中。除此之外,如果你的 bean 被注释为 @Ordered 或者如果 bean 实现了 Ordered 接口(interface),那么这个列表将包含所有的 beans。(Spring reference)

@Autowired 文档:

In case of a Collection or Map dependency type, the container will autowire all beans matching the declared value type.

@Autowired
List<MyType> beans;

编辑:使用内置的 OrderComparator 进行排序

对于您的外部上下文调用,为了让您的 bean 按顺序排列优先级,您可以使用内置比较器:

org.springframework.core.annotation.AnnotationAwareOrderComparator(new ArrayList(applicationContext.getBeansOfType(...).values()));

或者

Collections.sort((List<Object>)applicationContext.getBeansOfType(...).values(),org.springframework.core.annotation.AnnotationAwareOrderComparator.INSTANCE);

关于java - 从应用程序上下文中获取 bean 类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41289887/

相关文章:

java - Spring boot Hibernate 一对多关系

java - Spring Data JPA 查询 + 交叉表

java - 在 Spring Data Query 中过滤子对象

spring - CommonsMultipartResolver setMaxUploadSize 限制文件大小还是请求大小?

java - jFreeChart 中的条形图 w 条形图均从特定范围开始

java - 不知道我是如何以及在哪里陷入这个无限循环的

java - JPopupMenu 的 JMenuItem 的热键

Java 1.8 : TLSv1. 2 ClientHello 握手失败(缺少椭圆曲线扩展?)

java - 在 Spring 批处理中重复作业(并停止、开始)

spring - 如何使用 Spring Batch 读取多个表