@Order in Spring

In this post, we are going to discuss the @Order annotation. We are covering various features of this annotation.

 

Introduction

@Order annotation defines the sort order for an annotated component. This annotation is available from Spring 2.0. This annotation has an optional value argument which represents an order value as defined in the Ordered interface.

The default value is Ordered.LOWEST_PRECEDENCE, indicating lowest priority, similarly, the value Ordered.HIGHEST_PRECEDENCE  for overriding the highest priority.

 

1. @Order annotation

Before Spring 4, @Order annotation was only used for ordering AspectJ aspects. Post Spring 4, Spring @Order annotation support ordering of auto-wired components in collections like Lists and Arrays.

 

2. How to Use @Order

To understand this annotation, let’s build the following example.

  • We want to recommend a car to the potential customers.
  • Toyota is the first recommendation.
  • Honda is the second recommendation.
  • UsedCard will be the lowest priority recommendation.

 

2.1 Car Interface

Let’s create our Car interface.

public interface Car {

 /**
  * This method is responsible for recommending car to customer based on our algorithm
  * @return Recommended car
  */
 String getCarRecommendation();
}

 

2.2 Car Creations

let’s create three different instances of the car and set the order based on our algorithm.

@Component
@Order(1)
public class Toyota implements Car {

 @Override
 public String getCarRecommendation() {
  return "Toyota";
 }
}

@Component
@Order(2)
public class Honda implements Car {

 @Override
 public String getCarRecommendation() {
  return "Honda";
 }
}

@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class UsedCar implements Car {

 @Override
 public String getCarRecommendation() {
  return "Certified Car";
 }
}

In the “UsedCar” section, we added the lowest priority.

 

3 Test Application

Let’s test our application to see how this annotation work.

@RunWith(SpringRunner.class)
@SpringBootTest
public class OrderAnnotationTest {

 @Autowired
 private List < Car > cars;

 @Test
 public void test_spring_order_annotation() {

  assertThat(cars.get(0).getCarRecommendation(), is(equalTo("Toyota")));
  assertThat(cars.get(1).getCarRecommendation(), is(equalTo("Honda")));
  assertThat(cars.get(2).getCarRecommendation(), is(equalTo("Certified Car")));
 }
}

 

3 Summary

In this article, we discuss the Spring @Order annotation. We learned when to use this annotation and how to customize its behavior.

Source code for this post can be found over Github.

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of