Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of @Order annotation in Spring?

I have come across a glance of code which uses @Order annotation. I want to know what is the use of this annotation with respect to Spring Security or Spring MVC.

Here is an example:

@Order(1) public class StatelessAuthenticationSecurityConfig extends WebSecurityConfigurerAdapter {      @Autowired     private UserDetailsService userDetailsService;      @Autowired     private TokenAuthenticationService tokenAuthenticationService;  } 

What happen to the order of above mentioned class if we do not use this annotation?

like image 887
Qasim Avatar asked May 19 '15 14:05

Qasim


People also ask

What is Spring boot order?

Annotation Type Order@Order defines the sort order for an annotated component. The value() is optional and represents an order value as defined in the Ordered interface. Lower values have higher priority. The default value is Ordered.

What is @DependsOn in Spring?

The @DependsOn annotation in spring forces the IoC container to initialize one or more beans. This annotation is directly used on any class or indirectly annotated with @Component or on methods annotated with @Bean .

What is the use of @springboot annotation?

Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.

What is the difference between @qualifier and @primary?

We use @Qualifier in Spring to autowire a specific bean among same type of beans, where as @Primary is used to give high preference to the specific bean among multiple beans of same type to inject to a bean.


1 Answers

It is used for Advice execution precedence.

The highest precedence advice runs first. The lower the number, the higher the precedence. For example, given two pieces of 'before' advice, the one with highest precedence will run first.

Another way of using it is for ordering Autowired collections

@Component @Order(2) class Toyota extends Car {     public String getName() {         return "Toyota";     } }  @Component @Order(1) class Mazda extends Car {     public String getName() {         return "Mazda";     } }  @Component public class Cars {     @Autowired     List<Car> cars;      public void printNames(String [] args) {          for(Car car : cars) {             System.out.println(car.getName())         }     } } 

You can find executable code here: https://github.com/patrikbego/spring-order-demo.git

Hope this clarifies it a little bit further.

Output:-

Mazda Toyota

like image 133
Patrik Bego Avatar answered Sep 20 '22 21:09

Patrik Bego