Monday, October 22, 2012

Basic Setter Injection


The Spring IoC container also supports setter injection, which is the preferred method of dependency injection in Spring. Setter injection uses the set* methods in a class file to garner property names that are configurable in the spring XML config.

From a configuration standpoint, setter injection is easier to read because the property name being set is assigned as an attribute to the bean, along with the value being injected. To determine the property names, Spring follows the JavaBeans Specification
(http://java.sun.com/products/javabeans/docs/spec.html).

In most cases Spring will lowercase the first letter after “set” in the method name and use the rest of the method name as-is for deducing the property name. So for example if there is a setMessage() method in your class, the property name you would use when setting that property on a bean in the XML config is 'message'. If there is a setFirstName() method in your class, the property name you would use when setting the value is 'firstName'. In cases where the letters after “set” are all uppercase, Spring will leave the property name as uppercase. So if you have setXML() on a class, the property name would be 'XML'.

Because Spring uses the set method names to infer the property name, the naming of your set methods should follow the JavaBeans Spec, or at least be consistent within the confines of your application. See the example below for basic setter injection on our Message class.

SetterMessage .java

public class SetterMessage {
  private String message = null;
  public String getMessage() { 
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
}

The property element is used to define the setter injection:
SetterMessageTest-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="message" class="org.springbyexample.di.xml.SetterMessage">
  <property name="message" value="Spring is fun." />
</bean>
</beans>

No comments:

Post a Comment