Sunday, 14 April 2013

Setter Injection in spring

Setter Injection:

If Spring container uses setter methods of spring bean class to inject dependent values of Bean properties, then it is called “setter injection”. In this process spring container uses zero argument constructor to create Spring Bean class object.

Lets discuss this process with an example


public class DemoBean {

  String message;

  // Setter Method
  public void setMessage(String message) {
   this.message = message;
  }

  // Getter Method.
  public String getMessage() {
   return message;
  }

}

Actually getter method is not necessary for injecting dependencies using setter injection. For performing setter injection setter method is enough. Getter method is only used when we want to access the value of that particular variable otherwise there is no need to write getter method.


Lets see how we can map the above class as a bean in xml file

<bean id="demoBean" class="DemoBean">
  <property name="message" value="Hello"/>
</bean>

As we are performing setter injection properties (Variables in class) of class are defined in <propertry/> tag inside <bean> tag.

In the above bean definition we have given the name of property as message hence spring container searches for a proper setter method for the given property "message". It places 'set' before the property name and makes first letter of the property capital, hence the appropriate setter method for the above property "message" is setMessage(). So spring container searcher for a method with the name setMessage() in DemoBean class.

If there is no proper setter method specified for the given property then it generates an exception.

You can also observe that we have specified an attribute "value" in <property/> tag. That means when setMessage() method is called the value "Hello" is passed as an argument to that method.

Note: setter injection only searches for appropriate setter method of the property name specified in <property/> tag. It doesn't matter which name of variable we have specified in the class. In other words variable names in the class should not be same as the property name of the bean.

For instance in the above example it is not mandatory to have the name of the variable as "message" in DemoBean. But we must have a proper setter method setMessage(String message).


No comments:

Post a Comment