Basic Concept
Spring Setup
Spring Boot
Usage of Inversion of Control (IOC) in Spring Framework
Before to proceed to IOC Container we will first understand the Inversion of Control (IOC). It is the software engineering principle by following which, the control of object creation is passed to framework or container instead of developer. It is commonly followed in Object Oriented Programming.
The advantages of Inversion of Control (IOC)
By using Inversion of Control (IOC) it becomes easy to decouple the execution of task from it's implementation and greater modularity of program. It also becomes easy to switch between different implementation and testing.
IoC Container in Spring Framework
It is the most important component in spring framework also called backbone of spring. It is responsible for assembling, instantiating and configuring the objects. The IoC Container collects information from XML file and works accordingly.
There are two types of IoC containers.
- BeanFactory
- ApplicationContext
BeanFactory in Spring Framework and it's usage
BeanFactory is an interface and XmlBeanFactory class is it's implementation. To use the BeanFactory, we need to create the instance of XmlBeanFactory class as shown below.
Resource resource=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(resource);
The constructor of XmlBeanFactory class takes Resource object as an argument and we need to provide resource object to create the object of BeanFactory.
ApplicationContext in Spring Framework and it's usage
ApplicationContext is an interface and ClassPathXmlApplicationContext class is it's implementation. To use ApplicationContext We need to instantiate ClassPathXmlApplicationContext class as shown below.
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
The constructor of ClassPathXmlApplicationContext class takes string as an argument and we need to provide the name of the xml file to create the instance of ApplicationContext.
Difference between BeanFactory and the ApplicationContext
The org.springframework.beans.factory.BeanFactory and the org.springframework.context.ApplicationContext both the interfaces act as the IoC containers. The ApplicationContext interface is built on top of the BeanFactory interface and it provides some extra functionality than BeanFactory such as simple integration with Spring's AOP and message resource handling event propagation. It is better to use ApplicationContext than BeanFactory.
Difference between Inversion of Control and IoC Container
Inversion of Control is the design principle of software engineering and Ioc Container is the core component of Spring framework responsible for assembling, instantiating and configuring the objects.
Aamir Shayan
Software Engineer