我最近開始在spring 3.2上工作。我試圖理解構造函數參數解析的情況下,何時通過構造函數注入傳遞依賴關係。我創建了下面的例子。構造函數參數解析
package com.springinaction.springidol;
public interface Performer {
void perform();
}
package com.springinaction.springidol;
public class Juggler implements Performer {
private int beanBags=3;
private String name;
public Juggler(){
}
public Juggler(String name,int beanBags){
System.out.println("First constructor gets called");
this.beanBags=beanBags;
this.name=name;
}
public Juggler(int beanBags,String name){
System.out.println("Second constructor gets called");
this.beanBags=beanBags;
this.name=name;
}
public void perform(){
System.out.println("JUGGLING "+beanBags+name+" BEANBAGS");
}
}
請查看下面我用過的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-3.0.xsd">
<bean id="duke" class="com.springinaction.springidol.Juggler">
<constructor-arg value="Jinesh" />
<constructor-arg value="77" />
</bean>
在上述情況下調用的構造是第一構造函數。但在此之後,我稍微更改了xml文件併爲這兩個參數添加了type屬性。
<?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-3.0.xsd">
<bean id="duke" class="com.springinaction.springidol.Juggler">
<constructor-arg type="java.lang.String" value="Jinesh" />
<constructor-arg type="int" value="77" />
</bean>
</beans>
在上面的例子中,spring調用的構造函數是第二個構造函數。我不明白爲什麼春天決定調用第二個構造函數而不是第一個構造函數?在上面的例子中,spring如何決定在傳遞type屬性時調用哪個構造函數?
感謝這樣詳細的解釋索蒂里奧斯。第一種情況下是否也遵循上述流程?如果遵循相同的流程,那麼爲什麼它在第一個場景中調用了第一個構造函數? – Beast
@Beast過程是一樣的,但這裏參數的順序很重要。在'ConstructorResolver'遍歷構造的陣列中,嘗試使用'(INT,字符串)'但失敗了,因爲值'Jinesh'不能轉換到一個'int'。發生'UnsatisfiedDependencyException'並且該構造函數被跳過。所述陣列中的第二個構造變成候選(第一在您的示例),並且因爲'「77」'可以被轉換爲一個'int',它被選擇。在堆棧的某個地方,有一個轉換系統在做某些事情。 –
感謝您的replyour的幫助,如果我想通過基於Maven春源代碼你們有任何配置文件來調試所有help.One最後一個問題? – Beast