Spring Dependency Injection using Setter method

In this article, we will extend the previous article to learn one of the Spring Framework’s core feature Dependency Injection (DI). DI refers to the concept of supplying the external dependencies to the software component rather than creating/instantiating the objects in traditional way using ‘new’ operator.

There are three types of Dependency Injection provided by Spring Framework or to be precise IoC container. These are

  • Setter Injection – most favored & widely used
  • Constructor Injection – dependencies are supplied during instance instantiation
  • Interface Injection

Out of above three approaches, we will see an example for first two. And this article describes & demonstrates about the setter injection. In the next article, we will learn about constructor injection.

Technology Used

  • Java 1.7
  • Eclipse Kepler IDE
  • Maven 3.0.4
  • Spring-4.0.0-RELEASE

Maven-zing Spring Application

This is the simple Application using Setter Injection to demonstrate how external dependencies are getting injected into the spring beans using declarative Spring context XML

Note: And we don’t really require the Maven here for creating build (war/ear) but having said that this helps to download the required jars from the repository. Using maven command, we can include these downloaded jars into eclipse classpath using mvn eclipse:eclipse

Add Spring-4.0.0 dependencies to the pom.xml

<br />
&lt;dependency&gt;<br />
	&lt;groupId&gt;org.springframework&lt;/groupId&gt;<br />
	&lt;artifactId&gt;spring-core&lt;/artifactId&gt;<br />
	&lt;version&gt;${spring.version}&lt;/version&gt;<br />
&lt;/dependency&gt;<br />
&lt;dependency&gt;<br />
	&lt;groupId&gt;org.springframework&lt;/groupId&gt;<br />
	&lt;artifactId&gt;spring-context&lt;/artifactId&gt;<br />
	&lt;version&gt;${spring.version}&lt;/version&gt;<br />
&lt;/dependency&gt;<br />

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath.

  • spring-core-4.0.0-RELEASE
  • spring-context-4.0.0-RELEASE
  • spring-beans-4.0.0-RELEASE
  • spring-aop-4.0.0-RELEASE
  • spring-expression-4.0.0-RELEASE
  • commons-logging-1.1.1
  • aopalliance-1.0

Complete pom.xml here

<br />
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br />
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;</p>
<p>	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br />
	&lt;groupId&gt;in.bench.resources&lt;/groupId&gt;<br />
	&lt;artifactId&gt;SpringAppCore&lt;/artifactId&gt;<br />
	&lt;packaging&gt;war&lt;/packaging&gt;<br />
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br />
	&lt;name&gt;SpringAppCore&lt;/name&gt;<br />
	&lt;url&gt;http://maven.apache.org&lt;/url&gt;</p>
<p>	&lt;properties&gt;<br />
		&lt;spring.version&gt;4.0.0.RELEASE&lt;/spring.version&gt;<br />
		&lt;java.version&gt;1.7&lt;/java.version&gt;<br />
		&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br />
		&lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;<br />
	&lt;/properties&gt;</p>
<p>	&lt;dependencies&gt;<br />
		&lt;dependency&gt;<br />
			&lt;groupId&gt;org.springframework&lt;/groupId&gt;<br />
			&lt;artifactId&gt;spring-core&lt;/artifactId&gt;<br />
			&lt;version&gt;${spring.version}&lt;/version&gt;<br />
		&lt;/dependency&gt;<br />
		&lt;dependency&gt;<br />
			&lt;groupId&gt;org.springframework&lt;/groupId&gt;<br />
			&lt;artifactId&gt;spring-context&lt;/artifactId&gt;<br />
			&lt;version&gt;${spring.version}&lt;/version&gt;<br />
		&lt;/dependency&gt;<br />
	&lt;/dependencies&gt;<br />
&lt;/project&gt;<br />

Let’s see coding in action

Create Address and Employee Class

For this Setter Dependency Injection, we will create two classes namely Employee & Address. And in the Employee Class, we will have address as member variable. This is the variable which will get injected during bean instantiation of employee bean using ‘ref’ attribute.

Address.java

<br />
package com.spring.series.core;</p>
<p>public class Address {</p>
<p>	private String street;<br />
	private String city;<br />
	private String state;<br />
	private String zipcode;</p>
<p>	/**<br />
	 * getter's and setter's<br />
	 */<br />
	public String getStreet() {<br />
		return street;<br />
	}<br />
	public void setStreet(String street) {<br />
		this.street = street;<br />
	}<br />
	public String getCity() {<br />
		return city;<br />
	}<br />
	public void setCity(String city) {<br />
		this.city = city;<br />
	}<br />
	public String getState() {<br />
		return state;<br />
	}<br />
	public void setState(String state) {<br />
		this.state = state;<br />
	}<br />
	public String getZipcode() {<br />
		return zipcode;<br />
	}<br />
	public void setZipcode(String zipcode) {<br />
		this.zipcode = zipcode;<br />
	}</p>
<p>	/**<br />
	 * This method prints the address details<br />
	 */<br />
	public void printAddressDetail(){<br />
		System.out.println(&quot;Address Street \t\t: &quot; + street);<br />
		System.out.println(&quot;Address City \t\t: &quot; + city);<br />
		System.out.println(&quot;Address State \t\t: &quot; + state);<br />
		System.out.println(&quot;Address Zip Code \t: &quot; + zipcode);<br />
	}<br />
}<br />

Employee.java

