Yatin Garg
Yatin Garg

Reputation: 141

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

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

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

In 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 one... Why? How the spring decides here which one to call

Upvotes: 3

Views: 104

Answers (1)

Yuri
Yuri

Reputation: 1814

Basically this happens because the order in which the arguments appear in the bean configuration file will not be considered when invoking the constructor.

To solve this problem you can use the index attribute to specify the constructor argument index. Here is the bean configuration 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>

Upvotes: 5

Related Questions