通过xml文件配置 spring自动装配5中模式

spring中,支持 5 自动装配模式: 

- no – 缺省情况下,自动配置是通过“ref”属性手动设定 
- byName – 根据属性名称自动装配。如果一个bean的名称和其他bean属性的名称是一样的,将会自装配它。 
- byType – 按数据类型自动装配。如果一个bean的数据类型是用其它bean属性的数据类型,兼容并自动装配它。 
- constructor – 在构造函数参数的byType方式。 
- autodetect – 如果找到默认的构造函数,使用“自动装配用构造”; 否则,使用“按类型自动装配”。

package com.hyq.common;//Customer实体
public class Customer {
    private Person person;
    public Customer(Person person) {
        this.person = person;
    }
    public void setPerson(Person person) {
        this.person = person;
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
package com.hyq.common;//Person实体
public class Person {
    private int id;
    private String name;
    ...
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

  • 1.Auto-Wiring ‘no’: 
    • 这是默认的模式,你需要通过 ‘ref’ 属性来连接 bean。
<bean id="customer" class="com.hyq.common.Customer">
     <property name="person" ref="person"/>
</bean>
<bean id="person" class="com.hyq.common.Person"/>
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
  • 2.Auto-Wiring ‘byName’: 
    • 按属性名称自动装配。在这种情况下,由于对“person” bean的名称是相同于“customer” bean 的属性(“person”)名称,所以,Spring会自动通过setter方法将其装配 – “setPerson(Person person)“.
<bean id="customer" class="com.hyq.common.Customer" autowire="byName" />    
<bean id="person" class="com.hyq.common.Person" />
 
 
  • 1
  • 2
  • 1
  • 2
  • 3. Auto-Wiring ‘byType’: 
    • 通过按属性的数据类型自动装配Bean。在这种情况下,由于“Person” bean中的数据类型是与“customer” bean的属性(Person对象)的数据类型一样的,所以,Spring会自动通过setter方法将其自动装配。– “setPerson(Person person)“.
<bean id="customer" class="com.hyq.common.Customer" autowire="byType" />
<bean id="person" class="com.hyq.common.Person" />
 
 
  • 1
  • 2
  • 1
  • 2
  • 4. Auto-Wiring ‘constructor’: 
    • 通过构造函数参数的数据类型按属性自动装配Bean。在这种情况下,由于“person” bean的数据类型与“customer” bean的属性(Person对象)的构造函数参数的数据类型是一样的,所以,Spring通过构造方法自动装配 – “public Customer(Person person)“.
<bean id="customer" class="com.hyq.common.Customer" autowire="constructor" />
    <bean id="person" class="com.hyq.common.Person"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值