Spring 自动装配 byType

自动装配 byType,这种模式由属性类型指定自动装配。

Spring 容器看作 beans,在 XML 配置文件中 beans 的 autowire 属性设置为 byType。然后,如果它的 type 恰好与配置文件中 beans 名称中的一个相匹配,它将尝试匹配和连接它的属性。如果找到匹配项,它将注入这些 beans,否则,它将抛出异常。

例如,在配置文件中,如果一个 bean 定义设置为自动装配 byType,并且它包含 SpellChecker 类型的 spellChecker 属性,那么 Spring 就会查找定义名为 SpellChecker 的 bean,并且用它来设置这个属性。你仍然可以使用 标签连接其余属性。

如果要使用自动装配byTyp,那么XML 配置文件将成为如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

    <!-- Definition for textEditor bean-->
    <bean id="textEditor" class="hello.TextEditor" autowire="byType">
        <property name="name" value="Generic Text Editor"/>
    </bean>

    <!-- Definition for spellChecker bean -->
    <bean id="SpellChecker" class="hello.SpellChecker">
    </bean>

</beans>

每天学习一点点,每天进步一点点。

原文地址:https://www.cnblogs.com/youcoding/p/12775343.html