What is the use of @Order annotation in Spring?

Solution 1:

It is used for Advice execution precedence.

The highest precedence advice runs first. The lower the number, the higher the precedence. For example, given two pieces of 'before' advice, the one with highest precedence will run first.

Another way of using it is for ordering Autowired collections

@Component
@Order(2)
class Toyota extends Car {
    public String getName() {
        return "Toyota";
    }
}

@Component
@Order(1)
class Mazda extends Car {
    public String getName() {
        return "Mazda";
    }
}

@Component
public class Cars {
    @Autowired
    List<Car> cars;

    public void printNames(String [] args) {

        for(Car car : cars) {
            System.out.println(car.getName())
        }
    }
}

You can find executable code here: https://github.com/patrikbego/spring-order-demo.git

Hope this clarifies it a little bit further.

Output:-

Mazda Toyota

Solution 2:

@Order Annotations (as well as the Ordered interface) implies a specific order, in which the beans will be loaded or prioritized by Spring.

Lower numbers indicate a higher priority. The feature may be used to add beans in a specific order into a collection (ie via @Autowired), among other things.

In your specific example the annotation does not change anything in the class itself. Whereever this specific class is used, it is used with the highest priority (since it is set as '1'), probably since additional, but depending information is being added in other classes, ordered at a lower precedence.

Solution 3:

@Order Annotation specifies the order of loading the bean by spring container. The lower the order(integer), higher is the precedence. So order of 0 will have more precedence than order of 10. Likewise order of -100 will have more precedence than 0.