Constructor argument resolution:-
Constructor argument resolution matching occurs using the argument’s type. If no
potential ambiguity exists in the constructor arguments of a bean definition,
then the order in which the constructor arguments are defined in a bean
definition is the order in which those arguments are supplied to the appropriate
constructor when the bean is being instantiated. Consider the following class:
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}}
The following configuration works fine, and you do not need to specify the constructor argument indexes.
<beans>
<bean id="foo" class="x.y.Foo">
<constructor-arg ref="bar"/>
<constructor-arg ref="baz"/>
</bean>
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
</beans>
Let we check one more case where we pass different types to the constructor. Consider the following class:
package x.y;
public class Foo {
private int years;
private String name;
public Foo(int years, String name) {
this.years = years;
this.name = name;
}}
The container can use type matching with simple types if you explicitly specify the type of the constructor argument using the type attribute. For example:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="2014"/>
<constructor-arg type="java.lang.String" value="Vipul"/>
</bean>
The best way to pass constructor arguments, use the index attribute to specify explicitly the index of constructor arguments. Here the index is 0 based. For example:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="2014"/>
<constructor-arg index="1" value="Vipul"/>
</bean>
Finally in case you are passing a reference to an object, you need to use ref attribute of <constructor-arg> tag and if you are passing a value directly then you should use value attribute.