跳转至

Spring Beans 自动装配byName

1. 介绍

  你已经学会如何使用元素来声明 bean 和通过使用 XML 配置文件中的元素来注入 。

  Spring 容器可以在不使用元素的情况下自动装配相互协作的bean之间的关系,这有助于减少编写一个大的基于 Spring 的应用程序的 XML 配置的数量。

1.1 自动装配模式

下列自动装配模式,它们可用于指示 Spring 容器为来使用自动装配进行依赖注入。你可以使用元素的 autowire 属性为一个 bean 定义指定自动装配模式。

模式 描述
no/default 这是默认的设置,它意味着没有自动装配,你应该使用显式的bean引用来连线。你不用为了连线做特殊的事。在依赖注入章节你已经看到这个了。
byName 由属性名自动装配。Spring 容器看到在 XML 配置文件中 bean 的自动装配的属性设置为 byName。然后尝试匹配,并且将它的属性与在配置文件中被定义为相同名称的 beans 的属性进行连接,找不到就是显示null。根据set方法后面的名称首字母小写决定的,不是参数列表的名称
byType 由属性数据类型自动装配。Spring 容器看到在 XML 配置文件中 bean 的自动装配的属性设置为 byType。然后如果它的**类型**匹配配置文件中的一个确切的 bean 名称,它将尝试匹配和连接属性的类型。如果存在不止一个这样的 bean,则一个致命的异常将会被抛出。 如果有多个类型就会报错,不知道选择哪个。找不到即是null
constructor 类似于 byType,但该类型适用于构造函数参数类型。如果在容器中没有一个构造函数参数类型的 bean,则一个致命错误将会发生。首先按照类型进行判断,若有多个相同类型的bean,再跟进id进行判断,id一样,就装配为null,
autodetect Spring首先尝试通过 constructor 使用自动装配来连接,如果它不执行,Spring 尝试通过 byType 来自动装配。

可以使用 byType 或者 constructor 自动装配模式来连接数组和其他类型的集合。

一般使用byName

1.2 自动装配的局限性

  当自动装配始终在同一个项目中使用时,它的效果最好。如果通常不使用自动装配,它可能会使开发人员混淆的使用它来连接只有一个或两个 bean 定义。不过,自动装配可以显著减少需要指定的属性或构造器参数,但你应该在使用它们之前考虑到自动装配的局限性和缺点。

限制 描述
重写的可能性 你可以使用总是重写自动装配的 设置来指定依赖关系。
原始数据类型 你不能自动装配所谓的简单类型包括基本类型,字符串和类。
混乱的本质 自动装配不如显式装配精确,所以如果可能的话尽可能使用显式装配。

2. ByName

ioc10.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--spring 自动装配-->
<bean id="address" class="com.cmz.bean.Address">
    <property name="province" value="江苏省"></property>
    <property name="city" value="宿迁市"></property>
    <property name="town" value="来龙镇"></property>
</bean>

<!--在spring中,可以使用自动装配的功能,spring会把某些bean注入到另一个bean中-->
<bean id="nperson" class="com.cmz.bean.Nperson" autowire="byName">
    <property name="id" value="1"></property>
    <property name="name" value="summer"></property>
</bean>
</beans>

MyTest10_byName.class

import com.cmz.bean.Nperson;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author summer
 * @create 2020-02-22 23:45
 */
public class MyTest10_byName {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc10.xml");
        Nperson nperson = context.getBean("nperson", Nperson.class);
        System.out.println(nperson);
    }
}

运行

Person{id=1, name='summer', age=null, gender='null', date=null, hobbies=null, address=Address{province='江苏省', city='宿迁市', town='来龙镇'}, lists=null, sets=null, maps=null, properties=null}

虽然我没有在nperson的bean中写address的property,但是spring会根据byName自动去找当前xml中符合address的。