Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
Jordi P.S. Avatar asked Jun 06 '13 17:06

Jordi P.S.


People also ask

How do I list all beans in a Spring Boot application?

A bean is the foundation of a Spring-managed application; all beans reside withing the IOC container, which is responsible for managing their life cycle. We can get a list of all beans within this container in two ways: Using a ListableBeanFactory interface. Using a Spring Boot Actuator.

What is a a bean in spring?

A bean is the foundation of a Spring-managed application; all beans reside withing the IOC container, which is responsible for managing their life cycle. We can get a list of all beans within this container in two ways:

How to specify the Order of beans while injecting into collection?

We can specify the order of the beans while injecting into the collection. For that purpose, we use the @Order annotation and specify the index: Spring container first will inject the bean with the name “Harry”, as it has the lowest order value. It will then inject the “John”, and finally, the “Adam” bean:

What is @order in Spring Boot?

Spring is a popular Java application framework and Spring Boot is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily. @Order defines the sort order for an annotated component.


2 Answers

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.

like image 159
rubensa Avatar answered Oct 16 '22 10:10

rubensa


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.

like image 26
Jordi P.S. Avatar answered Oct 16 '22 09:10

Jordi P.S.