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; }
}
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
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;
}
}
<bean id="exampleBean" class="com.vaani.spring.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
</bean>
Note that we are doing ref bean= and then referring to bean.
No comments:
Post a Comment