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

时间:2016-12-22 18:50:07

标签: java spring

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

 @Component
  @Order(value=2)

我在一些未启用Spring的遗留代码中,所以我制作了一个获取ApplicationContext的方法。对于春豆,我知道我可以做类似的事情:

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

但是ApplicationContext只提供了一个返回无序地图的方法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();

希望我能做得更好。

1 个答案:

答案 0 :(得分:3)

Spring可以将类型的所有bean自动装配到列表中。除此之外,如果您的bean使用@Ordered注释,或者bean实现Ordered接口,那么此列表将包含所有bean。(Spring reference

@Autowired docs:

  

如果是Collection或Map依赖类型,容器将自动装配与声明的值类型匹配的所有bean。

@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);
相关问题