Spring-04 Bean的自動裝配

Spring-04 Bean的自動裝配

Bean的自動裝配

1.自動裝配說明

  • 自動裝配是使用spring滿足bean依賴的一種方法。
  • spring會在應用上下文中為某個bean尋找其依賴的bean。

Spring中bean有三種裝配機制,分別是:

  1. 在xml中顯式配置;
  2. 在java中顯式配置;
  3. 隱式的bean發現機制和自動裝配。

這裡我們主要講第三種:自動化的裝配bean。

Spring的自動裝配需要從兩個角度來實現,或者說是兩個操作:

  1. 組件掃描(component scanning):spring會自動發現應用上下文中所創建的bean;
  2. 自動裝配(autowiring):spring自動滿足bean之間的依賴,也就是我們說的IoC/DI;

組件掃描和自動裝配組合發揮巨大威力,使得顯示的配置降低到最少。

推薦不使用自動裝配xml配置 , 而使用註解 。

2.案例

2.1 創建實體類

public class Cat {
    public void shout() {
        System.out.println("miao~");
    }
}
public class Dog {
    public void shout() {
        System.out.println("wang~");
    }
}
public class User {
    private Cat cat;
    private Dog dog;
    private String str;
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    public String getStr() {
        return str;
    }
    public void setCat(Cat cat) {
        this.cat = cat;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public void setStr(String str) {
        this.str = str;
    }
}

2.2 創建配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
       xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="//www.springframework.org/schema/beans //www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dog" class="pojo.Dog"/>
    <bean id="cat" class="pojo.Cat"/>

    <bean id="user" class="pojo.User">
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
        <property name="str" value="zc"/>
    </bean>
</beans>

2.3 測試

    @Test
    public void Test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        User user = (User) context.getBean("user");
        user.getCat().shout();
        user.getDog().shout();
    }

1

3.按名稱自動裝配

由於在手動配置xml過程中,常常發生字母缺漏和大小寫等錯誤,而無法對其進行檢查,使得開發效率降低。

採用自動裝配將避免這些錯誤,並且使配置簡單化。

修改bean配置:autowire=”byName”

<bean id="user" class="pojo.User" autowire="byName">
      <property name="str" value="zc"/>
</bean>

再次測試,一切正常。

但是如果將 cat 的bean id修改為 catXXX,就會出現java.lang.NullPointerException

因為按byName規則找不對應set方法,真正的setCat就沒執行,對象就沒有初始化,所以調用時就會報空指針錯誤。

當一個bean節點帶有 autowire byName的屬性時。

  1. 將查找其類中所有的set方法名,例如setCat,獲得將set去掉並且首字母小寫的字符串,即cat。
  2. 去spring容器中尋找是否有此字符串名稱id的對象。
  3. 如果有,就取出注入;如果沒有,就報空指針異常。

4.按類型自動裝配

使用autowire byType首先需要保證:同一類型的對象,在spring容器中唯一。

修改bean配置:autowire=”byType”

<bean id="user" class="pojo.User" autowire="byType">
    <property name="str" value="zc"/>
</bean>

再次測試,一切正常。

但是如果添加一個Cat的bean:

<bean id="cat1" class="pojo.Cat"/>

會報錯:NoUniqueBeanDefinitionException,所以同一類型的對象,在spring容器中必須唯一。

綜上:

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

5.註解實現自動裝配

5.1 引入context文件頭

<?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">
  
</beans>

5.2 開啟屬性註解支持!

<context:annotation-config/>

5.3 @Autowired

5.3.1 導入依賴

<!-- //mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.3</version>
</dependency>

5.3.2 修改案例

將User類中的set方法去掉,使用@Autowired註解

public class User {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String str;
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    public String getStr() {
        return str;
    }
}

5.3.3 修改配置文件

<?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
">

    <bean id="dog" class="pojo.Dog"/>
    <bean id="cat" class="pojo.Cat"/>
    <bean id="user" class="pojo.User"/>
    
    <context:annotation-config/>

</beans>

測試,一樣成功。

@Autowired(required=false)

false:對象可以為null;

true:對象必須存對象,不能為null。

5.4 @Qualifier

  • @Autowired是根據類型自動裝配的,加上@Qualifier則可以根據byName的方式自動裝配
  • @Qualifier不能單獨使用。

5.4.1 配置文件修改

<?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
">

    <bean id="dog" class="pojo.Dog"/>
    <bean id="dog1" class="pojo.Dog"/>
    <bean id="cat" class="pojo.Cat"/>
    <bean id="cat1" class="pojo.Cat"/>
    <bean id="user" class="pojo.User"/>
    <context:annotation-config/>

</beans>

沒有加Qualifier測試,直接報錯

這時候,在屬性上添加Qualifier註解

    @Autowired
    @Qualifier(value = "cat")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog")
    private Dog dog;

    private String str;

測試,成功輸出。

5.5 @Resource

  • @Resource如有指定的name屬性,先按該屬性進行byName方式查找裝配;
  • 其次再進行默認的byName方式進行裝配;
  • 如果以上都不成功,則按byType的方式自動裝配。
  • 都不成功,則報異常。

5.5.1 第一種

實體類

public class User {
   @Resource(name = "cat")
   private Cat cat;
   @Resource
   private Dog dog;
   private String str;
}

bean.xml

<bean id="dog" class="pojo.Dog"/>
<bean id="cat" class="pojo.Cat"/>
<bean id="cat1" class="pojo.Cat"/>

<bean id="user" class="pojo.User"/>

測試通過

5.5.2 第二種

bean.xml

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat" class="com.kuang.pojo.Cat"/>

實體類只保留註解

@Resource
private Cat cat;
@Resource
private Dog dog;

測試通過

5.6 註解總結

@Autowired與@Resource異同:

1、@Autowired與@Resource都可以用來裝配bean。都可以寫在字段上,或寫在setter方法上。

2、@Autowired默認按類型裝配(屬於spring規範),默認情況下必須要求依賴對象必須存在,如果要允許null 值,可以設置它的required屬性為false,如:@Autowired(required=false) ,如果我們想使用名稱裝配可以結合@Qualifier註解進行使用

3、@Resource(屬於J2EE復返),默認按照名稱進行裝配,名稱可以通過name屬性進行指定。如果沒有指定name屬性,當註解寫在字段上時,默認取字段名進行按照名稱查找,如果註解寫在setter方法上默認取屬性名進行裝配。當找不到與名稱匹配的bean時才按照類型進行裝配。但是需要注意的是,如果name屬性一旦指定,就只會按照名稱進行裝配。

它們的作用相同都是用註解方式注入對象,但執行順序不同。@Autowired先byType,@Resource先byName。

個人博客為:
MoYu’s Github Blog
MoYu’s Gitee Blog

Tags: