Search

Spring Setter Injection Example

In this example you will learn how to set a bean property via setter injection. Consider the followingUser bean class.
package com.vaannila;

public class User {

private String name;
private int age;
private String country;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public String toString() {
return name + " is " + age + " years old, living in " + country;
}
}
 The User bean class has three attributes viz. name, age and country. All the three attributes are set using the setter injection. The toString() method of the User bean class is overridden to display the user object.
Here the beans.xml file is used to do spring bean configuration. The following code shows how to set a property value thru setter injection.
<?xml version="0" encoding="UTF-8"?>

<bean id="user" class="com.vaannila.User" >
<property name="name" value="Eswar" />
<property name="age" value="24"/>
<property name="country" value="India"/>
</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.
Here we set "Eswar", "24" and "India" for the User bean properties name, age and countryrespectively. The following Main class is used to get the User bean from the Spring IoC container and dispaly its value it to the user.
package com.vaannila;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support. ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {
ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
User user = (User)context.getBean("user");
System.out.println(user);
}

}
 On executing the Main class the following message gets displayed on the console.
Eswar is 24 years old, living in India
Download Spring examples source code

No comments:

Post a Comment