彈簧教程 - 彈簧汽車線束

2018-01-09 19:06 更新

彈簧教程 - 彈簧汽車線束


春天可以自動(dòng)地蠶豆。要啟用它,請(qǐng)?jiān)?lt; bean>中定義“autowire"屬性。

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="byName" />

彈簧有五種自動(dòng)接線模式。

  • no - Default, no auto wiring
  • byName - Auto wiring by property name.
  • byType - Auto wiring by property data type.
  • constructor - byType mode in constructor argument.
  • autodetect - If a default constructor is found, use "autowired by constructor"; Otherwise, use "autowire by type".


Java Bean

客戶Java bean。

package com.hgci.cnmon;
public class Customer 
{
  private Person person;
  public Customer(Person person) {
    this.person = person;
  }
  public void setPerson(Person person) {
    this.person = person;
  }
}

Person Java bean

package com.hgci.cnmon;
public class Person 
{
}


自動(dòng)接線“否"

這是默認(rèn)模式,我們需要通過(guò)“ref"屬性連接Java bean。

<bean id="customer" class="com.hgci.cnmon.Customer">
         <property name="person" ref="person" />
</bean>
<bean id="person" class="com.hgci.cnmon.Person" />

自動(dòng)接線“byName"

以下代碼將autowire byName添加到bean聲明中。

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="byName" />

因?yàn)椤皃erson"bean的名稱與“customer"bean的名稱相同“person"屬性,Spring將通過(guò)setPerson(Person person)方法自動(dòng)連接。

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="byName" />
<bean id="person" class="com.hgci.cnmon.Person" />

自動(dòng)布線“byType"

以下xml配置將自動(dòng)連線類型聲明為byType。

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="byType" />

因?yàn)椤皃erson"bean的數(shù)據(jù)類型與數(shù)據(jù)類型相同“客戶"bean的屬性person對(duì)象,Spring將通過(guò)方法setPerson(Person person)自動(dòng)連接它。

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="byType" />
<bean id="person" class="com.hgci.cnmon.Person" />

自動(dòng)布線“構(gòu)造函數(shù)"

以下代碼將bean的自動(dòng)連線類型聲明為構(gòu)造函數(shù)

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="constructor" />

“person"bean的數(shù)據(jù)類型與“customer"bean的屬性(Person對(duì)象)中的構(gòu)造函數(shù)參數(shù)數(shù)據(jù)類型相同,Spring將通過(guò)構(gòu)造方法 - “public Customer(Person person)"自動(dòng)連接它。

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="constructor" />
<bean id="person" class="com.hgci.cnmon.Person" />

自動(dòng)布線“構(gòu)造函數(shù)"...

以下代碼顯示如何使用autodetect autowire。如果找到構(gòu)造函數(shù),則使用“constructor"; 否則,使用“byType"。

<bean id="customer" class="com.hgci.cnmon.Customer" 
      autowire="autodetect" dependency-check="objects />

由于在“Customer"類中有一個(gè)構(gòu)造函數(shù),Spring將通過(guò)構(gòu)造方法 - “public Customer(Person person)"自動(dòng)連接它。

<bean id="customer" class="com.hgci.cnmon.Customer" autowire="autodetect" />
<bean id="person" class="com.hgci.cnmon.Person" />
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)