English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring setter method injection

We can also inject dependencies through setter methods. <bean>of <property>Sub-elements are used for Setter injection. Here, we need to inject

Original and string-based values Subset objects (including objects) Set values

Injecting original values and values based on strings through setter methods.

Let's take a look at injecting original values and values based on strings through setter methods. We have created three files here:

Employee.java applicationContext.xml Test.java

Employee.java

This is a simple class that contains three fields id, name, and city, along with their setters and getters, and a method to display this information.

package com.w3codebox;
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);
}
}

applicationContext.xml

We provide information to the Bean through this file. The property element calls the setter method. The value sub-element of the attribute assigns 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.w3codebox.Employee</codebox.Employee>
<property name="id">
<value>20</value>/value>
</property>
<property name="name">
<value>Arun</value>/value>
</property>
<property name="city">
<value>ghaziabad</value>/value>
</property>
</bean>
</beans>

Test.java

This class retrieves a Bean from the applicationContext.xml file and calls the display method.

package com.w3codebox;
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();
        
    }
}

Output:

20 Arun Ghaziabad