Spring – Dependency Injection using Inversion of Control

What is Dependency Injection ?

“Dependency Injection”, the word itself clarifies that we are trying to Inject the dependency between the Parent Classes and the calling Class.  But how spring provides it as a Feature and how it is different from previous implementation, is what we need to understand.

Java Programming Concept is all about the object oriented programming, class instantiation, encapsulation and polymorphism. Spring also executes on the same implementation but it provides a simple approach where it allows to make a class independent from its dependencies. To achieve this and make classes loosely decoupled, Spring separates the class creation and class usage (invoked by another dependent class).

Dependency Injection is implemented by using the technique termed as ‘Inversion of Control’. First, we need to understand how IoC Container uses the Spring Framework.

How IoC Container uses the Spring Framework ?

Core Packages: The org.springframework.beans and org.springframework.context packages are the Core Component for Spring Framework IoC Container execution.

Bean Factory: The advanced configuration capability comes from the usage of the BeanFactory. It acts as a Factory class and provides Bean Definition for the multiple application beans and create instances of the bean whenever is requested by the client call.   

Application Context: The ApplicationContext provides access to the bean methods, loading file resources, publishing events, message resourcing supporting internationalization, parent context inheritance for easy integration.

Application Context implementatio n

The ApplicationContext provides the below given commonly used implementation:

  1. ClassPathXmlApplicationContext:  loads the context definition for the application by retrieving it from the XML File.
<strong>ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");</strong>
  • FileSystemXmlApplicationContext: loads the context definition for the application by retrieving it from the XML File placed in the File System.
<strong>ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");</strong>
  • XmlWebApplicationContext: loads the context definition for the application by retrieving it from the XML File within the web application.
<strong>&nbsp;ApplicationContext context = new XmlWebApplicationContext ("bean.xml");</strong>

Below given are the possible ways for implementing the Inversion of Control (Spring IoC Container):

  1. With the usage of Factory Pattern
  2. With the usage of Service Locator Pattern
  3. With the Inclusion of Dependency Injection through
  • The Constructor Injection
  • The Setter Injection
  • The Interface Injection

Dependency Injection – using Constructor Injection


Spring – Bean Scope

The most important component of the Spring Framework is the Spring Core Container which creates the objects, wires them together, manages the configuration and overall object life cycle from creation of the object till its destruction. These objects are called Beans which are created from the configuration metadata provided to the container. Configuration Metadata provides the information to the container with regard to bean

  1. Managing Bean Creation Process

2. Managing life cycle of the bean

3. Managing dependencies of the bean

Configuration Metadata Properties

Below are the commonly used properties for the configuration metadata in spring bean scope.

Name – specifies bean identifier

Class –  specifies the bean class for which bean is to be created

Constructor –arg – specifies the dependency injection  

Scope – specifies the scope of the object created from the bean definition

Properties – specifies properties for the dependency injection  

Auto wiring Mode – specifies the dependency injection  

lazy-initialization mode – specifies the lazy initiation of the bean instance. That is, bean instance is created when it is requested and not at the start-up of the application

initialization method – A callback to be called just after all necessary properties on the bean have been set by the container

destruction method – A callback to be used when the container containing the bean is destroyed

Configuration Metadata Methodologies

Configuration Metadata can be provided by using the below given methodologies

  • XML based configuration file.
  • Annotation-based configuration
  • Java-based configuration

Sample XML Configuration

<?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-3.0.xsd">

   <!-- A simple bean definition -->
   <bean id = "..." class = "createCustomer">
    </bean>

   <!-- A bean definition with lazy init set on -->
   <bean id = "..." class = "..." lazy-init = "true">
    </bean>

   <!-- A bean definition with initialization method -->
   <bean id = "..." class = "..." init-method = "Initiate-customer-process">
   </bean>

   <!-- A bean definition with destruction method -->
   <bean id = "..." class = "..." destroy-method = "destruct-customer-process">
   </bean>

      
</beans>

Spring supported Bean Scope

The Spring Framework supports the below given bean scopes.

Singleton Scope:  With the use of singleton scope, Spring IOC Container creates only 1 bean instance of the object defined by the bean definition.

The below bean configuration file does not include the scope specified and thus makes it as a singleton instance.

spring-singleton-bean-scope

Another bean configuration with the usage of scope as “singleton”

spring-singleton-bean-scope

Prototype Bean Scope

With the use of prototype scope, Spring IOC Container creates a new bean instance every time the bean is requested.

Spring Prototype Bean Scope

Bean Scope Annotation

Spring also provides annotation to define the bean scope as an alternative to the XML based configuration. The annotation based bean depends on bytecode metadata for wiring up components instead of angle-bracket declarations and allows developers to write the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

The RequiredAnnotationBeanPostProcessor, using a BeanPostProcessor in conjunction with annotations is a common means of extending the Spring IOC container.

Spring 2.5 also added support for JSR-250 annotations, such as @PostConstruct and @PreDestroy.

Spring 3.0 added support for JSR-330 (Dependency Injection for Java) annotations contained in the javax.inject package such as @Inject and @Named

Spring Bean Scope Annotation


Spring – IOC Container

The most important component of the Spring Framework is the Spring Core Container which creates the objects, wires them together, manages the configuration and overall object life cycle from creation of the object till its destruction. We can also say that The IoC container is responsible to instantiate, configure and assemble the objects. The Spring container uses Dependency Injection (DI) to manage the components that make up an application. The below diagram depicts that the application classes are combined with the configuration metadata which creates and initializes the ApplicationContext and provides a fully customized application, ready for use

Spring IOC Container

Spring Containers

Spring provides two types of containers.

  • Spring BeanFactory container
  • Spring ApplicationContext container

Spring Bean Factory Container

Spring Bean Factory Container uses the org. springframework. beans. factory. BeanFactory interface and provides the support for Dependency Injection (DI) by registering different beans and their dependencies. The XmlBeanFactory is the implementation class for the BeanFactory interface. The constructor of XmlBeanFactory class receives the Resource object so we need to pass the resource object to create the object of BeanFactory.

Resource resource=new ClassPathResource(“applicationContext.xml”);  

BeanFactory factory=new XmlBeanFactory(resource); 

Spring ApplicationContext Container

The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface. Use the below given syntax to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext as given below:

ApplicationContext context =   new ClassPathXmlApplicationContext(“applicationContext.xml”);  

spring- applicationContext container

The constructor of ClassPathXmlApplicationContext class receives string, so we can pass the name of the xml file to create the instance of ApplicationContext.

Below given are the possible ways for implementing the Inversion of Control (Spring IoC Container):

  1. With the usage of Factory Pattern
  2. With the usage of Service Locator Pattern
  3. With the Inclusion of Dependency Injection through
  • The Constructor Injection
  • The Setter Injection
  • The Interface Injection




Spring Architecture

Spring Framework is one of the most commonly used Java EE open source framework, initially written by Rod Johnson and was released under the Apache 2.0 license in June 2003. The Spring Framework provides a comprehensive and infrastructural support providing focus on building application-level business logic and reduces the ties on specific deployment environments.

The tutorial is designed on the Spring Version Spring 5 for the student and Java developers or anyone who wants to learn spring framework for implementing the learned skills to enhance their career path.

What is Spring Framework ?

Spring framework is a modular architecture consisting of several modules (grouped as Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, Messaging, and Test) which allows developers to build enterprise web applications with the ease. Developers can select the modules required for building the components of web applications without having to bring in all the modules and thus makes it lightweight and flexible as developers are using only the required set of modules and not the complete bundle . The below given is the Spring Architecture Diagram highlighting the main modules it provides. Let’s discuss about the architecture components to understand how they can be used in the application development.

Spring Architecture

Core Container in Spring

The Spring Core Container consists of spring-core, spring-beans, spring-context, spring-context-support, and spring-expression (expression language) modules

  • The spring-core and spring-beans modules provides the fundamental parts of the framework, including the IoC (Inversion of Control) and Dependency Injection (DI) features.
  • The spring-beans module provides BeanFactory, which inherits the implementation of the factory pattern.
  • The spring-context module provides the mechanism to access objects in a framework-style manner, similar to a JNDI registry with the base foundation of spring-core and spring-beans modules. The Context module inherits spring-beans module to provide support for internationalization (resource bundles), event propagation, resource loading, and the transparent creation of contexts (Servlet Container) and also supports Java EE features such as EJB, JMX, and basic remoting. The ApplicationContext interface is the focal point of the Context module.
  • The spring-expression (SpEL) module provides a powerful expression language for querying and manipulating an object graph at runtime.

Data Access / Integration in Spring

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules. Let’s discuss about these components to understand how they can be used in the application development.

  • The spring-jdbc (JDBC) module provides a JDBC-abstraction layer that removes the need for tedious JDBC related coding and parsing of vendor specific error codes.
  • The spring-orm (ORM)module provides integration layers for popular object-relational mapping APIs, including Hibernate, JPA, JPA, Top Link, JDO and iBatis.
  • The spring-oxm (OXM) module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XML Beans, JiBX and XStream
  • The spring-jms (Java Messaging Service -JMS) module contains features for producing and consuming messages.
  • The spring-tx (Transaction) module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs

Web Layer in Spring

The Web layer consists of the Web (spring-web), Web-MVC(spring-webmvc), Web-Socket (spring-websocket) and Web Portlet (Web-Portlet) modules. Let’s discuss about these components to understand how they can be used in the application development.

  • The Web module provides basic web-oriented integration features such as HTTP Client for remoting support, multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.
  • The Web-MVC module contains Spring’s Model-View-Controller (MVC) and REST Services implementation for web applications.
  • The Web-Socket module provides support for WebSocket-based, two-way communication between the client and the server in web applications.
  • The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module

AOP , Aspects, Instrumentation in Spring

  • The spring-aop module provides an aspect-oriented programming implementation allows developers to define method interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.
  • The spring-aspects (Aspects) module provides integration with AspectJ, which is again a powerful and mature AOP framework
  • The spring-instrument (Instrumentation) module provides class instrumentation support and class loader implementations to be used in certain application servers. The spring-instrument-tomcat module contains Spring’s instrumentation agent for Tomcat

Messaging

The spring-messaging (Messaging) module provides key abstractions such as MessageMessageChannelMessageHandler and provides support for STOMP as the Web Socket sub-protocol to use in applications. It also provides the set of annotations for mapping messages to methods, similar to the Spring MVC annotation based programming model

Test module in Spring

  • The spring-test (Test) module supports the Unit testing and Integration Testing of Spring components with JUnit or