- We have changed the order of constructor.
- Observe the output.
`
<bean class="com.constructor.injection.beans.Employee" id="employee">
<constructor-arg type="float" value="10000" />
<constructor-arg type="String" value="Sumit" />
</bean>
`
`
bean initialized using str-float constructor
Name:null
Designation:Sumit
salary:10000.0
`
`
<bean class="com.constructor.injection.beans.Employee" id="employee">
<constructor-arg type="float" index="0" value="10000" />
<constructor-arg type="String" value="Sumit" />
</bean>
`
`
bean initialized using float-str constructor
Name:Sumit
Designation:null
salary:10000.0
`
- For 1st use case output, observe the output, why we are we getting wrong output ?
- That's because internally Spring uses
ConstructorResolver
class to decidewhich constructor
to use toinitialize
our beans. - This class uses
Reflection
technique whichselects
thefirst matching constructor
from theconstructor list
available and thislist is random
. - That's why if we change the
order of constructor
in the class , theselected constructor
changes.
- That's because internally Spring uses
- To resolve this, add
index
attribute- To resolve this problem the Spring team strongly
recommends
to use another attribute calledindex
with type attribute in<constructor-arg>
. - This attribute
instructs the container
to select the constructor based upon the index/order
/position
of supplied arguments.
- To resolve this problem the Spring team strongly