自动装配
1.ByName自动装配
<!--
byname:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean id
-->
<bean id="people" class="com.xiaoguan.pojo.people" autowire="byName">
<property name="name" value="xiaoguanya"/>
</bean>
2.ByType自动装配
<bean class="com.xiaoguan.pojo.Cat"/>
<bean class="com.xiaoguan.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.xiaoguan.pojo.People" autowire="byType">
<property name="name" value="xiaoguan"/>
</bean>
小结:
- byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
3.使用注解实现自动装配
1)准备工作:利用注解的方式注入属性
①在spring配置文件中引入context文件头
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
②开启属性注解支持
<context:annotation-config/>
@Autowired
- @Autowired是按类型自动装配的,不支持id匹配