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