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

tic*_*ock 3 java spring

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

 @Component
  @Order(value=2)
Run Code Online (Sandbox Code Playgroud)

而且我在一些未启用 Spring 的遗留代码中,所以我制造了一种方法来获取ApplicationContext. 对于春豆,我知道我可以这样做:

@Bean
public SomeType someType(List<OtherType> otherTypes) {
    SomeType someType = new SomeType(otherTypes);
    return someType;
}
Run Code Online (Sandbox Code Playgroud)

ApplicationContextonly 提供了一种getBeansOfType返回无序映射的方法。我试过,getBeanNames(type)但这也会返回无序的东西。

我唯一能想到的是创建一个只包含 List 的虚拟类,为该虚拟类创建一个 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();
Run Code Online (Sandbox Code Playgroud)

只是希望我能做得更好。

Ale*_*can 6

Spring 可以将某个类型的所有 bean 自动装配到列表中。除此之外,如果您的 bean 用@Ordered或 如果 bean 实现了Ordered接口注释,那么这个列表将包含所有 bean 的排序。(Spring参考

@Autowired 文档:

在 Collection 或 Map 依赖类型的情况下,容器将自动装配与声明的值类型匹配的所有 bean。

@Autowired
List<MyType> beans;
Run Code Online (Sandbox Code Playgroud)

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

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

org.springframework.core.annotation.AnnotationAwareOrderComparator(new ArrayList(applicationContext.getBeansOfType(...).values()));
Run Code Online (Sandbox Code Playgroud)

或者

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