spring4.0之七:Ordering Autowired Collections
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();
- }
- }
此例中,Organization中的people是无序的。多数情况下,在xml配置里,bean被有序添加到people list。这时Srping 4.0提供了一个解决方案:使用@Order。
@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 {
- }