Spring inline constructor overload

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); } } 

Spring configuration file:

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

Is there any specific rule for determining which constructor Spring will call?

+4
source share
3 answers

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

I suggest a solution below to help eliminate 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, to eliminate the ambiguity

EDIT: -

Read more about this issue here .

+3
source

I donโ€™t believe that. Note that you can enter arguments, for example:

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

which will eliminate the confusion in this scenario.

0
source

Based on tests for Spring 3.1.0, the second constructor will be used. I do not know why, the documentation did not give a definitive answer.

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

0
source

All Articles