Bean的自动装配
- 自动装配,spring满足bean依赖的一种方式
- autowire
- spring会在上下文中自动寻找,并自动给bean装配属性
在spring中有三种装配方式
- 在xml中显示的配置
- 在java中显示的配置
- 隐式 的自动装配bean【重要】
XML Configuration Demo
-
原先使用的方法
-
<bean id="cat" class="com.haoyun.POJO.Cat"/> <bean id="dog" class="com.haoyun.POJO.Dog"/> <bean id="People" class="com.haoyun.POJO.People"> <property name="name" value="haoyun"/> <property name="cat" ref="cat"/> <property name="dog" ref="dog"/> </bean>
-
@Test public void CatDogTest(){ ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); People people = (People) classPathXmlApplicationContext.getBean("People"); people.getCat().shout(); people.getDog().shout(); classPathXmlApplicationContext.registerShutdownHook(); }
-
其他类需要使用ref
-
现在加入两个自动装配的autowire选项
-
byName
-
<bean id="cat" class="com.haoyun.POJO.Cat"/> <bean id="dog" class="com.haoyun.POJO.Dog"/> <!-- <bean id="dog1" class="com.haoyun.POJO.Dog"/>如果这里的id更改,就找不到了--> <!--byName:会自动再容器上下文查找,和自己对象set方法后面值对应的bean id--> <bean id="People" class="com.haoyun.POJO.People" autowire="byName"> <property name="name" value="haoyun"/> </bean>
-
-
byType
-
<bean id="cat" class="com.haoyun.POJO.Cat"/> <bean class="com.haoyun.POJO.Dog"/> <!-- <bean id="dog" class="com.haoyun.POJO.Dog"/> 但是不能配重,全局只能有一个--> <!--连bean-id都可以不用--> <!--byType:自动在容器的上下文查找,和自己对象相同类型bean--> <bean id="People" class="com.haoyun.POJO.People" autowire="byType"> <property name="name" value="haoyun"/> </bean>