Spring 自动装配Bean属性

来自spring in action spring实战

可以通过四种类型装配bean的依赖关系,byName,byType,constructor,autodetect

1. byName

把与Bean的属性、具有相同名字的其他bean自动装配到Bean的对应属性中,如果没有和属性名字匹配的Bean,则该属性不进行装配。

<bean id="kenny" class="bean.insertproperty.Instrumentalist" >
        <!-- 会根据数据类型自动判断 所有值都要加双引号 -->
        <property name="song" value="国歌" />
        <property name="age" value="22" />
        <property name="instrument" ref="saxophone"></property>
</bean>
<bean id="saxophone" class="bean.insertproperty.Saxophone" />

比如对属性instrument进行byName装配,在bean标签中插入 autowire=“byName”,同时将id为Saxophone标签该为需要装配的属性名instrument

<bean id="kenny" class="bean.insertproperty.Instrumentalist" 
    autowire="byName">
        <!-- 会根据数据类型自动判断 所有值都要加双引号 -->
        <property name="song" value="国歌" />
        <property name="age" value="22" />
        <property name="instrument" ref="saxophone"></property>
</bean>
<bean id="instrument" class="bean.insertproperty.Saxophone" />
2. byType

把与Bean的属性具有相同类型的其他bean自动装配到Bean的对应属性中。如果没有跟属性类型想匹配的Bean,则该属性不装配。
修改标签autowire=”byType”
会出现的问题:
当有多个bean为同一类型时,会出现如下错误:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [bean.insertproperty.Instrument] is defined: expected single matching bean but found 2: saxophone,instrument
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1126)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1292)
… 13 more
错误信息显示没有声明唯一的bean,无法由类型确定bean
因为我设置了两个bean

    <bean id="saxophone" class="bean.insertproperty.Saxophone" />
    <bean id="instrument" class="bean.insertproperty.Saxophone" />
3. constructor

把与Bean的构造器入参具有相同类型的其他Bean自动装配到构造器里。

<bean id="poeticjuggler" class="bean.PoeticJuggler" autowire="constructor">
</bean>
<bean id="sonnet29" class="bean.Sonnet29">
public class PoeticJuggler extends Juggler {
    Poem poem;

    public PoeticJuggler(Poem poem) {
        this.poem = poem;
    }

    public PoeticJuggler(Poem poem, int beanbags) {
        super(beanbags);
        this.poem = poem;
    }
    @Override
    public void perform() {

        super.perform();
        System.out.println("while reciting");
        poem.recite();
    }
}

以constructor方式装配 PoeticJuggler 类,首先Spring框架会在配置中寻找和某一构造器所有入参的bean。会扫描poem类的bean,发现sonnet29匹配,则进行构造。

4. autodetect

首先采用constructor进行自动装配。如果失败则尝试byType进行自动装配。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值