Spring的三种装配方式:
- 在xml中显示的配置
- 在java中显示的配置
- 隐式的自动装配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