In this post, we will 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
, showing the 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 for 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 “Used Car” 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")));
}
}
Conclusion
In this article, we discuss the Spring @Order annotation. We learned when to use this annotation and how to customize its behavior.
Pingback: How to Add a Filter in Spring Boot - Daily Code Buffer