Spring

Spring @Order Annotation

Introduction:

The Spring @Order annotation was first introduced in Spring 2.0. It was then used only to define the order among the AspectJ advices. Later in Spring 4.0, the implementation of this annotation was further improved a bit. Since then, it also supports ordering of Spring components or beans in a collection like a Java array or a List.

This annotation internally makes use of the OrderComparator class for Spring XML-based applications and AnnotationAwareOrderComparator for the annotation-based Spring applications.

In this tutorial, we’ll explore how to use this annotation.

Spring @Order Annotation:

The Spring @Order annotation accepts exactly one optional argument, value, which determines the order of the component:

Lower the value of this argument, higher is its precedence. In other words, the ones with the lower value will come first in the Java List or an array.

The default value of this argument is Ordered.LOWEST_PRECEDENCE. This means that the marked component is having the least precedence among all ordered beans. Similarly, we can use Ordered.HIGHEST_PRECEDENCE to mark a Spring bean having the highest precedence.

Why use?

Some of the common use-cases of @Order annotation include:

  • Ordering the advices in AspectJ; the real intention with which it was first introduced
  • When we want to define an order for loading our CommandLineRunner or ApplicationRunner classes
  • For injecting a list of beans in an ordered fashion in a Java array or a List
  • Defining the order of filter execution say in case of Spring Security

Example Setup:

Let’s say we have a Vehicle interface:

And we define a few implementation classes:

Here, we have ordered all three of these Spring components. The Bike bean has the highest precedence followed by Car and finally the Truck.

Testing Our Implementation:

Let’s quickly write a Junit to see how things work:

Clearly, Spring has autowired our beans in our vehicles Java List on the basis of their precedence.

Conclusion

In this mini-tutorial, we explored the usage of Spring @Order annotation.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *