At the Core of Spring Framework, Spring IoC (Inversion of Control) is implemented using the Dependency Injection design pattern. The Spring IoC Container creates, configures and connects the objects (which are called Beans), then manage their life cycle.
This tutorial introduce principle of Spring IoC and a simple example using Containers to you.
I. Technology
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.0.RELEASE
II. Overview
1. Container & Dependency Injection
The container helps inject the dependencies. Let’s see an example:
We want to provide a CustomerService with 2 implementations of CustomerPackage: BasicPackage and BusinessPackage.
This is content of CustomerService.java
public class CustomerService { private CustomerPackage customerPackage = new BasicPackage(); //or new BusinessPackage() public String callSupport() { return customerPackage.support(); } } |
Because we create a CustomerPackage instance in the class CustomerService, it is tightly coupled. So if we want to change BasicPackage to BusinessPackage, we need to modify:
private CustomerPackage customerPackage = new BusinessPackage(); |
To avoid this kind of coupling, Spring Framework has a strong container to manage components. Instead of hard coding by creating new instance inside, we have the container inject the dependencies, by using setter injection or constructor injection.
Content of CustomerService.java after using Dependency Injection
public class CustomerService { // private CustomerPackage customerPackage = new BasicPackage(); //or new BusinessPackage() // // public String callSupport() { // return customerPackage.support(); // } CustomerPackage customerPackage; //setter injection public void setCustomerPackage(CustomerPackage customerPackage) { this.customerPackage = customerPackage; } public String callSupport() { return customerPackage.support(); } } |
Now, we don’t need to instantiate CustomerPackage object because the container will handle the operation.
Configuration for IoC Container will be done in XML file:
<bean id="basicPackage" class="...BasicPackage"></bean> <bean id="businessPackage" class="...BusinessPackage"></bean> <bean id="customerService" class="...CustomerService"> <property name="customerPackage"> <ref bean="basicPackage" /> </property> </bean> |
The container reads configuration metadata (XML, Java annotations, or Java code) to know what objects to instantiate, configure, and assemble.
The diagram below shows a high-level view of how Spring Container works:
2. Types of Containers
Spring provides two types of containers:
– BeanFactory: the root interface of Spring IoC container.
– ApplicationContext: child interface of BeanFactory, provides Spring AOP features. It has some useful implementations:
+ AnnotationConfigApplicationContext: for standalone java applications and in case of using annotations for Configuration.
+ ClassPathXmlApplicationContext: If using Configuration XML File in standalone application, we do not need to provide the full path of the XML file.
+ FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext but Configuration XML File can be loaded from anywhere in the file system, so we must provide full path.
+ AnnotationConfigWebApplicationContext and XmlWebApplicationContext: for web applications.
3. Project Structure
4. Step to do
– Create Spring Boot project
– Create Interface & Classes for Bean
– Create Service
– Create Spring Bean Configuration File
– Add commands to SpringBootApplication Class
– Run Spring Boot Application & Enjoy Result
III. Practice
1. Create Spring Boot project
Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields:
Click Next and Finish. Spring Boot project will be created successfully.
2. Create Interface & Classes for Bean
Under package bean, create interface CustomerPackage and its implementations:
CustomerPackage.java
package com.javasampleapproach.springioc.bean; public interface CustomerPackage { public String support(); } |
BasicPackage.java
package com.javasampleapproach.springioc.bean; public class BasicPackage implements CustomerPackage{ @Override public String support() { return "Support Basic Customers"; } } |
BusinessPackage.java
package com.javasampleapproach.springioc.bean; public class BusinessPackage implements CustomerPackage { @Override public String support() { return "Support Business Customers"; } } |
3. Create Service
Under package service, create CustomerService.java:
package com.javasampleapproach.springioc.service; import com.javasampleapproach.springioc.bean.CustomerPackage; public class CustomerService { CustomerPackage customerPackage; //setter injection public void setCustomerPackage(CustomerPackage customerPackage) { this.customerPackage = customerPackage; } public String callSupport() { return customerPackage.support(); } } |
4. Create Spring Bean Configuration File
Under src/main/resources, create bean.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="basicPackage" class="com.javasampleapproach.springioc.bean.BasicPackage"></bean> <bean id="businessPackage" class="com.javasampleapproach.springioc.bean.BusinessPackage"></bean> <bean id="customerService" class="com.javasampleapproach.springioc.service.CustomerService"> <property name="customerPackage"> <ref bean="basicPackage" /> </property> </bean> </beans> |
5. Add commands to SpringBootApplication Class
Open SpringIoCApplication.java, change the content inside:
package com.javasampleapproach.springioc; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.support.ClassPathXmlApplicationContext; //import org.springframework.context.support.FileSystemXmlApplicationContext; import com.javasampleapproach.springioc.service.CustomerService; @SpringBootApplication public class SpringIoCApplication { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); // FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("E:/STS/WorkPlace/SpringIoC/src/main/resources/bean.xml"); CustomerService service = context.getBean(CustomerService.class); System.out.println(service.callSupport()); context.close(); } } |
6. Run Spring Boot Application & Enjoy Result
– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results in Console Screen:
Support Basic Customers |
IV. Source Code
Last updated on September 23, 2018.