English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring IoC Container

The IoC container is responsible for instantiating, configuring, and assembling objects. The IoC container gets information from XML files and works accordingly. The main tasks performed by the IoC container are:

Instantiate application classes Configure objects Assemble object dependencies

There are two types of IoC containers. They are:

BeanFactory ApplicationContext

Difference between BeanFactory and ApplicationContext

org.springframework.beans.factory. BeanFactory and org.springframework.context. ApplicationContext Interfaces act as IoC containers. The ApplicationContext interface is built on top of the BeanFactory interface. It adds some additional features compared to BeanFactory, such as simple integration with Spring's AOP, message resource handling (used for I18N),Event propagation, the specific application layer context of Web applications (such as WebApplicationContext). Therefore, using ApplicationContext is better than using BeanFactory.

Using BeanFactory

XmlBeanFactory is an implementation class of the BeanFactory interface. To use BeanFactory, we need to create an instance of the XmlBeanFactory class, as shown below:

Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);

The constructor of the XmlBeanFactory class accepts a Resource object, so we need to pass this resource object to create the BeanFactory object.


Using ApplicationContext

The ClassPathXmlApplicationContext class is an implementation class of the ApplicationContext interface. We need to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext, as shown below:

ApplicationContext context = 
    new ClassPathXmlApplicationContext("applicationContext.xml");

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