1. 程式人生 > 其它 >Spring學習筆記——第六部分 Bean的自動裝配

Spring學習筆記——第六部分 Bean的自動裝配

技術標籤:Spring學習筆記springjava

Spring學習筆記——第六部分 Bean的自動裝配


自動裝配是Spring滿足bean依賴的一種方式。
Spring會在上下文中自動尋找,並自動給bean裝配屬性。

1. byName

<bean id="cat" class="com.zhang.pojo.Cat"/>
<bean id="
dog"
class="com.zhang.pojo.Dog"/>
<!--byName:會自動在上下文中查詢和自己物件set方法後面對應值的bean id--> <bean id="people" class="com.zhang.pojo.People" autowire="byName"> <property name="name" value="張作鵬"/> </bean>

2. byType

<
bean
class="com.zhang.pojo.Cat"/>
<bean class="com.zhang.pojo.Dog"/> <!--byType:會自動在上下文中查詢和自己物件屬性型別相同的bean--> <bean id="people" class="com.zhang.pojo.People" autowire="byType"> <property name="name" value="張作鵬"
/>
</bean>

小結:

  • byName的時候,需要保證所有bean的id唯一,並且這個bean需要和自動注入的屬性的set方法的值一致。
  • byType的時候,需要保證所有bean的class唯一,並且這個bean需要和自動注入的屬性的型別一致。

3. 使用註解實現自動裝配

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

要使用註解的須知:

  • 匯入約束,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
        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>

3.1 @Autowired

@Autowired直接在屬性上使用即可
預設是byNype

set方法也可以刪除,前提是自動裝配的屬性在Spring容器中存在,並且名字於是類就變成了這樣:

public class People {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public Dog getDog() {
        return dog;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

如果@Autowired自動裝配的環境比較複雜,自動裝配無法通過一個註解完成的時候,我們可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一個唯一的bean物件注入!

3.2 @Resource

public class People {
    @Resource(name = "cat1")
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;
}
<bean id="cat1" class="com.zhang.pojo.Cat"/>
<bean id="cat2" class="com.zhang.pojo.Cat"/>
<bean id="dog" class="com.zhang.pojo.Dog"/>
<bean id="people" class="com.zhang.pojo.People"/>

在這裡插入圖片描述

3.3 @Autowired和@Resource的區別

  • 都是用來自動裝配的,都可以放在屬性欄位上。
  • @Autowired通過byType實現,而且必須要求這個物件存在。
  • @Resource通過byName實現,如果找不到名字,則通過byType實現。