Spring Framework Setter Injection with Examples
In this tutorial we will discuss Spring Framework Setter Injection which is the main method of dependency injection in Spring. In the previous tutorial we discussed constructor injection, which is the another method. The property element is used to define the setter injection in Spring by using the name of the property element and looking for the corresponding setXXXXXX methods in the specified bean. The following table will provide a guideline for how Spring maps property names to Java setter method names.
Setter Injection Naming Conventions
Property Name | Setter Method Name |
---|---|
name | setName() |
setEmail() | |
favoriteName | setFavoriteName() |
HTML | setHTML() |
Setter Injection – Populating Basic Elements
Populating a bean is quite easy in Spring. Using the property element we are able to assign any of the properties of the bean by using the name attribute. When we do so, Spring will call the appropriate setter method that matches using the naming conventions described above. It will then assign the value of the field found in the value attribute.
<bean id="client" class="com.avaldes.Client"> <property name="id" value="123"></property> <property name="name" value="Amaury Valdes"></property> <property name="email" value="amaury@mail.com"></property> <property name="active" value="true"></property> <!-- more --> </bean>
Reference Injection
In reference injection, values are injected by reference. The definitions from one bean are injected into another. To do this, instead of using the attribute value, you use the ref attribute and refer to the bean’s id of the other.
<bean id="company" class="com.avaldes.Company"> <property name="name" value="TasteOHoney"></property> <property name="numEmployees" value="10"></property> <property name="client" ref="clientBean"></property> </bean> <bean id="clientBean" class="com.avaldes.Client"> <property name="id" value="123"></property> <property name="name" value="Amaury Valdes"></property> <!-- more --> </bean>
Setter Injection – Populating List Collection Elements
For the List collection, we use the property element with name attribute of “children“, create the list node and add value nodes with each of Albert Einstein’s children.
<property name="children"> <list> <value>Hans Albert Einstein</value> <value>Eduardo Einstein</value> </list> </property>
Setter Injection – Populating Map Collection Elements
Next, we will work on Map collection, which has key/value pairs. In this example, the collection is aptly named “phones“. We create the Map node, but will need to add entry key nodes with each key correctly labeled and the value for each phone in the corresponding value node.
<property name="phones"> <map> <entry key="home"> <value>212-555-1212</value> </entry> <entry key="mobile"> <value>212-444-1313</value> </entry> <entry key="work"> <value>212-333-3456</value> </entry> </map> </property>
Setter Injection – Populating Set Collection Elements
In this last example, we are populating a Set which looks very similar to List, except that the node will correspond to set instead of list. The main differing quality between a Set and List is that sets do not contain duplicate elements.
<property name="favoriteNumbers"> <set> <value>11</value> <value>17</value> <value>25</value> <value>39</value> </set> </property>
Application Context (spring-config.xml)
<?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.xsd"> <bean id="companyBean" class="com.avaldes.Company"> <property name="name" value="TasteOHoney"></property> <property name="numEmployees" value="10"></property> <property name="client" ref="clientBean"></property> </bean> <bean id="clientBean" class="com.avaldes.Client"> <property name="id" value="123"></property> <property name="name" value="Amaury Valdes"></property> <property name="email" value="amaury@mail.com"></property> <property name="active" value="true"></property> <property name="children"> <list> <value>Hans Albert Einstein</value> <value>Eduardo Einstein</value> </list> </property> <property name="phones"> <map> <entry key="home"> <value>212-555-1212</value> </entry> <entry key="mobile"> <value>212-444-1313</value> </entry> <entry key="work"> <value>212-333-3456</value> </entry> </map> </property> <property name="favoriteNumbers"> <set> <value>11</value> <value>17</value> <value>25</value> <value>39</value> </set> </property> </bean> </beans>
Maven Project Object Model (pom.xml)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.samples</groupId> <artifactId>SpringSetterInjectionExample</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <!-- Generic properties --> <java.version>1.6</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.1.1.RELEASE</version> </dependency> </dependencies> </project>
Company Class (Company.java)
package com.avaldes; public class Company { private String name; private int numEmployees; private Client client; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumEmployees() { return numEmployees; } public void setNumEmployees(int numEmployees) { this.numEmployees = numEmployees; } public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } @Override public String toString() { return "Company [name=" + name + ", numEmployees=" + numEmployees + ", client=" + client + "]"; } }
Client Class (Client.java)
package com.avaldes; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class Client { private int id; private String name; private String email; private boolean active; private ArrayList<String> children; private HashMap<String, String> phones; private HashSet<Integer> favoriteNumbers; 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public ArrayList<String> getChildren() { return children; } public void setChildren(ArrayList<String> children) { this.children = children; } public HashMap<String, String> getPhones() { return phones; } public void setPhones(HashMap<String, String> phones) { this.phones = phones; } public HashSet<Integer> getFavoriteNumbers() { return favoriteNumbers; } public void setFavoriteNumbers(HashSet<Integer> favoriteNumbers) { this.favoriteNumbers = favoriteNumbers; } public Client() { System.out.println("Inside Client() constructor..."); } @Override public String toString() { return "Client [id=" + id + ", name=" + name + ", email=" + email + ", active=" + active + ", children=" + children + ", phones=" + phones + ", favoriteNumbers=" + favoriteNumbers + "]"; } }
Tester Application (TestSetterInjection.java)
This simple tester application simply gets the spring configuration metadata from the spring-config.xml. Gets the bean called companyBean from the beanFactory and displays its contents to the console by using the toString() method.
package com.avaldes; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSetterInjection { public static void main(String[] args) { BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml"); Company company = (Company) beanFactory.getBean("companyBean"); System.out.println("Output: " + company.toString()); } }
Output – Setter Injection (DI)

Output: Company [name=TasteOHoney, numEmployees=10, client=Client [id=123, name=Amaury Valdes, email=amaury@mail.com, active=true, children=[Hans Albert Einstein, Eduardo Einstein], phones={home=212-555-1212, mobile=212-444-1313, work=212-333-3456}, favoriteNumbers=[11, 17, 25, 39]]]
That’s It
Enjoy Spring Framework!
Related Posts
- Introduction to Spring Framework, IoC and Injection
In this tutorial we will cover a basic introduction the Spring framework, Inversion of Control and Dependency Injection. We will discuss the benefits of using it, and why it is so popular in today's environment. - Spring Framework Constructor Injection Example
In this tutorial, we will concentrate on Constructor Injection. As the name suggests, constructor injection is form of dependency injection that is accomplished when we supply the arguments to the constructor so that when the bean is instantiated by the factory it contains all of the necessary information to be property constructed. - Spring Framework Constructor Injection with Collections Example
In this tutorial, we will modify our previous example and add a few collections so we can illustrate how we use constructor injection with differing collection types. Specifically, we will show how to perform constructor injection with List, Map and Set objects. - Spring Framework Setter Injection with Examples In this tutorial we will discuss Spring Framework Setter Injection which is the main method of dependency injection in Spring. The property element is used to define the setter injection in Spring by using the name of the property element and looking for the corresponding setXXXXXX methods in the specified bean.
- Spring Bean Scopes Example
In this tutorial we will begin covering scope of Spring beans. In Spring when you define a bean in the Spring configuration file, you are telling Spring about its scope whether you define it or not. This is a powerful and flexible approach because you can choose the scope of the objects you create via configuration instead of having to hardcode the scope of an object at the Java class level. - Spring Bean Life Cycle Example – @PostConstruct, @PreDestroy, InitializingBean, DisposableBean, init-method and destroy-method
In this tutorial we will cover the Spring Bean Life Cycle and the methods, attributes and annotations used to hook into the management of the bean life cycle in the IoC container. - Integrating Java JMX Managed Beans using Spring and Annotations
This post will show how to create managed beans using the JMX standard using Spring. JMX stands for Java Management Extensions, and was created to implement a standard and uniform way to manage your applications. By using JMX remote can connection to a JVM and monitor running applications on that JVM. In addition to monitoring, remote clients are able to directly run methods and modify runtime parameters of the application that is being managed. - Integrating Spring Message Driven POJO with ActiveMQ
This post will show how to create a message driven POJO that can send and receive JMS message using ActiveMQ as the Message Oriented Middleware (MOM). We will discuss various approaches to creating the MDPs (Message Driven POJOs) in this tutorial and discuss setting up ActiveMQ from Apache.
Please Share Us on Social Media






Leave a Reply