Spring DI- Constructor Injection with XML Metadata configuration

Constructor argument name: Introduced in Spring 3.0. To resolve the argument ambiguity now name of the constructor argument could also be used.

 <bean id="address" >
  <constructor-arg type="int" value="276044"></constructor-arg>                               -- line 1
  <constructor-arg type="java.lang.String" value="My City"></constructor-arg>                        -- line 2
  <constructor-arg type="java.lang.String" name ="street" value="My Street"></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>

Here name of the argument is mentioned as “street” hence that will be treated as argument for street field. For others sequence will be treated as it defined here.
Sequence of argument in constructor would be line 3-2-4-5-1

Note*:To make it work @ConstructorProperties() needs to be used to define the name of the property.

@ConstructorProperties({"flatNo", "bldgNo","streetNo","city","pincode"})
 public Address(String flatNo, String bldgNo, String streetNo, String city,int pincode) {
  super();
  this.flatNo = flatNo;
  this.bldgNo = bldgNo;
  this.streetNo = streetNo;
  this.city = city;
  this.pincode = pincode;
 }

All above things can be done via static factory method instead of constructor. In that case name of the factory method in the class needs to be mentioned via “factory-method” tag.

Example : Address class has static factory method that creates Object of the address class and do some operation on it.

 public static Address createInstance(String flatNo, String bldgNo, String streetNo, String city, int pincode){
  Address a1 = new Address();
  a1.setflatNo(add);
  a1.setbldgNo(com);
  a1.setstreetNo(name);
  a1.setCity(city);
  a1.setPincode(pincode);
  return a1;
 }

Now we can use constructor injection, but not static factory method will be invoked.

 <bean id="address" factory-method="createInstance">
  <constructor-arg type="int" value="276044"></constructor-arg>
  <constructor-arg type="java.lang.String" value="360"></constructor-arg>
  <constructor-arg type="java.lang.String" value="C2"></constructor-arg>
  <constructor-arg type="java.lang.String" value="My Street"></constructor-arg>
  <constructor-arg type="java.lang.String" value="My City"></constructor-arg>
 </bean>

 

Leave A Comment

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