In the Spring framework, we can also inject the dependency between the beans by using the Setter method. The setter method is a preferable one in Spring because it is easier to understand as the property name being set is just acted like an attribute to the bean. In this method, we create a setter for each dependent object and pass it as a parameter to the associated setter. We then bind these parameterized objects based on the spring configuration file.
For injecting through the setter method, The property subelement of bean is used. In this type of Dependency injection, we will inject;
In this example, we will see how we can identify the dependency between the dependent objects through Injecting primitive and string-based values by the Setter method. For this purpose, we create three files:
It is a simple class that includes id, name, and city as the three fields with its setters and getters and a method to display the field values.
package com.intellinuts; public class Employee { private int id; private String name; private String city; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } void display(){ System.out.println(id+" "+name+" "+city); } }
This file is used to provide the information to the bean. Here, the property element calls the setter method. The value subelement of the property will be used to assign the specified value.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="obj" class="com.intellinuts.Employee"> <property name="id"> <value>20</value> </property> <property name="name"> <value>Arun</value> </property> <property name="city"> <value>Ghaziabad</value> </property> </bean> </beans>
This class gets the bean from the applicationContext.xml file and calls the display() method to print the output.
package com.intellinuts; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.*; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Employee e=(Employee)factory.getBean("obj"); s.display(); } }
The result will be:
20 Arun Ghaziabad