Bean的自動裝配

自動裝配是spring滿足bean依賴一種方式

spring會在上下文中自動尋找,並自動給bean裝配屬性

 

在spring中有三種裝配的方式

  1,在xml中顯示的配置

  2,在Java中顯示配置

  3,隱式的自動裝配bean【重要】

 

byName自動裝配

<!--
byName:會自動在容器上下文中查找,和自己對象set方法後面的值對應的beanid!
-->
<bean id="people" class="com.tan.pojo.People" autowire="byName">
<property name="name" value="楓葉"/>
</bean>

 

byType自動裝配

<!--
byName:會自動在容器上下文中查找,和自己對象set方法後面的值對應的beanid!
byType:會自動在容器上下文中查找,和自己對象屬性類型相同的bean!
-->
<bean id="people" class="com.tan.pojo.People" autowire="byType">
<property name="name" value="楓葉"/>
</bean>

 

 

小結:

  byNmame的時候,需要保證所有bean的id唯一,並且這個需要和自動注入的屬性的set方法的值一致

  byType的時候,需要保證所有bean的class唯一,並且這個需要和自動注入的屬性的類型一致

 

 

使用註解實現自動裝配

   基於注釋的配置的引入提出了一個問題,即這種方法是否比 XML「更好」。簡短的回答是「視情況而定」。長答案是,每種方法都有其優缺點,通常,由開發人員決定哪種策略更適合它們。

 

要使用註解須知:

  1,導入context約束

  2,配置註解的支持<context:annotation-config/>

 

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=“//www.springframework.org/schema/beans”

  xmlns:xsi=“//www.w3.org/2001/XMLSchema-instance”

  xmlns:context=“//www.springframework.org/schema/context”

  xsi:schemaLocation=“//www.springframework.org/schema/beans

    //www.springframework.org/schema/beans/spring-beans.xsd

    //www.springframework.org/schema/context

    //www.springframework.org/schema/context/spring-context.xsd”>

 

  <context:annotation-config/>

 

 

</beans>

 

 

  @Autowired

  直接在屬性上使用即可!也可以在set方式上使用!

  使用Autowired我們可以不用編寫set方法了,前提是你這個自動裝配的屬性IOC(Spring)容器中存在,且符合名字byName

  科普:

  @Nullable 字段標記了這個註解,

  

public @interface Autowired {

/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.
*/
boolean required() default true;

}

  

測試代碼:

public class People {
//如果顯示的定義了Autowired的required屬性為false,說明這個對象可以為null,否則不能為空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;

 

小結:

@Resource和@Autowired的區別:

  都是用來自動裝配的,都可以放在屬性字段上

  @Autowired通過byType的方式實現,而且必須要求這個對象存在【常用】

  @Resource默認通過byName方式實現,如果找不到名字,則通過byType實現!都找不到就報錯【常用】

  執行順序不同:

    @Autowired通過byType的方式實現,@Resource默認通過byName方式實現

 

Tags: