简体   繁体   English

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

[英]Get List of bean types from application context

I'm interested in getting a list of beans from the Spring ApplicationContext . 我对从Spring ApplicationContext获取bean列表感兴趣。 In particular, these are Ordered beans 特别是这些是Ordered

 @Component
  @Order(value=2)

And I'm in some legacy code that is not Spring enabled, so I've manufactured a method to get the ApplicationContext . 而且我在一些未启用Spring的旧代码中,因此我制造了一种获取ApplicationContext的方法。 For spring beans, I know I can do something like: 对于春豆,我知道我可以做类似的事情:

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

But the ApplicationContext only provides a method getBeansOfType which returns an unordered map. 但是ApplicationContext仅提供了一个getBeansOfType方法,该方法返回无序映射。 I've tried getBeanNames(type) but that also returns things unordered. 我已经尝试过getBeanNames(type)但是它也返回无序的东西。

The only thing I can think of is to create a dummy class that just contains the List, create a bean for that dummy class and retrieve the ordered list: 我唯一想到的就是创建一个仅包含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();

Just wish I could do better. 只是希望我能做得更好。

Spring can autowire all beans of a type into list. Spring可以将所有类型的bean自动装配到列表中。 In addition to this if your beans are annotated with the @Ordered or if the beans implement the Ordered interface, then this list will have all the beans ordered.(Spring reference ) 除此之外,如果您的bean用@Ordered注释,或者如果bean实现了Ordered接口,那么此列表将对所有bean进行排序。(Spring 参考

@Autowired docs: @Autowired文档:

In case of a Collection or Map dependency type, the container will autowire all beans matching the declared value type. 如果是Collection或Map依赖类型,则容器将自动装配所有与声明的值类型匹配的bean。

@Autowired
List<MyType> beans;

EDIT: Ordering using the built-in OrderComparator 编辑:使用内置的OrderComparator进行订购

For your external context call, in order to have your beans prioritized by their order you could take advandate of the built-in comparator: 对于您的外部上下文调用,为了使Bean按其顺序优先,您可以采用内置比较器的优点:

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

Or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM