Constructor-arg behavior for spring ... Why the following behavior?

Rectangle(int x, String y){
    this.x=x;
    this.y=y;
}

Rectangle(String y, int z){
    this.z=z;
    this.y=y;
}

      

In the above code, I used folllowing in the xml: -

<constructor-arg type="int" value="10"/>
<constructor-arg type="java.lang.String" value="10"/>

      

the constructor that works in this case is the second ... Why? How does spring decide which one to call here

+3


source to share


1 answer


This mainly happens because the order in which the arguments appear in the bean config file will not be considered when the constructor is called .

To solve this problem , you can use the index attribute to specify the index of the constructor argument. Here is the bean config file after adding the index attribute:



<bean id="rectangle" class="com.shape.rectangle" >
    <constructor-arg index="0" type="int" value="10"/>
    <constructor-arg index="1" type="java.lang.String" value="10"/>
</bean>

      

+6


source







All Articles