自动装配
Spring会在上下文自动寻找并且给bean注入装配属性
ByName
<bean id="cat" class="com.lms.pojo.Cat"/>
<bean id="dog" class="com.lms.pojo.Dog"/>
<bean id="person" class="com.lms.pojo.Person" autowire="byName">
<property name="name" value="yi"/>
</bean>
自动在容器上下文查找,会依据Set方法后面名称相同id的bean进行自动装配
ByType
<bean id="cat" class="com.lms.pojo.Cat"/>
<bean id="dog1" class="com.lms.pojo.Dog"/>
<bean id="person" class="com.lms.pojo.Person" autowire="byType">
<property name="name" value="yi"/>
</bean>
自动在容器上下文差找类型相同的bean,故id与成员名称不匹配、没有id都可以执行
当有重复类型时不可运行
注解实现自动装配
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
①导入约束:context约束
②开启注解支持`context:annotation-config/
③在实体类中需要注入的成员加上@AutoWired注解(此方法无需set方法,需要在IOC容器中有匹配对象ByType+ByName)
public class Person {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
注:
@Autowired
@Qualifier("dog")
private Dog dog;
可以使用@Qualifier用名字指定使用的bean
@Resource
private Dog dog;
可以用Java的Resource注解进行自动装配
小结:
@Resource与@AutoWired对比
①都用于自动装配,可以放属性字段上
②@AutoWired默认ByType再ByName
③@Resource默认ByName再ByType,两个都找不到则报错