7、bean的自動裝配
- 自動裝配是Spring滿足bean依賴的一種方式!
- Spring會在上下文中自動尋找,並自動給bean裝配屬性!
在Spring中有三種裝配的方式
- 在xml中顯示的配置
- 在java中顯示配置
- 隱式的自動裝配bean【重要】
7.1、自動裝配
- 環境搭建
- 一個人有兩個寵物!
7.2、ByName自動裝配
<!--
byName:會自動在容器上下文中查找,和自己對象set方法后面的值對應的beanid!
-->
<bean id="people" class="com.rui.pojo.People" autowire="byName">
<property name="name" value="尹銳"/>
</bean>
7.3、ByType自動裝配
<bean id="cat" class="com.rui.pojo.Cat"/>
<bean id="dog" class="com.rui.pojo.Dog"/>
<!--
byName:會自動在容器上下文中查找,和自己對象set方法后面的值對應的beanid!
byType:會自動在容器上下文中查找,和自己對象屬性類型相同的bean!
-->
<bean id="people" class="com.rui.pojo.People" autowire="byType">
<property name="name" value="尹銳"/>
</bean>
小結:
- byname的時候,需要保證所有bean的id唯一,並且這個bean需要和注入的屬性的set方法的值一致
- bytype的時候,需要保證所有bean的class唯一,並且這個bean需要和注入的屬性的類型一致
7.4、使用注解實現自動裝配
jdk1.5支持的注解,Spring2.5就支持注解了!
要使用注解須知:
-
導入約束 context約束
-
配置注解的支持: 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>
@Autowired
直接在屬性上用即可!也可以在set方式上使用!
使用Autowired我們可以不用使用Set方法了,前提是你這個自動裝配的屬性在IOC(Spring)容器中存在且符合名字(ByName)
科普:
@Nullable 字段標記了這個注解,說明這個字段可以為null
public @interface Autowired {
boolean required() default true;
}
測試代碼:
public class People {
//如果顯式的定義了AutoWired的required屬性為false,說明這個對象可以為null,否則不允許為空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
如果@Autowired自動裝配的環境比較復雜,自動裝配無法通過一個注解【@Autowired】完成的時候、我們可以使用@Qualifier(value = "xxx")去配合@Autowired的使用,指定一個唯一的bean對象注入
@Autowired注解
public class people{
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog")
private Dog dog;
private String name;
}
@Resource注解
public class people{
@Resource(name="cat")
private Cat cat;
@Resource
private Dog dog;
}
小結
@Resource和@Autowired的區別:
- 都是用來自動裝配的,都可以放在屬性字段上
- @Autowired通過byType的方式實現,而且必須要求這個對象存在!【常用】
- @Resource默認通過byname的方式實現,如果找不到名字,則通過byType實現!如果兩個都找不到的情況下,就報錯!
- 執行順序不同:@Autowired通過byType的方式實現 @Resource默認通過byname的方式實現