Spring Dependency Injection

Spring Overview

Spring is an open source framework created to address the complexities of enterprise application development.

The fundamental functionality provided by the Spring Container is dependency injection. Spring provides a light-weight container, e.g. the Spring core container, for dependency injection (DI).

This container allows us to inject required objects into other objects. This results in a design in which the Java classes are not hard-coupled. The injection in spring is either done via setter injection or construction injection.

The Spring core container:

  • handles the configuration, generally based on annotations or on an XML file (XMLBeanFactory)
  • manages the selected Java classes via the BeanFactory

IOC(Inversion of Control)

The IOC or Inversion of Control is the core feature of the Spring Framework. Developers use the IOC container to manage the beans and its dependency in the application. Thus, it simplifies the implementation of business logic in the application. The IOC is very important and it’s very necessary to fully understand it.

What is IOC?

The Inversion of Control is the process by which application defines the dependency and these dependencies are then satisfied in runtime by the Spring Framework. The IoC is also known as Dependency Injection (DI).

I the application dependencies are satisfied through:

  1. Constructor Injection
    Here the IOC container injects the dependency through the constructor.
  2. Setter Injection
    The setter injection is done through the setters (setter method).
  3. Interface Injection
    The spring does not provide direct Interface Injection functionality.

What are the benefits of IOC (Dependency Injection)?

Benefits of IOC (Dependency Injection) are as follows:

  • Java components / classes should be as independent as possible of other Java classes. This increases the possibility to reuse these classes and to test them independently of other classes (Unit Testing). To decouple Java components from other Java components the dependency to a certain other class should get injected into them rather than the class itself creates / finds this object.
  • Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
  • Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
  • Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
  • IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

Three Fundamental DI Styles in Spring

 

1)      XML Based

  • <bean/>
  • <namespace.*/>

2)      Annotations Based

  • @Component
  • @Autowired
  • @Resource
  • @Service
  • @Repository
  • @Transactional
  • @Resource

3)      Java Based

  • @Configurable classes
  • @Bean Method

Before going through the following examples  i.e

  • XML Bases Spring Dependency Injection
  • Annotataion Based Spring Dependency Injection

You need  the following  files

First, create a Maven Java  Project for the following examples:

1)      Pom.xml :-    Add dependencies of spring in pom.xml .

2)      ApplicationContext.xml  (add this in resource folder)

3)      UserService.java (Interface)

4)      UserServiceImpl.java (class)

5)      UserDao.java (Interface)

6)      UserDaoImpl.java (class)

XML Based Spring Dependency Injection

Constructor-based dependency injection

In the constructor-based dependency injection, one bean definition is injected into another. For this you use the constructor-arg.

In this example,create maven project with packaging jar. You will see a UserDao  is injected to UserServiceImpl. The first bean definition is the userDaoImpl with the id userDao. It is injected into the another bean class userServiceImpl with the id as userService. by using constructor with ref attribute.

(Download pom.xml  file)

POM.XML

               User.java

 

package net.paxcel.springdependancyinjectiondusingxml.bean;

public class User {

                private Long userId;

                private String name;

                private String city;

                private String state;

                public Long getUserId() {

                                return userId;

                }

                public void setUserId(Long userId) {

                                this.userId = userId;

                }

                public String getName() {

                                return name;

                }

                public void setName(String name) {

                                this.name = name;

                }

                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;

                }

}

UserDao.java

 

package net.paxcel.springdependancyinjectiondusingxml.dao;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

public interface UserDao {

                public User getUserdetail();

}

UserDaoImpl.java

 

package net.paxcel.springdependancyinjectiondusingxml.daoImpl;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

import net.paxcel.springdependancyinjectiondusingxml.dao.UserDao;

public class UserDaoImpl  implements UserDao {

            public User getUserdetail()

                  {

                               User user=new User();

                                user.setUserId(1l);

                                user.setName(“Priya”);

                                user.setCity(“Bathinda”);

                                user.setState(“Punjab”);

                               return user;

                     }

UserService.java

 package net.paxcel.springdependancyinjectiondusingxml.service;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

public interface UserService {

                public User getUserDetail();

}

UserServiceImpl.java

package net.paxcel.springdependancyinjectiondusingxml.serviceImpl;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

import net.paxcel.springdependancyinjectiondusingxml.dao.UserDao;

import net.paxcel.springdependancyinjectiondusingxml.service.UserService;

public class UserServiceImpl implements UserService{

                private UserDao userDao;

                public UserServiceImpl (UserDao userDao)

                {

                                this.userDao=userDao;

                }

