Bean XML 配置(3)- 依賴注入配置



Spring 系列教程


本文介紹使用xml中配置Bean之間的依賴關系。

xml配置文件中,在bean的定義中可配置該bean的依賴項,通常使用的配置方式有2種:

  • 構造函數注入
  • Setter方法注入

構造函數注入

根據XML中的配置,Spring容器首先創建所依賴Bean實例,然后傳遞給類的構造函數。

示例:

public class App {
    
    private Service mainService;
    private Service[] services;
  
    // 注入Service實例
    public App(Service main){
        this.mainService = main;
    }
 
    // 注入Service實例數組
    public App(Service[] services){
        this.services = services;
    }
}

在bean.xml中,定義App類依賴項:


<!-- App Bean定義 -->
<bean id="app" class="App">
 
 <!-- 構造函數注入單個依賴項實例 -->
 <constructor-arg ref="logger"/>
 
 <!-- 構造函數注入依賴項實例數組 -->
 <!-- <constructor-arg>
  <list>
    <ref bean="database"/>
    <ref bean="mail"/>
    <ref bean="logger"/>
  </list>
 </constructor-arg> --> 
</bean>

<!-- Service bean (依賴項)定義 -->
<bean id="database" class="Database"/>
<bean id="logger" class="Logger"/>
<bean id="mail" class="Mail"/>

DatabaseLoggerMail都繼承自基類Service

<constructor-arg>用於構造函數方式注入Bean,ref屬性指明要注入的Bean(引用方式),屬性值是所依賴bean的ID。

XML的bean定義中只能有1個<constructor-arg>,所以在上面的示例中要么注入單個服務實例,要么注入服務實例數組。

確保在XML文件中為所有依賴項配置bean,否則Spring容器無法注入這些依賴項。

Setter方法注入

根據XML中的配置,Spring容器調用類的Setter方法注入依賴項。

示例:

public class App {

    // ...
    
    public Service getMainService() {
        return mainService;
    }
    
    // 通過setter方法注入服務實例
    public void setMainService(Service mainService) {
        this.mainService = mainService;
    }
    
    public Service[] getServices() {
        return services;
    }
    
    // 通過setter方法注入服務實例數組
    public void setServices(Service[] services) {
        this.services = services;
    }
}

在bean.xml中,定義類的依賴項。Spring容器根據<property>配置,調用類的相應setter方法,設置屬性,實現依賴項的注入。

<bean id="app" class="App">
 
 <!-- Setter 方法配置 -->
 <property name="mainService" ref="logger"/>
 <property name="services">
  <list>
   <ref bean="database"/>
   <ref bean="mail"/>
   <ref bean="logger"/>
  </list>
 </property>
  
</bean>

Spring容器怎么知道調用哪個setter方法? Spring容器根據name調用setter方法:name對應“set”關鍵字后面的屬性名,name="mainService"對應於setMainService

注入值的配置

前面介紹了使用<constructor-arg><property>注入依賴的Bean實例,另外還可以使用它們來注入值。

示例:

<bean id="app" class="App">
 
 <!-- 構造函數注入值 -->
 <constructor-arg type="int" value="12345"/>
 <constructor-arg type="java.lang.String" value="myApp"/>
 
 <!-- 也可通過構造函數的參數序號注入值 -->
 <!-- <constructor-arg index="0" value="12345"/> -->
 <!-- <constructor-arg index="1" value="myApp"/> -->

 <!-- Setter方法注入值 -->
 <!-- <property name="id" value="1234"/> -->
 <!-- <property name="name" value="myApp"/> -->
  
</bean>

XML中value屬性的值會賦給類中的屬性,如果引用一個bean,則使用ref屬性。

如果需要傳遞空字符串或null作為值,可以按如下設置:

<bean id="app" class="App">
  <property name="name" value=""/>
</bean>
<bean id="app" class="App">
  <property name="name"><null/></property>
</bean>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM