Spring自動裝配(含註解裝配)

Spring自動裝配

  • 自動裝配是使用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配置 , 而使用註解 .

測試環境搭建

1、新建一個項目

2、新建兩個實體類,Cat Dog 都有一個叫的方法

public class Cat {
   public void shout() {
       System.out.println("miao~");
  }
}
public class Dog {
   public void shout() {
       System.out.println("wang~");
  }
}

3、新建一個用戶類 User

public class User {
   private Cat cat;
   private Dog dog;
   private String str;
}

4、編寫Spring配置文件

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

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

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

5、測試

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

結果正常輸出,環境OK

byName

autowire byName (按名稱自動裝配)

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

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

測試:

1、修改bean配置,增加一個屬性 autowire=“byName”

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

2、再次測試,結果依舊成功輸出!

3、我們將 cat 的bean id修改爲 catXXX

4、再次測試, 執行時報空指針java.lang.NullPointerException。因爲按byName規則找不對應set方法,真正的setCat就沒執行,對象就沒有初始化,所以調用時就會報空指針錯誤。

小結:

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

  1. 將查找其類中所有的set方法名,例如setCat,獲得將set去掉並且首字母小寫的字符串,即cat。

  2. 去spring容器中尋找是否有此字符串名稱id的對象。

  3. 如果有,就取出注入;如果沒有,就報空指針異常。

byType

autowire byType (按類型自動裝配)

使用autowire byType首先需要保證:同一類型的對象,在spring容器中唯一。如果不唯一,會報不唯一的異常。

NoUniqueBeanDefinitionException

測試:

1、將user的bean配置修改一下 : autowire=“byType”

2、測試,正常輸出

3、在註冊一個cat 的bean對象!

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

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

4、測試,報錯:NoUniqueBeanDefinitionException

5、刪掉cat2,將cat的bean名稱改掉!測試!因爲是按類型裝配,所以並不會報異常,也不影響最後的結果。甚至將id屬性去掉,也不影響結果。

這就是按照類型自動裝配!

註解自動裝配

在beans.xml中要加上一些支持

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:annotation-config/>
    
    
    
    <!--bean就是java對象 , 由Spring創建和管理-->
    <bean id="cat" class="com.kuang.pojo.Cat"/>
    <bean id="dog" class="com.kuang.pojo.Dog"/>
    <bean id="user" class="com.kuang.pojo.User"/>
</beans>

@Autowired

  • @Autowired是按類型自動轉配的,不支持id匹配。
  • 此方法使用的方式是byType,這個會自動的找cat這個id,找不到,就會報錯,不論beans.xml中有多少個相同的類
  • 需要導入 spring-aop的包!(beans.xml中文件的一個支持,也要進行一定的支持)

測試:

1、將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;
  }
}

2、此時配置文件內容

<context:annotation-config/>

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

3、測試,成功輸出結果!

@Autowired(required=false) 說明:false,對象可以爲null;true,對象必須存對象,不能爲null。

//如果允許對象爲null,設置required = false,默認爲true
@Autowired(required = false)
private Cat cat;

@Qualifier

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

測試實驗步驟:

1、配置文件修改內容,保證類型存在對象。且名字不爲類的默認名字!

<bean id="dog1" class="com.kuang.pojo.Dog"/>
<bean id="dog2" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>

2、沒有加Qualifier測試,直接報錯

3、在屬性上添加Qualifier註解

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

測試,成功輸出!

@Resource

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

實體類:

public class User {
   //如果允許對象爲null,設置required = false,默認爲true
   @Resource(name = "cat2")
   private Cat cat;
   @Resource
   private Dog dog;
   private String str;
}

beans.xml

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

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

測試:結果OK

配置文件2:beans.xml , 刪掉cat2

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

實體類上只保留註解

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

結果:OK

結論:先進行byName查找,失敗;再進行byType查找,成功。

小結

@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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章