What is the use of @Order annotation in Spring?

SpringSpring SecurityAnnotations

Spring Problem Overview


I have come across a glance of code which uses @Order annotation. I want to know what is the use of this annotation with respect to Spring Security or Spring MVC.

Here is an example:

Spring Solutions


Solution 1 - Spring

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 - Spring

@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 - Spring

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQasimView Question on Stackoverflow
Solution 1 - SpringPatrik BegoView Answer on Stackoverflow
Solution 2 - SpringScorpioView Answer on Stackoverflow
Solution 3 - SpringPraful JhaView Answer on Stackoverflow