                public User getUserDetail() {

                                return userDao.getUserdetail();

                }

SpringDIMain.java

package net.paxcel.springdependancyinjectiondusingxml.main;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

import net.paxcel.springdependancyinjectiondusingxml.service.UserService;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDIMain {

                public static void main(String[] args) {

                  ApplicationContext context = newClassPathXmlApplicationContext

                                                           (“applicationContext.xml”);

                                BeanFactory beanFactory = context;

                                UserService userService = (UserService) beanFactory

                                                                .getBean(“userService”);

                                User user = userService.getUserDetail();

                                System.out.println(“User Id :” + user.getUserId());

                                System.out.println(“User Name :” + user.getName());

                                System.out.println(“City :” + user.getCity());

                                System.out.println(“State :” + user.getState());

                }

}

ApplicationContext.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”

                xmlns:tx=“http://www.springframework.org/schema/tx” xmlns:sec=“http://www.springframework.org/schema/security”

                xmlns:aop=“http://www.springframework.org/schema/aop” xmlns:jdbc=“http://www.springframework.org/schema/jdbc”

     xsi:schemaLocation=“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

                       http://www.springframework.org/schema/tx

                       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>

                <context:component-scan

                            base-package=“net.paxcel.springdependancyinjectiondusingxml” />

                <bean id=“userService”

                                 class=“net.paxcel.springdependancyinjectiondusingxml.serviceImpl.UserServiceImpl”>

                                <constructor-arg ref=“userDao” />

                </bean>

                <bean id=“userDao”

              class=“net.paxcel.springdependancyinjectiondusingxml.daoImpl.UserDaoImpl”>

                </bean>

</beans>

Setter Injection

Here in this example you will see another different type of injection known as setter injection which is the preferred method dependency injection in Spring. The convention of writing the setter method is that start the method name with set and add the method name start with capital character like setMessage or setName.

For this example Create maven Project and the following files and classes.

User.java

package net.paxcel.springdependancyinjectiondusingxml.bean;

public class User {

                private Long userId;

                private String name;

                private String city;

                private String state;

                public Long getUserId() {

                                return userId;

                }

                public void setUserId(Long userId) {

                                this.userId = userId;

                }

                public String getName() {

                                return name;

                }

                public void setName(String name) {

                                this.name = name;

                }

                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;

                }}

UserDao.java

 

package net.paxcel.springdependancyinjectiondusingxml.dao;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

public interface UserDao {

                public User getUserdetail();

 }

UserDaoImpl.java

package net.paxcel.springdependancyinjectiondusingxml.daoImpl;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

import net.paxcel.springdependancyinjectiondusingxml.dao.UserDao;

public class UserDaoImpl implements UserDao{

          public User getUserdetail()

                 {

                                User user=new User();

                                 user.setUserId(1l);

                                user.setName(“Priya”);

                                user.setCity(“Bathinda”);

                                                user.setState(“Punjab”);

                                return user;

                }

}

UserService.java

 

package net.paxcel.springdependancyinjectiondusingxml.service;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

public interface UserService {

                public User getUserDetail();

}

UserServiceImpl.java

 package net.paxcel.springdependancyinjectiondusingxml.serviceImpl;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

import net.paxcel.springdependancyinjectiondusingxml.dao.UserDao;

import net.paxcel.springdependancyinjectiondusingxml.service.UserService;

public class UserServiceImpl implements UserService{

                private UserDao userDao;

             public void setUserDao(UserDao userDao {

                       this.userDao=userDao;

              }

           Public UserDao getUserDao(){

                      return userDao;

              }

           public User getUserDetail() {

                    return userDao.getUserdetail();

            }

}

SpringDIMain.java

 package net.paxcel.springdependancyinjectiondusingxml.main;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

import net.paxcel.springdependancyinjectiondusingxml.service.UserService;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDIMain {

                public static void main(String[] args) {

                                ApplicationContext context = new ClassPathXmlApplicationContext(

                                                                “applicationContext.xml”);

                                BeanFactory beanFactory = context;

                                UserService userService = (UserService) beanFactory

                                                                .getBean(“userService”);

                                User user = userService.getUserDetail();

                                System.out.println(“User Id :” + user.getUserId());

                                System.out.println(“User Name :” + user.getName());

                                System.out.println(“City :” + user.getCity());

                                System.out.println(“State :” + user.getState());

                }

}

ApplicationContext.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”

                xmlns:tx=“http://www.springframework.org/schema/tx” xmlns:sec=“http://www.springframework.org/schema/security”

                xmlns:aop=“http://www.springframework.org/schema/aop” xmlns:jdbc=“http://www.springframework.org/schema/jdbc”

                xsi:schemaLocation=“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

                                                                http://www.springframework.org/schema/tx

                                                                                                http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>

                <context:component-scan base-package=“net.paxcel.springdependancyinjectiondusingxml” />

                <bean id=“userService”

                                class=“net.paxcel.springdependancyinjectiondusingxml.serviceImpl.UserServiceImpl”>

                                <property name=”userDao”  ref=“userDao” />

                </bean>

                <bean id=“userDao”

