Home » Spring » Dependency Injection (DI) with Spring

Dependency Injection (DI) with Spring

Dependency Injection is the basic design principle on which the core spring framework is built.Dependency Injection helps you to avoid writing unnecessary creation and lookup code in your application.If a class A reqires a class B's functionalities,we don't have to write a number of line of code to create an instance of class B to use its methods.Spring framework uses Dependency injection and injects the object of B into the Class A during runtime.Spring uses inversion of control to satisfy dependencies between objects.

A class A has a dependency to class B if class uses class B as a variable.

If dependency injection is used then the class B is given to class A dependency via

the constructor of the class A - this is then called construction injection

a setter - this is then called setter injection

Below image shows a simple diagram that uses dependency injection where different beans are injected into the Object XXX.

Spring Dependency Injection

Following are some of the scenarios where dependency injection can be used in enterprise application.

  • The Dao Classes use the Data Sources which can be injected using Spring.
  • The Service classes may need to consume EJBs.
  • The Objects may have to load the message resources to use the messages..

Advantages of Dependency Injection

  • Loosely couple architecture.
  • Separation of responsibility
  • Configuration and code is separate.
  • Using configuration, a different implementation can be supplied without changing the dependent code.
  • Testing can be performed using mock objects.

Dependency Injection Types

In Spring framework, Dependency Injection (DI) is used to satisfy the dependencies between objects. It exits in two major types :

  • Setter Injection
  • Constructor Injection

Setter Injection

In this type of injection, the spring container uses setter method in the dependent (our) class for injecting its dependencies (primitive values..Or any).Spring container knows whether to perform setter or constructor injection by reading the information from an external file called spring configuration file

In case of setter injection, the class must contain a setter method to get dependencies other wise spring container doesn’t inject the dependencies to dependent object.

Constructor Injection

Constructor injection is second approach to implement Dependency injection in Spring. Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

As mentioned above there are two ways in Spring for Dependency injection, constructor and setter injection. Configuration for dependency are done using Spring-configuration XML or using annotations.After release of Spring 2.5, it is possible to configure the dependency injection via annotations.Annotations are mostly preferred for their ease of use. Spring manages these objects using BeanFactory. When an instance is created, by default they are singletons and this can be changed using the configuration.

Spring Dependency Injection using Annotations

Create an interface Book.java , Using this interface dependency injection is done.

Book.java

package com.javawebtutor.spring.ioc;

public interface Book {
public String writer() ;
}

Create a class TechBook.java which implements Book interface.TechBook.java – Implements the Book interface and therefore this interface can be used for injection.

TechBook.java

package com.javawebtutor.spring.ioc;
public class TechBook implements Book {
public String writer() {
return "javawebtutor";
}
}

Create class ArtsBook.java which should implement Book interface. This is the selected implementation for injection because @Service annotation is mentioned in this class. @Service tells the spring IOC container to use this class.

ArtsBook.java

package com.javawebtutor.spring.ioc;

import org.springframework.stereotype.Service;

@Service
public class ArtsBook implements Book {

public String writer() {
return "Dev";
}
}

Create class Library.java and add following code into this.

Library.java

package com.javawebtutor.spring.ioc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Library {
private Book book;
@Autowired
public void setBook(Book book) {
this.book = book;
}
public void getAuthorName() {
System.out.println(book.writer());
}
}

spring-context.xml

spring-context.xml – gives the configuration information to the spring container. In this we describe that we are using annotation based configurations.spring-context.xml file is mentioned below.

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<!-- Dependency Injection with annotations -->
	<context:component-scan base-package="com.javawebtutor.spring.ioc" />
		<mvc:annotation-driven />
</beans>

Test.java – loads the spring configuration and gets the bean. Spring IOC container based on annotations, provides the ArtsBook.java instance at runtime.

package com.javawebtutor.spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDI {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext("META-INF/spring-context.xml");
		BeanFactory factory = appContext;
		Library library = (Library) factory.getBean("book");
        library.getAuthorName();
	}
}

Spring Dependency Injection using XML

To make the container aware of the dependent class and the dependencies we can set up the configuration file like this.We can remove all the annotations in the java classes. In spring configuration we declare the chosen implementation to supply at runtime.

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<!-- Dependency Injection without annotations -->
	<bean id="book" class="com.javawebtutor.spring.ioc.Book" />
	<bean id="library" class="com.javawebtutor.spring.ioc.Library">
		<property name="book" ref="book" />
	</bean>
</beans>

Previous Next Article
comments powered by Disqus