自动装配式Spring满足bean依赖的一种方式!
Spring会在上下文中自动寻找,并自动给bean装配属性
在spring中有3种自动装配的方式
1.在xml中显式的配置
2.在java中显式的配置
3.隐式的自动装配bean 【重要】
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dog" class="pojo.Dog"/>
<bean id="cat" class="pojo.Cat"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanId
-->
<bean id="people" class="pojo.People" autowire="byName">
<property name="name" value="cz"/>
</bean>
</beans>
测试代码
@Test
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
People people=context.getBean("people",People.class);
people.getCat().shout();
people.getDog().shout();
}
byType
<!--
byName:会自动在容器上下文中查找,和自己对象属性类型相同的bean,而且id可以省略
-->
<bean id="people" class="pojo.People" autowire="byType">
<property name="name" value="cz"/>
</bean>
总结:
byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致