Spring overloaded constructor injection

老子叫甜甜 提交于 2019-11-27 07:58:04

问题


This is the code :

public class Triangle {


private String color;
private int height;


public Triangle(String color,int height){
    this.color = color;
    this.height = height;
}

public Triangle(int height ,String color){
    this.color = color;
    this.height = height;
}

public void draw() {
    System.out.println("Triangle is drawn , +
            "color:"+color+" ,height:"+height);
}

}

The Spring config-file is :

 <bean id="triangle" class="org.tester.Triangle">
    <constructor-arg value="20" />
    <constructor-arg value="10" />
</bean>

Is there any specific rule to determine which constructor will be called by Spring ?


回答1:


Here, the first argument will be matched to the first parameter of each method and then the parameter will be matched.

I would suggest the solution below to help remove ambiguity

If you want to call your first constructor use

<bean id="triangle" class="org.tester.Triangle">
<constructor-arg type="int"  value="20" />
<constructor-arg type="java.lang.String"  value="10" />
</bean>

If you want to call your second constructor use

<bean id="triangle" class="org.tester.Triangle">
    <constructor-arg type="java.lang.String"value="20" />
    <constructor-arg   type="int"  value="10" />
</bean>

So that resolves the ambiguity

EDIT :-

Please read more about this problem here.




回答2:


I don't believe so. Note that you can type the arguments e.g:

<bean id="triangle" class="org.tester.Triangle">
    <constructor-arg type="int" value="20" />
    <constructor-arg value="10" />
</bean>

which would remove the confusion in this scenario.




回答3:


Based on tests for Spring 3.1.0, the second constructor will be used. I don't know why, the documentation didn't give any definitive answer.

Bitbucket code To test, run Main class, it will output String FIRST or SECOND, depending which constructor will be used to create Triangle object.



来源:https://stackoverflow.com/questions/13864787/spring-overloaded-constructor-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!