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
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency>
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
<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>in.bench.resources</groupId> <artifactId>SpringAppCore</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringAppCore</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.0.0.RELEASE</spring.version> <java.version>1.7</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-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies> </project>
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
package com.spring.series.core; public class Address { private String street; private String city; private String state; private String zipcode; /** * getter's and setter's */ public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } /** * This method prints the address details */ public void printAddressDetail(){ System.out.println("Address Street \t\t: " + street); System.out.println("Address City \t\t: " + city); System.out.println("Address State \t\t: " + state); System.out.println("Address Zip Code \t: " + zipcode); } }
Employee.java
package com.spring.series.core; public class Employee { private String name; private int age; private String employeeCode; private String designation; private Address address; /** * getter's and setter's */ 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 getEmployeeCode() { return employeeCode; } public void setEmployeeCode(String employeeCode) { this.employeeCode = employeeCode; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } /** * This method prints the employee details */ public void printEmployeeDetail(){ System.out.println("Employee Name \t\t: " + name); System.out.println("Employee Age \t\t: " + age); System.out.println("Employee Code \t\t: " + employeeCode); System.out.println("Employee Designation \t: " + designation); System.out.println("\nInvoking Address object & Printing Address details\n"); // this loc invokes method of Address class & this object is injected during spring bean instantiation address.printAddressDetail(); }
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
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <bean id="employee" class="com.spring.series.core.Employee"> <property name="name" value="Mark"></property> <property name="age" value="32"></property> <property name="employeeCode" value="E10910"></property> <property name="designation" value="Software Architect"></property> <property name="address" ref="address"></property> </bean> <bean id="address" class="com.spring.series.core.Address"> <property name="street" value="Spring Office St." /> <property name="city" value="Columbus" /> <property name="state" value="OHIO" /> <property name="zipcode" value="43211" /> </bean> </beans>
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
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
package com.spring.series.core; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestEmployee { public static void main(String[] args) { testApplicationContext(); } private static void testApplicationContext(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/core/SpringContext.xml"); Employee employee = (Employee) applicationContext.getBean("employee"); System.out.println("Spring Application Demo using ApplicationContext\n"); // invoke print() method of Employee class employee.printEmployeeDetail(); } }
Output in console
Mar 04, 2014 2:20:53 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@766e119d: startup date [Tue Mar 04 14:20:53 IST 2014]; root of context hierarchy Mar 04, 2014 2:20:53 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [com/spring/series/core/SpringContext.xml] Spring Dependency Injection using Setter Method Employee Name : Mark Employee Age : 32 Employee Code : E10910 Employee Designation : Software Architect Invoking Address object & Printing Address details Address Street : Spring Office St. Address City : Columbus Address State : OHIO Address Zip Code : 43211
Download project
Spring Dependency Injection using Setter method (3kB)
Happy Coding !!
Happy Learning !!