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?
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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With