Spring4.0系列7-Ordering Autowired Collections

简介:

spring 4.0的一个小特性是在自动注入的时候使用@Order。Spring 2.5中,我们将bean注入List,如下代码:

Java代码   收藏代码
  1. import org.springframework.stereotype.Component;  
  2. @Component  
  3. public class Employee implements Person {  
  4. }  

 

Java代码   收藏代码
  1. import org.springframework.stereotype.Component;   
  2. @Component   
  3. public class Customer implements Person {   
  4. }  

 

Java代码   收藏代码
  1. import org.springframework.beans.factory.annotation.Autowired;  
  2. import org.springframework.stereotype.Component;  
  3. @Component  
  4. public class Organization {  
  5.     @Autowired  
  6.     List<Person> people;  
  7.    
  8.     public String toString() {  
  9.         return people.toString();  
  10.     }  
  11. }  

 

此例中,Organization中的people是无序的。多数情况下,在xml配置里,bean被有序添加到people list。这时Srping 4.0提供了一个解决方案:使用@Order。
@Order注解在Spring2.0时已经在Spring框架里。它的主要作用是给组件排序。现在在Spring4.0里,它也能给注入到有序的colletion的bean排序。@Order接受一个排序值,值小的优先级高,也意味着在collection中排序靠前。上面的例子改写成:
Java代码   收藏代码
  1. import org.springframework.core.annotation.Order;  
  2. import org.springframework.stereotype.Component;  
  3. @Component  
  4. @Order(value=1)  
  5. public class Employee implements Person {  
  6. }  
 
Java代码   收藏代码
  1. import org.springframework.core.annotation.Order;  
  2. import org.springframework.stereotype.Component;  
  3. @Component  
  4. @Order(value=2)  
  5. public class Customer implements Person {  
  6. }  
目录
相关文章
|
Java 开发者 Spring
Spring Framework 中的 @Autowired 注解:概念与使用方法
【4月更文挑战第20天】在Spring Framework中,@Autowired 注解是实现依赖注入(Dependency Injection, DI)的一种非常强大的工具。通过使用 @Autowired,开发者可以减少代码中的引用绑定,提高模块间的解耦能力
1278 6
|
Java Spring 容器
Spring中@Autowired和@Resource注解异同点
Spring中@Autowired和@Resource注解异同点
253 0
|
开发框架 Java 测试技术
Spring Boot 项目中使用 `@Autowired` 注解,合理吗?
Spring Boot 项目中使用 `@Autowired` 注解,合理吗?
391 1
Spring Boot 项目中使用 `@Autowired` 注解,合理吗?
|
安全 Java 开发者
Spring依赖注入大揭秘:@Autowired、@Qualifier和@Resource的区别与应用
Spring依赖注入大揭秘:@Autowired、@Qualifier和@Resource的区别与应用
601 0
|
IDE Java 测试技术
为什么Spring和IDEA不推荐使用@Autowired注解,有哪些替代方案?
为什么Spring和IDEA不推荐使用@Autowired注解,有哪些替代方案?
654 1
为什么Spring和IDEA不推荐使用@Autowired注解,有哪些替代方案?
|
Java Spring
spring注解@Autowired、@Resource说明
spring注解@Autowired、@Resource说明
142 0
|
Java 编译器 Spring
Spring中@Autowired和@Resource的区别
Spring中@Autowired和@Resource的区别
284 0
|
Java Spring
Idea spring boot cannot autowired 解决方法
Idea spring boot cannot autowired 解决方法
247 0
|
Java Spring 容器
Spring中@Autowired与@Resource自动注入实现原理
Spring中@Autowired与@Resource自动注入实现原理
285 0
|
缓存 Java 容器
九.Spring源码剖析-Autowired自动注入原理
这篇文章接上一篇文章属性注入讲一讲 @Autowired 注解的实现源码,这个也是面试被问的比较多的。

热门文章

最新文章

下一篇
开通oss服务