spring-自动装配

 Spring自动装配 ‘ByName’

当在xml文件中加上属性autowire=“byName”后,不需要在xml显式的去配置注入了,

只需要在java代码中写set方法(setSpellChecker()方法),容器会根据这个来自动的去搜寻注入。

这里的搜寻是在xml配置文件中去搜寻bean,根据id

beans.xml,其他的和上一篇博客一样。

    <bean id="textEditor" class="com.test.TextEditor" autowire="byName">
        <!-- <property name="spellChecker" ref="spellChecker" /> -->
        <property name="money" value="@qq" />
    </bean>
    <bean id="spellChecker" class="com.test.SpellChecker"></bean>

 spring自动装配‘ByType’

这里是根据Type去查找的,在set中传入的参数类型,在xml文件中去查找相对应的bean,查找到了bean的type与其一致的话就注入

但是在测试中发现,若是在xml存在多个与其类型匹配的话,就会出问题报错

beans.xml,其他的和上一篇博客一样。

    <bean id="textEditor" class="com.test.TextEditor" autowire="byType">
        <!-- <property name="spellChecker" ref="spellChecker" /> -->
        <property name="money" value="@qq" />
    </bean>
    <bean id="spellChecker" class="com.test.SpellChecker"></bean> 
Spring 由构造函数自动装配

基于构造函数的自动装配,是根据java实体类中的带参构造函数,与上面的基于“byType”基本是类似的。

beans.xml

    <bean id="textEditor" class="com.test.TextEditor" autowire="constructor">
        <property name="money" value="@qq" />
    </bean>
    <bean id="spellChecker2" class="com.test.SpellChecker2"></bean>
    <!-- <bean id="spellChecker1" class="com.test.SpellChecker1"></bean> -->

TextEditoe.java

    public TextEditor(SpellChecker spellChecker){
        this.spellChecker=spellChecker;
    }

参考:w3cSchool教程

原文地址:https://www.cnblogs.com/yanliang12138/p/9728283.html