Rajinder Menu

Setter-Based Dependency Injection


In Setter based dependency injection Spring Container uses setter methods of the properties defined in the class to inject their values.

<property name="prop_name" value="prop_value"/>  tag is used in the bean definition to provide values for properties in the class.

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

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

    /*Spring Container will use this setter method for injecting value for 'make' property*/
    public void setMake(String make){
        this.make=make;
    }
 
    public String getMake(){
        return make;
    }

//setters and getters for other properties...

}

Above class has three properties namely make, model, year.

To inject values for these properties you will define your bean in bean configuration file as :

<bean id="myCar" class="examples.spring.di.Car">
   <property name="make" value="Maruti Suzuki"/>
   <property name="model" value="Wagon R"/>
   <property name="year" value="2012"/>
</bean>


In above bean definition we have  injected only primitive values . Suppose Car class has one more property of type Engine (Let Engine is some other class) as:

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

//setters and getters...

}

Then your bean defintion would become:

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

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

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

Note that we have used ref attribute instead of value attribute in. Attribute ref is used to point to the id of some other bean instead of primitive values (like String, int etc).

You can find full example here.



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