Spring DI- Constructor Injection with XML Metadata configuration

Type Matching : Type(String / int) can be used to avoid ambiguity. Like in previous example we can use type as String or int to match the argument type.
Example :

 <bean id="address" >
  <constructor-arg type="int" value="276044"></constructor-arg>          -- line 1
  <constructor-arg type="java.lang.String" value="360"></constructor-arg>         -- line 2
  <constructor-arg type="java.lang.String" value="C2"></constructor-arg>                -- line 3
  <constructor-arg type="java.lang.String" value="My Street"></constructor-arg>        -- line 4
  <constructor-arg type="java.lang.String" value="My City"></constructor-arg>        -- line 5
 </bean>

In above example spring container will identify the sequence of argument same as they are defined here and type will help container to avoid ambiguity.
Sequence of argument in constructor would be line 2-3-4-5-1

Constructor argument sequence(Explicit) : There might be the case when sequence of the argument is not the same in constructor as it is defined in XML. To define the sequence of the argument explicitly, index attribute could be used.

Example :

 <bean id="address" >
  <constructor-arg type="int" value="276044"></constructor-arg>          -- line 1
  <constructor-arg type="java.lang.String" value="My Street"></constructor-arg>        -- line 2
  <constructor-arg type="java.lang.String" value="My City"></constructor-arg>        -- line 3
  <constructor-arg type="java.lang.String" value="360" index ="0"></constructor-arg>     -- line 4
  <constructor-arg type="java.lang.String" value="C2" index ="1"></constructor-arg>      -- line 5
 </bean>

Note*: Index is 0 based.
Note*: Here index for two argument is provided while index for other 3 other args are not defined in that case container will take sequence as it is defined here.
Sequence of the argument in constructor should be line 4-5-2-3-1

Leave A Comment

Your email address will not be published. Required fields are marked *