Friday, March 18, 2011

Spring : Setter Dependency Injection(Xml approach)

In this example you will learn how to set a bean property via setter injection. Consider the bean here :

package com.vaani.spring.beans;
public class ExampleBean
{
private String s;
private int i;

public void setStringProperty(String s) { this.s = s; }
public void setIntegerProperty(int i) { this.i = i; }
}
Now the above bean has 2 attributes – String s and int i. Now the bean has corresponding setters in it.

Bean Configuration file – Using property and value tags
Here the beans.xml file is used to do spring bean configuration. The following code shows how to set a property value through setter injection.

<?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"
>
<!--inject the ExampleBean -->
<!-- -->
<bean id="exampleBean" class="com.vaani.spring.ExampleBean">
<property name="stringProperty">
<value>Hi!</value>
</property>
<property name="integerProperty">
<value>1</value>
</property>
</bean>
</beans>

The id attribute of the bean element is used to specify the bean name and the class attribute is used to specify the fully qualified class name of the bean. The property element with in the bean element is used to inject property value via setter injection. The name attribute of the property element represents the bean attribute and the value attribute specifies the corresponding property value.
Note – To do setter injection we need to have a setter in the class, such that its name is derived as setAbc, than in spring you should name property as abc.
Here we set "Hi!" and "1" for the example bean. properties – s and i respectively.

Download the source

The Example can be downloaded from here.


DI when properties are not simple types


So here ref comes into picture. Example for passing property value as an another bean

package com.vaani.spring;
public class ExampleBean
{
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
public void setBeanOne(AnotherBean b) {
beanOne = b;
}
public void setBeanTwo(YetAnotherBean b) {
beanTwo = b;
}
}
In the XML bean descriptor file:

<bean id="exampleBean" class="com.vaani.spring.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
</bean>
We can refer these beans by using getBeans method , like we did it here.
Note that we are doing ref bean= and then referring to bean.

Download the source


You can download the source code from here.

No comments:

Post a Comment

Chitika