Setter Injection

Setter Injection is a bean wiring technique in which the JavaBean setter methods are used for supplying the bean properties to the objects that need them.

You can wire the bean properties by declaring a <property> element for the bean in the configuration file within the <bean> tag.

The <property> element can inject dependencies using the setter methods of the property in the following ways:

Injecting simple values

Referencing other beans

Injecting simple values:

You can use the value attribute of the <property> element to inject a string value into a bean property.

The value attribute can also take on values of other types such as integer floating point and boolean.

For example:
<bean id="triangle"
class="org.manish.javasafari">
<property name="type" value="Equilateral"/>
</bean>      

Now add a variable type to Triangle class and write get and set for this variable.

package org.manish.javasafari;

public class Triangle {
	String type;
public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
public void draw()
{
System.out.println(getType() +"Triangle Draw");	
}
}

Lets run the app and see the output

Spring Setter injection

Referencing other beans:

  • You can also wire beans of an application with each other with the help of DI.
  • To wire beans with each other, you have to specify bean references in the bean configuration file.
  • You can specify a bean reference for a bean property by using the ref attribute of the element.
  • The ref attribute sets the value of the specified property of the bean by passing to it a reference of another bean.
For example:
<bean id="color"
class="org.manish.javasafari.Color"/>

<bean id="Triangle"
class="org.manish.javasafari.Triangle">
<property name="type" value="Equilateral" />
<property name="cl" ref="color" /></bean>