春季订购豆类清单 [英] Spring ordered list of beans

查看:96
本文介绍了春季订购豆类清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个实现相同接口的bean. 每个bean都用

I have several beans that implement the same interface. Each bean is annotated with

@Component 
@Order(SORT_ORDER).
public class MyClass implements BeanInterface{
    ...
}

在某一时刻,我自动装配了一个组件列表,并希望得到一个经过排序的bean列表. Bean列表未按照我使用批注设置的顺序进行排序.

At one point I autowire a list of components and I expect a sorted list of beans. The list of beans is not sorted according the orders I have set with the annotation.

我尝试实现Ordered接口,并且发生了相同的行为.

I tried implementing the interface Ordered and the same behaviour occurs.

@Component
public class Factory{


    @Autowired
    private List<BeanInterface> list; // <- I expect a sorted list here
    ...
}

我做错什么了吗?

推荐答案

我找到了解决该问题的方法,正如您所说,尽管这是一个不错的功能,但它并不意味着要这样做.

I found a solution to the issue, as you say, this annotation is not meant for that despite it would be a nice feature.

要使其工作,只需在包含排序列表的Bean中添加以下代码即可.

To make it work this way its just necessary to add the following code in the bean containing the sorted list.

@PostConstruct
public void init() {
    Collections.sort(list,AnnotationAwareOrderComparator.INSTANCE);
}

希望有帮助.

这篇关于春季订购豆类清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