且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring学习笔记:05 自动装配Bean

更新时间:2021-12-19 03:20:22

Spring的三种装配方式:

  1. 在xml中显示的配置
  2. 在java中显示的配置
  3. 隐式的自动装配bean 【重要】

测试环境搭建:一个people类中有私有的狗和猫对象 狗和猫对象各自有自己的叫声方法

先使用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">
    <bean id="dog" class="com.spring.myclass.Dog"/>
    <bean id="cat" class="com.spring.myclass.Cat"/>
    <bean id="people" class="com.spring.myclass.People">
        <property name="name" value="geshuaipi"/>
        <property name="cat"  ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>
</beans>

此时写一个test方法运行输出结果为

People{cat=com.spring.myclass.Cat@61862a7f, dog=com.spring.myclass.Dog@441772e, name='geshuaipi'}

byName

使用byname自动装配来试试:

<?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">
    <bean id="dog" class="com.spring.myclass.Dog"/>
    <bean id="cat" class="com.spring.myclass.Cat"/>
    <bean id="people" class="com.spring.myclass.People" autowire="byName">
        <property name="name" value="geshuaipi"/>
    </bean>
</beans>

发现仍然可以正常运行

我们把dog的名字换掉试试

<?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">
    <bean id="dog22" class="com.spring.myclass.Dog"/>
    <bean id="cat" class="com.spring.myclass.Cat"/>
    <bean id="people" class="com.spring.myclass.People" autowire="byName">
        <property name="name" value="geshuaipi"/>
    </bean>
</beans>

此时便会报错,因为byName找不到dog

byName总结:byName会自动在容器的上下文中查找和自己对象set方法后面的值对应的beanid