Spring – IoC


This Blog covers the Spring Framework implementation of the Inversion of Control (IoC) principle.

From Spring official document, IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.

The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes or a mechanism such as the Service Locator pattern.

Take it short, based on my understand what we can do using IoC is that we could save our time on create new objects/instances and ask the bean factory do everything when we need.

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container.

In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality.

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.


Normal way to create a new object in Java:

User cur = new User();

In Spring Framework:

// 1. We load the spring configuration (.xml)
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

// 2. Gain objects from configuration
User user = context.getBean("user", User.class);


Process of IoC

  1. .xml Configuration file

    <bean id = "dao" class = "spring.dao.user"></bean>
  2. Create factory class for service class and dao class

    class UserFactory{
    public static UserDao getDao(){
        String classValue = CLASS.VALUE // from .xml parse, step 1
        Class clz = Class.forName(classValue); // create obj by reflection
        return (UserDao)clz.newInstance();


  1. BeanFactory

    Inner Interface for Spring, normally not used for develop.

    It won’t ceate obect when load configuration file.

  2. ApplicationContext

    Superset of Beanfactory, normally used for develop

    It will create object when load configuration file.

Leave a Reply