春天可以自動(dòng)地蠶豆。要啟用它,請(qǐng)?jiān)?lt; bean>中定義“autowire"屬性。
<bean id="customer" class="com.hgci.cnmon.Customer" autowire="byName" />
彈簧有五種自動(dòng)接線模式。
客戶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 { }
這是默認(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" />
以下代碼將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" />
以下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" />
以下代碼將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" />
以下代碼顯示如何使用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" />
更多建議: