Spring 专题
专题目录
您的位置:java > Spring专题 > Spring自动装配Beans
Spring自动装配Beans
作者:--    发布时间:2019-11-20
在spring框架,可以用 auto-wiring 功能会自动装配bean。要启用它,只需要在 <bean>定义“autowire”属性。
<bean id="customer" class="com.h3.common.customer" autowire="byname" />
在spring中,支持 5 自动装配模式。
  • no – 缺省情况下,自动配置是通过“ref”属性手动设定
  • byname – 根据属性名称自动装配。如果一个bean的名称和其他bean属性的名称是一样的,将会自装配它。
  • bytype – 按数据类型自动装配。如果一个bean的数据类型是用其它bean属性的数据类型,兼容并自动装配它。
  • constructor – 在构造函数参数的bytype方式。
  • autodetect – 如果找到默认的构造函数,使用“自动装配用构造”; 否则,使用“按类型自动装配”。

示例

customer 和 person 对象自动装配示范。
package com.h3.common;

public class customer 
{
	private person person;
	
	public customer(person person) {
		this.person = person;
	}
	
	public void setperson(person person) {
		this.person = person;
	}
	//...
}
package com.h3.common;

public class person 
{
	//...
}

1. auto-wiring ‘no’

这是默认的模式,你需要通过 'ref' 属性来连接 bean。
<bean id="customer" class="com.h3.common.customer">
                  <property name="person" ref="person" />
	</bean>

	<bean id="person" class="com.h3.common.person" />

2. auto-wiring ‘byname’

按属性名称自动装配。在这种情况下,由于对“person” bean的名称是相同于“customer” bean 的属性(“person”)名称,所以,spring会自动通过setter方法将其装配 – “setperson(person person)“.

<bean id="customer" class="com.h3.common.customer" autowire="byname" />	
<bean id="person" class="com.h3.common.person" />

查看完整的示例 – spring按名称自动装配

3. auto-wiring ‘bytype’

通过按属性的数据类型自动装配bean。在这种情况下,由于“person” bean中的数据类型是与“customer” bean的属性(person对象)的数据类型一样的,所以,spring会自动通过setter方法将其自动装配。– “setperson(person person)“.

<bean id="customer" class="com.h3.common.customer" autowire="bytype" />
<bean id="person" class="com.h3.common.person" />

查看完整的示例 – spring通过类型自动装配

4. auto-wiring ‘constructor’

通过构造函数参数的数据类型按属性自动装配bean。在这种情况下,由于“person” bean的数据类型与“customer” bean的属性(person对象)的构造函数参数的数据类型是一样的,所以,spring通过构造方法自动装配 – “public customer(person person)“.

<bean id="customer" class="com.h3.common.customer" autowire="constructor" />
	
	<bean id="person" class="com.h3.common.person" />

查看完整的示例 – 

查看完整的示例 – spring按autodetect自动装配成功.

这是一件好事,这两个auto-wire’ 和 ‘dependency-check’ 相结合,以确保属性始终自动装配成功。
<bean id="customer" class="com.h3.common.customer" 
			autowire="autodetect" dependency-check="objects />
	
	<bean id="person" class="com.h3.common.person" />

结论

在我看来,spring ‘auto-wiring’ 以极大的成本做出更快开发效率 - 它增加了对整个 bean 配置文件复杂性,甚至不知道哪些bean将自动装配哪个bean。

在实践中,我更顷向手动关联创建,它始终是干净,也很好地工作,或者使用 @autowired 注解,这是更加灵活和建议。



网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册