Spring 自动装配Bean属性

来源:互联网 发布:wifi速度测试软件 编辑:程序博客网 时间:2024/05/22 23:58

来自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进行自动装配。

原创粉丝点击