Spring 4.0的一个小特性是在自动注入的时候使用@Order。Spring 2.5中,我们将bean注入List,如下代码:
- import org.springframework.stereotype.Component;
- @Component
- public class Employee implements Person {
- }
- import org.springframework.stereotype.Component;
- @Component
- public class Customer implements Person {
- }
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- @Component
- public class Organization {
- @Autowired
- List<Person> people;
- public String toString() {
- return people.toString();
- }
- }
@Order注解在Spring2.0时已经在Spring框架里。它的主要作用是给组件排序。现在在Spring4.0里,它也能给注入到有序的colletion的bean排序。@Order接受一个排序值,值小的优先级高,也意味着在collection中排序靠前。上面的例子改写成:
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- @Component
- @Order(value=1)
- public class Employee implements Person {
- }
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- @Component
- @Order(value=2)
- public class Customer implements Person {
- }