Spring ordered list of beans Spring ordered list of beans spring spring

Spring ordered list of beans


Ordering autowired collections is supported since Spring 4.

See: Spring 4 Ordering Autowired Collections

Summary: if you add @Order(value=1), @Order(value=2)... to your bean definitions, they will be injected in a collection ordered according to the value parameter. This is not the same as declaring that you want the collection in natural order - for that you have to explicitly sort the list yourself after receiving it, as per Jordi P.S.'s answer.


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.

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

Hope it helps.


The @Order annotation is used to specify the order in which AOP advice is executed, it doesn't sort lists. To achieve sorting on your list have your BeanInterface classes implement the Comparable interface and override the compareTo method to specify how the objects should be sorted. Then you can sort the list using Collections.sort(list). Assuming BeanInterface has a method called getSortOrder that returns an Integer object specifying the object's sort order, you could do something like this:

@Component public class MyClass implements BeanInterface, Comparable<BeanInterface> {    public Integer getSortOrder() {        return sortOrder;    }    public int compareTo(BeanInterface other) {        return getSortOrder().compareTo(other.getSortOrder());    }}

Then you can sort the list like this:

Collections.sort(list);