                                class=“net.paxcel.springdependancyinjectiondusingxml.daoImpl.UserDaoImpl”>

                </bean>

</beans>

Setter or Constructor Injection?

There are no hard rules set by the Spring framework. Just use whatever type of DI that suit your project needs. However, due to the simplicity of the setter injection, it is always selected for most of the scenarios.

Annotation-Driven Dependency Injection in

@Transactional            for demarcating and configuring transaction definitions

@Repository                    for indicating a class that is operating as a repository (a.k.a. Data Access

Object or DAO)

@Required                       for enforcing annotated bean properties are provided a value

@Autowired                  Marks a constructor, field, setter method or config method as to be autowired  by Spring’s dependency                                                  injection facilities. Only one constructor (at max) of any given bean   class may carry this annotation,                                                   indicating the constructor to autowire when used as a Spring   bean. Such a constructor does not  public.                                  Fields are injected right after construction of a bean, before any config methods are invoked. Such a config                                   field does not have to be public.

@Component

Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning

 @Service

annotation is used to declare it as service bean

User.java

package net.paxcel.sprinddependencyinjectionannotationsample.bean;

public class User {

                private Long userId;

                private String name;

                private String city;

                private String state;

                public Long getUserId() {

                                return userId;

                }

                public void setUserId(Long userId) {

                                this.userId = userId;

                }

                public String getName() {

                                return name;

                }

                public void setName(String name) {

                                this.name = name;

                }

                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;

                }

}

UserDao.java

package net.paxcel.sprinddependencyinjectionannotationsample.dao;

import net.paxcel.sprinddependencyinjectionannotationsample.bean.User;

public interface UserDao {

                public User getUserdetail();

}

UserDaoImpl.java

package net.paxcel.sprinddependencyinjectionannotationsample.daoImpl;

import net.paxcel.sprinddependencyinjectionannotationsample.bean.User;

import net.paxcel.sprinddependencyinjectionannotationsample.dao.UserDao;

import org.springframework.stereotype.Repository;

@Repository(“userDao”)

public class UserDaoImpl implements UserDao{

                public User getUserdetail() {

                                User user=new User();

                                                user.setUserId(1l);

                                                user.setName(“Priya”);

                                                user.setCity(“Bathinda”);

                                                user.setState(“Punjab”);

                                return user;

                }

}

UserService.java

package net.paxcel.sprinddependencyinjectionannotationsample.service;

import net.paxcel.sprinddependencyinjectionannotationsample.bean.User;

public interface UserService {

                public User getUserDetail();

}

UserServiceImpl.java

package net.paxcel.sprinddependencyinjectionannotationsample.serviceImpl;

import org.springframework.stereotype.Service;

import net.paxcel.sprinddependencyinjectionannotationsample.bean.User;

import net.paxcel.sprinddependencyinjectionannotationsample.dao.UserDao;

import net.paxcel.sprinddependencyinjectionannotationsample.service.UserService;

import javax.annotation.Resource;

@Service(“userService”)

public class UserServiceImpl implements UserService {

                @Resource

                private UserDao userDao;

                public User getUserDetail() {

                                return userDao.getUserdetail();

                }

}

SpringDIMain.java

package net.paxcel.sprinddependencyinjectionannotationsample.serviceImpl;

import net.paxcel.springdependancyinjectiondusingxml.bean.User;

import net.paxcel.springdependancyinjectiondusingxml.service.UserService;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDIMain {

                public static void main(String[] args) {

                                ApplicationContext context = new ClassPathXmlApplicationContext(

                                                                “applicationContext.xml”);

                                BeanFactory beanFactory = context;

                                UserService userService = (UserService) beanFactory

                                                                .getBean(“userService”);

                                User user = userService.getUserDetail();

                                System.out.println(“User Id :” + user.getUserId());

                                System.out.println(“User Name :” + user.getName());

                                System.out.println(“City :” + user.getCity());

                                System.out.println(“State :” + user.getState());

                }

}

applicationContext.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”

                xmlns:tx=“http://www.springframework.org/schema/tx” xmlns:sec=“http://www.springframework.org/schema/security”

                xmlns:aop=“http://www.springframework.org/schema/aop” xmlns:jdbc=“http://www.springframework.org/schema/jdbc”

                xsi:schemaLocation=“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

                                                                http://www.springframework.org/schema/tx

                                                                                                http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>

                <context:component-scan

                                base-package=“net.paxcel.sprinddependencyinjectionannotationsample”/>

</beans>

References :

3 thoughts on “Spring Dependency Injection

  1. Ioc is a very generic term, that’s why people find it confusing. It is all about inverting main control of yout program to the framework. DI is the way to implement Ioc. But many times terms are used interchangeably, yet there are differences.

Leave a Reply

Your email address will not be published. Required fields are marked *


− one = 0

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>