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.
The Spring @Order annotation accepts exactly one optional argument, value, which determines the order of the component:
@Retention(value=RUNTIME) @Target(value={TYPE,METHOD,FIELD}) @Documented public @interface Order
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:
Let’s say we have a Vehicle interface:
public interface Vehicle { public String getDetails(); }
@Order(1) @Component public class Bike implements Vehicle { public String getDetails() { return "Bike: 2 Wheeler"; } } @Order(2) @Component public class Car implements Vehicle { public String getDetails() { return "Car: 4 Wheeler"; } } @Order(3) @Component public class Truck implements Vehicle { public String getDetails() { return "Truck: 6 Wheeler"; } }
Let’s quickly write a Junit to see how things work:
@RunWith(SpringRunner.class) @SpringBootTest public class SampleAppTest { @Autowired private List<Vehicle> vehicles; @Test public void testSpringOrderAnnotation() { assertThat(vehicles.get(0).getDetails(), isEqual("Bike: 2 Wheeler")); assertThat(vehicles.get(1).getDetails(), isEqual("Car: 4 Wheeler")); assertThat(vehicles.get(2).getDetails(), isEqual("Truck: 6 Wheeler")); } }
In this mini-tutorial, we explored the usage of Spring @Order annotation.
very good explanation for using Order annotation