【译文】【学习】Spring 自动装配

【目标读者】

  本教程是专为java编程人员设计的,用来帮助他们理解Spring 3框架以及基于它的应用。

【前置条件】

  在阅读教程之前你应该有一个比较好对java语言知识的理解

【系列教程】

  Introduction to spring framework

     Spring interview questions

  Dependency injection(ioc) in spring

  Spring hello world example in eclipse

  Spring java based configuaration

  Dependency injection via setter method in spring

  Dependency injection via constructor in spring

  Spring Bean scopes with examples

  Initializing collections in spring

  Beans Autowiring in spring

  Inheritance in Spring

  Spring ApplicationContext

  Spring lifetime callbacks

  BeanPostProcessors in Spring

  Annotation based Configuration in spring

  Spring AOP tutorial

 

【Spring 自动装配】

  前面已经说明了如何用<bean>元素并且在XML中使用<constructor-arg> 和 <property> 元素来注入bean。

  在Spring 框架中,我们可以选择使用自动状态特性来装配bean。在bean标签中使用 autowire 属性来启动这一特性。Spring容器可以在互相协作的bean之间自动装配,而不需要使用<property> 和<constructor-arg>元素,这可以帮助我们减少XML配置数量。如下所示:

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" autowire="byName">

【自动装配的模式】

  no - 不进行自动装配,默认的。他仅能通过ref手动指定。

  byName - 通过属性名自动装配。Spring容器查找autowire属性为byName的bean, Spring容器尝试装配这些bean, 如果这些bean的属性的名字和配XML配置文件中bean的name(id)一致。

  byType - 通过属性类型自动装配。Spring容器查找autowire属性为byType的bean, Spring容器尝试装配这些bean,如果这些bean的属性精确匹配配置文件中一个bean的class类型,则通过,如果有多个,则抛出异常。

  constructor - 与byType类似,不过不是匹配属性,而是匹配构造函数的参数类型。

  autodetect - 首先尝试constructor,如果部工作启用byType。

 

【自动装配的限制】

  覆盖的可能性: 你仍然可以通过使用<property>和<constructor-args>标签来定义属性注入,这回覆盖自动装配。就是说使用标签来定义的优先。

  原始数据类型: 对于基本数据类型你仍然不得不使用<property>和<constructor-args>,基本数据不能自动装配。

  迷惑性:如果在程序中有大量的依赖,很难找到使用自动装配的bean。

 

posted @ 2016-12-28 12:50  彭玉松  阅读(121)  评论(0)    收藏  举报