<br />
package com.spring.series.core;</p>
<p>public class Employee {</p>
<p>	private String name;<br />
	private int age;<br />
	private String employeeCode;<br />
	private String designation;<br />
	private Address address;</p>
<p>	/**<br />
	 * getter's and setter's<br />
	 */<br />
	public String getName() {<br />
		return name;<br />
	}<br />
	public void setName(String name) {<br />
		this.name = name;<br />
	}<br />
	public int getAge() {<br />
		return age;<br />
	}<br />
	public void setAge(int age) {<br />
		this.age = age;<br />
	}<br />
	public String getEmployeeCode() {<br />
		return employeeCode;<br />
	}<br />
	public void setEmployeeCode(String employeeCode) {<br />
		this.employeeCode = employeeCode;<br />
	}<br />
	public String getDesignation() {<br />
		return designation;<br />
	}<br />
	public void setDesignation(String designation) {<br />
		this.designation = designation;<br />
	}<br />
	public Address getAddress() {<br />
		return address;<br />
	}<br />
	public void setAddress(Address address) {<br />
		this.address = address;<br />
	}</p>
<p>	/**<br />
	 * This method prints the employee details<br />
	 */<br />
	public void printEmployeeDetail(){</p>
<p>		System.out.println(&quot;Employee Name \t\t: &quot; + name);<br />
		System.out.println(&quot;Employee Age \t\t: &quot; + age);<br />
		System.out.println(&quot;Employee Code \t\t: &quot; + employeeCode);<br />
		System.out.println(&quot;Employee Designation \t: &quot; + designation);</p>
<p>		System.out.println(&quot;\nInvoking Address object &amp; Printing Address details\n&quot;);</p>
<p>		// this loc invokes method of Address class &amp; this object is injected during spring bean instantiation<br />
		address.printAddressDetail();<br />
	}<br />
}<br />

Create Spring Bean Configuration file (Spring XML)

Configure the spring bean xml for employee bean & for the address attribute of employee bean reference the bean ‘address’ declared in the xml via property tag “ref” attribute.

From the Spring Bean XML, it is quite evident that dependent bean ‘address’ is injected into ‘employee’ bean via setter property/method i.e.; Setter injection.

SpringContext.xml

<br />
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br />
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;<br />
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:context=&quot;http://www.springframework.org/schema/context&quot;<br />
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<br />
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd&quot;&gt;</p>
<p>	&lt;bean id=&quot;employee&quot; class=&quot;com.spring.series.core.Employee&quot;&gt;<br />
		&lt;property name=&quot;name&quot; value=&quot;Mark&quot;&gt;&lt;/property&gt;<br />
		&lt;property name=&quot;age&quot; value=&quot;32&quot;&gt;&lt;/property&gt;<br />
		&lt;property name=&quot;employeeCode&quot; value=&quot;E10910&quot;&gt;&lt;/property&gt;<br />
		&lt;property name=&quot;designation&quot; value=&quot;Software Architect&quot;&gt;&lt;/property&gt;<br />
		&lt;property name=&quot;address&quot; ref=&quot;address&quot;&gt;&lt;/property&gt;<br />
	&lt;/bean&gt;</p>
<p>	&lt;bean id=&quot;address&quot; class=&quot;com.spring.series.core.Address&quot;&gt;<br />
		&lt;property name=&quot;street&quot; value=&quot;Spring Office St.&quot; /&gt;<br />
		&lt;property name=&quot;city&quot; value=&quot;Columbus&quot; /&gt;<br />
		&lt;property name=&quot;state&quot; value=&quot;OHIO&quot; /&gt;<br />
		&lt;property name=&quot;zipcode&quot; value=&quot;43211&quot; /&gt;<br />
	&lt;/bean&gt;</p>
<p>&lt;/beans&gt;<br />

Note: Name of the Spring Bean Configuration file can be anything (not necessary to have SpringContext.xml) and it’s your choice. But, in the enterprise application keep these file names appropriate to the business context. So that it will increase the readability of the application

Setter Injection

Test the Application that’s exactly …. Run it!

Having done with coding of Spring Bean (i.e.; Employee & Address POJO’s) and configured necessary Spring bean XML and its dependent beans, it’s time to execute and see the magic of Spring Framework’s one of core features Dependency Injection (via., setter method)

Let’s test using ApplicationContext

TestEmployee.java

<br />
package com.spring.series.core;</p>
<p>import org.springframework.context.ApplicationContext;<br />
import org.springframework.context.support.ClassPathXmlApplicationContext;</p>
<p>public class TestEmployee {</p>
<p>	public static void main(String[] args) {<br />
		testApplicationContext();<br />
	}</p>
<p>	private static void testApplicationContext(){</p>
<p>		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(&quot;com/spring/series/core/SpringContext.xml&quot;);<br />
		Employee employee = (Employee) applicationContext.getBean(&quot;employee&quot;);</p>
<p>		System.out.println(&quot;Spring Application Demo using ApplicationContext\n&quot;);</p>
<p>		// invoke print() method of Employee class<br />
		employee.printEmployeeDetail();<br />
	}<br />
}<br />

Output in console

<br />
Spring Dependency Injection using Setter Method</p>
<p>Employee Name 		: Mark<br />
Employee Age 		: 32<br />
Employee Code 		: E10910<br />
Employee Designation 	: Software Architect</p>
<p>Invoking Address object &amp; Printing Address details</p>
<p>Address Street 		: Spring Office St.<br />
Address City 		: Columbus<br />
Address State 		: OHIO<br />
Address Zip Code 	: 43211<br />

Download project

Spring Dependency Injection using Setter method (3kB)

Happy Coding !!
Happy Learning !!