Spring overloaded constructor injection

后端 未结 3 1407
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 21:28

This is the code :

public class Triangle {


private String color;
private int height;


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


        
相关标签:
3条回答
  • 2020-12-11 21:56

    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.

    0 讨论(0)
  • 2020-12-11 22:02

    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.

    0 讨论(0)
  • 2020-12-11 22:16

    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.

    0 讨论(0)
提交回复
热议问题