@Order Annotation in Spring Boot

What is @Order annotation in Spring Boot?

@Order annotation in Spring Boot represents the order of execution of a bean or an annotated component. The annotation @Order has an optional ‘value’ argument which takes an integer value. Based on this value the order of execution of components is decided. Moreover, we are allowed to pass either positive or negative value.

How does @Order annotation work in Spring Boot?

However, the default value is Ordered.LOWEST_PRECEDENCE. This value represents that the component has the lowest priority among all other components. Likewise, the value Ordered.HIGHEST_PRECEDENCE represents that the component has the highest priority among components.

When user provides an integer value into it, the lower value will have the higher precedence. For example, a component having @Order annotation with value 1 will run before value 2.

If Component does not have @Order annotation, it will execute in alphabetical order of bean name by default. Furthermore, if two components are having the same order value, the execution will happen in the alphabetical order of component name.

In summary, below details of order will follow:
1) Components with order value of negative numbers
2) Components with order value of positive number
3) No order value components in alphabetical order of their names

Examples of @Order annotation in Spring Boot?

Let’s consider the below components with @Order annotations in order to decide the final order of their executions.

public class C1 { }

public class C4{ }

public class C3{ }

public class C2{ }

public class C5{ }

public class E{ }

public class D{ }

From the list of above classes & aforementioned explanation of @Order annotation, we can conclude that the correct order of execution of components will be : C3, C1, C2, C4, C5, D, E

Best Use of @Order in AOP using AspectJ

For example, Let’s assume we are applying two aspects on the same method. By default, Spring will keep these two Aspects in the same order in which they were discovered by the component scan. If you want them to run in a particular order, you can use @Order annotation by passing an integer to it.

Another use of @Order annotation is in Junit where we can use it to determine the order of execution of test cases.

In order to learn all annotations on Spring Boot, kindly visit Spring Boot Annotations With Examples.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
javatechonline blog

javatechonline blog

Java, Spring Boot, Microservices Tutorials