Rajinder Menu

Constructor-Based Dependency Injection


In Constructor based dependency injection, Spring Container uses one of the constructors defined in the class in order to inject dependencies for that class.

In constructor based DI, instead of <property name="prop_name" value="prop_value"/>  tag, you use <constructor-arg  name="arg_name"  value="arg_value"/> tag in the bean definition.

For example, suppose you have a Car class defined as:

public class Car {
    private String make;
    private String model;
    private int year;
    private Engine engine;

/*Spring Container will use this constructor to inject dependencies*/
public Car(String make,String model,int year){
    this.engine=engine;
    this.model=model;
    this.make=make;
    this.year=year;
}
//setters and getters...
}

In the above class there is a constructor which has three arguments namely make, model, year.

Now in order inject these dependencies you will define your bean as :

<bean id="myCar"  class="exampes.spring.di.Car">
    <constructor-arg name="make" value="Maruti Suzuki"/>
    <constructor-arg name="model" value="Wagon R"/>
   <constructor-arg name="year" value="2012"/>

</bean>

In above bean definition we have  injected only primited values . Suppose Car class has a constructor :

public Car(String make,String model,int year, Engine engine){
...
this.engine=engine;
}

Here constructor has one more argument which is a reference to an instance of some other class Engine.

Now your bean definition will get changed as:

<bean id="myCar"  class="exampes.spring.di.Car">
   <constructor-arg name="make" value="Maruti Suzuki"/>
   <constructor-arg name="model" value="Wagon R"/>
   <constructor-arg name="year" value="2012"/>
  <constructor-arg name="engine" ref="myEngine"/>
</bean>

where myEngine is some other bean defined in configuration file as:

<bean id="myEngine" class="examples.spring.di.Engine">
...
</bean>

You can find full example here.

TODO: ambiguities in constructor resolving.




I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment