Thursday, 4 January 2018

What Is an IoC Container? Understanding BeanFactory and ApplicationContext in Spring

         The Spring IoC (Inversion of Control) Container is the core of the Spring Framework. It is responsible for creating objects, wiring their dependencies together, configuring them, and managing their complete lifecycle—from creation to destruction.

The Spring container uses Dependency Injection (DI) to manage the components that make up an application.

The objects created and managed by the Spring container are known as Spring beans.

A Spring bean is simply an object that is created, configured, and managed by the Spring IoC container. It is not a special type of object. Any Java POJO (Plain Old Java Object) can become a Spring bean if it is configured to be initialized by the Spring container using the appropriate configuration metadata.

The Spring container determines which objects to instantiate, configure, and assemble by reading the configuration metadata provided by the application. This metadata can be specified using XML configuration, Java annotations, or Java-based configuration.

The following diagram provides a high-level overview of how the Spring IoC container works.


IOC Container in Spring


There are two types of Spring IOC Containers,
  •  BeanFactory Container
  •  ApplicationContext Container

BeanFactory Container:

             The BeanFactory is the root interface of the Spring IoC container. It is defined in the org.springframework.beans.factory package and provides the basic functionality for managing Spring beans.

BeanFactory is responsible for instantiating, configuring, and assembling application objects, as well as managing their dependencies. It uses the configuration metadata provided by the application to create and initialize Spring beans.

One of the commonly used implementations of BeanFactory was XmlBeanFactory, which allowed beans and their dependencies to be defined in an XML configuration file. XmlBeanFactory reads the XML configuration metadata and creates fully configured Spring beans.

Note: XmlBeanFactory has been deprecated since Spring 3.1 and removed in later versions of Spring. It is recommended to use ApplicationContext instead.

The following example demonstrates a simple Hello World application using XmlBeanFactory.

Beans.xml,

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<bean id="helloWorld" class="com.src.sample.HelloWorld"> 
    <property name="message" value="Hello World!"/> 
</bean>

       The above XML code shows the contents of the bean xml configuration.  It has a single bean configured that has a single property by the name message.  A default value is set for the property.

Next, HelloWorld.java


 package com.src.sample; 
 public class HelloWorld { 
 
      private String message; 
      
      public void setMessage(String message){ 
           this.message = message; 
      } 
      public void getMessage(){ 
           System.out.println(message);
      } 
 }

The main class i.e HelloWorldMain.java to call the bean.

package com.src.sample; 
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory; 
import org.springframework.core.io.ClassPathResource; 

public class HelloWorldMain {     
     public static void main(String[] args) {           
           XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml")); 
           HelloWorld obj = (HelloWorld) factory.getBean("helloWorld"); 
           obj.getMessage(); 
     } 
}

         In the above program, XmlBeanFactory loads the XML configuration file from the classpath. It reads the configuration metadata to create, configure, and manage the Spring beans. When a bean is requested, the container returns the fully initialized bean.

Finally, the getMessage() method is invoked on the bean to display the desired output.

BeanFactory is lightweight and was traditionally preferred in environments with limited resources, such as mobile devices or applets. However, in modern Spring applications, ApplicationContext is the preferred choice because it provides additional enterprise-level features.

BeanFactory is the parent interface of ApplicationContext and offers only the basic IoC container functionality. ApplicationContext extends BeanFactory and provides additional features such as event propagation, internationalization (i18n), automatic BeanPostProcessor and BeanFactoryPostProcessor registration, annotation-based configuration, and easier integration with Spring AOP.


ApplicationContext Container:--

        The ApplicationContext is defined by the org.springframework.context.ApplicationContext interface. Like BeanFactory, it can load bean definitions, create and configure beans, wire their dependencies, and provide fully initialized beans when requested.

In addition to the basic features provided by BeanFactory, ApplicationContext offers several enterprise-level capabilities, such as support for internationalization (i18n), event publishing, annotation-based configuration, automatic registration of BeanPostProcessor and BeanFactoryPostProcessor, integration with Spring AOP, declarative transaction management, and loading resources from various sources.

The following are some of the most commonly used implementations of ApplicationContext:


  • FileSystemXmlApplicationContext       
        This implementation loads the definitions of the beans from an XML file. It is required to provide the full path of the XML bean configuration file to the constructor.


  • ClassPathXmlApplicationContext
      This container loads the definitions of the beans from an XML file.  However, it is not required to provide the full path of the XML file. It does require you to set CLASSPATH properly because this container will look for bean configuration XML file in the specified CLASSPATH.

  • XmlWebApplicationContext
This container loads the XML file with definitions of all beans from within a web application.


Following is the one sample example of FileSystemXmlApplicationContext,

HelloWorldMain.java,

package com.src.sample; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class HelloWorldMain {   
     public static void main(String[] args) { 
           ApplicationContext  context = new FileSystemXmlApplicationContext ("C:/Program/workspace/SpringExample/src/Beans.xml"); 
           HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); 
           obj.getMessage(); 
     } 
}


Difference between BeanFactory and the ApplicationContext:--

        The org.springframework.beans.factory.BeanFactory and org.springframework.context.ApplicationContext interfaces act as Spring IoC containers. The ApplicationContext interface extends the BeanFactory interface and provides all of its functionality along with several additional features.

ApplicationContext offers enterprise-level capabilities such as seamless integration with Spring AOP, message resource handling for internationalization (i18n), event publishing, annotation-based configuration, and application-specific contexts (such as WebApplicationContext) for web applications.

For these reasons, ApplicationContext is recommended over BeanFactory for almost all Spring applications.

No comments:

Post a Comment