6、bean的自动装配
-
自动装配是spring满足bean依赖的一种方式
-
spring会在上下文中自动寻找,并自动给bean装配属性
在spring中有三种装配方式:
1.在xml中显示装配
2.在java中显示装配(还未学)
3.隐式的自动装配bean【重要】
6.1 测试
-
环境搭建
- 一个人有两只宠物!
6.2 ByName自动装配
<bean id="cat" class="com.hardy.pojo.Cat"/>
<bean id="dog222" class="com.hardy.pojo.Dog"/>
<!-- byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean id
byType:会自动在容器上下文中查找,和自己对象类型相同的 bean id
必须保证这个类型全局唯一 不然xml中直接报错
-->
<bean id="people" class="com.hardy.pojo.People" autowire="byName">
<property name="name" value="张三" />
</bean>
6.3 ByType自动装配
<bean id="cat" class="com.hardy.pojo.Cat"/>
<bean id="dog222" class="com.hardy.pojo.Dog"/>
<!-- byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean id
byType:会自动在容器上下文中查找,和自己对象类型相同的 bean id
必须保证这个类型全局唯一 不然xml中直接报错
-->
<bean id="people" class="com.hardy.pojo.People" autowire="byType">
<property name="name" value="张三" />
</bean>
小结:
-
byName:需要保证所以的bean的ID唯一,并且这个bean需要和自动注入的属性的set方法的值一致
-
byType:需要保证所以的bean的class唯一,并且这个bean需要和自动注入的类型一致
6.4、使用注解实现自动装配
使用注解自动装配
jdk1.5支持的注解,spring2.5支持的注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
-
使用注解须知“
-
1.导入约束:context约束
-
2.配置注解的支持:<context:annotation-config />
-
<?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>
QAutowired
在属性上使用,也可以在set方法上使用
可以没有set方法,但在自动装配的属性在IOC容器(beans.xml)中,且符合byname
public class People {
//说明这个对象可以为null,否则不允许为空,即使为null也不会报错
@Autowired(required = false)
private Dog dog;
@Autowired(required = false)
private Cat cat;
如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候,不符合byname,也可以使用@Qualifier来指定
public class People {
//说明这个对象可以为null,否则不允许为空,即使为null也不会报错
@Autowired(required = false)
@Qualifier(value = "dog84")
private Dog dog;
@Autowired
@Qualifier(value = "cat84")
private Cat cat;
}
@Resource 注解
public class People {
@Resource(name = "cat84")
private Cat cat;
@Resource
private Dog dog;
}
小结:
-
@Resource和@Autowired的区别:
-
都是用来自动装配的,都可以放在属性字段上
-
@Resource和@Autowired都默认通过byType的方式实现,如果情况复杂,一个类型都很多个bean,则使用byName方式实现
-