Search code examples
javaspringsortingspring-mvcioc-container

Spring ordered list of beans


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

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

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.

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
    ...
}

Am I doing anything wrong?


Solution

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

    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);
    }
    

    Hope it helps.