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

3

我想获得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();

希望自己能更出色一些。

1个回答

7

Spring可以将同一类型的所有bean自动装配到列表中,如果您的bean使用了@Ordered注解或实现了Ordered接口,则此列表将按顺序包含所有bean。(Spring 参考文档

@Autowired文档:

对于集合(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);

是的,问题在于我无法将传统类转换为Spring受控bean。 - ticktock
编译错误.. sort() 接受的是 List,而不是 getBeansOfType 返回的 Map。不过我会深入研究 OrderComparator 的,谢谢! - ticktock
嘿,Alex,感谢你的所有帮助。我做了类似的事情...有趣的是,它们仍然无序进入。 - ticktock
1
啊,我错了。还有一个AnnotationAwareOrderComparator,它考虑了Order注解。OrderComparator仅在Ordered接口中搜索排序值。再试一次吧:D - Alex Ciocan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接