Recent Posts

Saturday, 8 June 2019

Spring IOC Containers

Spring IOC Containers
     The main intention of IOC Container is to read bean configurations from configuration file, creating Bean objects and Providing bean Objects to Spring applications.
There are two types of IOC Containers in SPring framework.
1. BeanFactory
2. ApplicationContext
1. BeanFactory 
☀ It is the fundamental or Base container provided by Spring Framework in order to manage bean objects.
☀ BeanFactory IOC container will provide basic functionalities to the spring framework by creating maintaining beans objects as per the beans configuration details which we provided in spring beans configuration file.
☀ To represent BeanFactory IOC Container, Spring framework has provided an interface in the form of "org.springframework.beans.factory.BeanFactory".
☀ For BeanFactory interface, Spring Framework has provided an implementation class in the form of org.springframework.beans.factory.xml.XmlBeanFactory.
☀ If we want to use BeanFactory IOC Container in Spring applications then we have to use the following steps.
  • Create Resource Object.
  • Create BeanFactory object
  • Get Bean and access Business Method.
1. Create Resource Object
☀ Resource is an object in Spring Framework, it able to represent all bean configuration details which we provided in beans configurations details.
☀ To represent Resource object, Spring Framework has provided a predefined interface in the form of "org.springframework.core.io.Resource"
☀ For Resource interface, Spring Framework has provided the following implementation classes.
org.springframework.core.io.ByteArrayResource: It able to represent all the beans configuration details which are available in the form of byte [].
org.springframework.core.io.FileSystemResource: It able to get all the beans configuration details which are available in the form of a file in our system hard disk.
org.springframework.core.io.ClassPathResource: It able to get all the beans configuration details which are existed at "classpath" environment variable referred locations.
org.springframework.core.io.InputStreamResource: It able to get all the beans configuration which are existed in the form of InputStream.
org.springframework.core.io.UrlResource: It able to get all the beans configuration details which are existed at a particular URL in the network.
org.springframework.web.context.support.ServletContextResource: It able to get all the beans configuration details which are existed in ServletContext. It will be used in spring web applications.
org.apringframework.web.portlet.context.PortletContextResource: It able to get all the beans configuration details which are existed in PortletContext. It will be used in spring web applications designed on the basis of portlets.
E.g
Resource res=new ClassPathResource("beans.xml");

2. Create BeanFactory Object 
     To create XmlBeanFactory class object we have to use the following constructor.
public XmlBeanFactory(Resource res)
E.g.
BeanFactory factory=new XmlBeanFactrory(res);

3. Get Bean object from BeanFactory and access business method     To get Bean object from BeanFactory we have to use the following method.
public Object getBean(String id_Name)
E.g.
Employee emp = (Employee) factory.getBean("employee");
Note: BeanFactory is deprecated in Spring3.x version.

E.g.
Bean Class
package com.ashok.spring.core.ioc.beanfactory.beans;

/**
 * 
 * @author Ashok Kumar
 *
 */
public class Employee {
   private String empName;
   private String empId;
   private String empAddress;
   private double salary;

   public String getEmpName() {
      return empName;
   }

   public void setEmpName(String empName) {
      this.empName = empName;
   }

   public String getEmpId() {
      return empId;
   }

   public void setEmpId(String empId) {
      this.empId = empId;
   }

   public String getEmpAddress() {
      return empAddress;
   }

   public void setEmpAddress(String empAddress) {
      this.empAddress = empAddress;
   }

   public double getSalary() {
      return salary;
   }

   public void setSalary(double salary) {
      this.salary = salary;
   }

   @Override
   public String toString() {
      return "Employee [empName=" + empName + ", empId=" + empId + ", empAddress=" + empAddress + ", salary=" + salary
            + "]";
   }
}
Config File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
   <bean id = "emp" class = "com.ashok.spring.core.ioc.beanfactory.beans.Employee">
      <property name = "empName" value = "Ashok Kumar"/>
      <property name = "empId" value = "Emp0087"/>
      <property name = "empAddress" value = "Bhimavaram"/>
      <property name = "salary" value = "47000"/>
   </bean>
</beans>
Client Application
package com.ashok.spring.core.ioc.beanfactory.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.ashok.spring.core.ioc.beanfactory.beans.Employee;

/**
 * 
 * @author Ashok Kumar
 *
 */
@SuppressWarnings("deprecation")
public class TestSpringApplication {
   public static void main(String[] args) {
      String configFile = "/com/ashok/spring/core/ioc/beanfactory/config/beans.xml";
      Resource resource = new ClassPathResource(configFile);
      BeanFactory factory = new XmlBeanFactory(resource);
      Employee emp = (Employee) factory.getBean("emp");
      System.out.println(emp);
   }
}
     In the above application, when we activate BeanFactory container then BeanFactory Container will be started and it will not create any Bean object immediately and it will perform the following actions.
1. It will take bean configuration file name and location from Resource object.
2. It will search for the respective bean configuration file at the specified location.
3. If the respective bean configuration file is available then Beanfactory container will load that xml file to the memory.
4. After XML file loading, BeanFactory Container will parse that xml file, that is, it will check all the tags in XML file are provided properly or not, all attributes are available properly or not.
5. After the XML file parsing, BeanFactory Container will read data from Beans configuration file and stores in Resource object.

     After getting BeanFactory Object, when we access getBean(-) method then BeanFactory will perform the following actions.
1. BeanFactory will search for the respective Bean configuration in Resource object on the basis of the provided identity.
2. If any bean configuration is identified in Resource object on the basis of the provided identity then BeanFactory container will take the respective bean class name and its location.
3. BeanFactory Container will search for the respective bean class at the specified location, if it is available then BeanFactory Container will load all the bean class bytecode to the memory.
4. BeanFactry Container will create Object for the loaded bean class and its dependent bean objects.
5. BeanFactory Container will store the generated bean object and its dependent objects in Container object in the form of Key-Value pairs, where keys must be the "id" attribute values which we specified in beans configuration file and values are Bean Objects.

2. ApplicationContext
     ApplicationContext IOC Container is an extension of BeanFactory IOC Container, it able to provide some advanced features like Internationalization, Event Handling etc. along with fundamental functionalities what BeanFactory is providing. In Spring, ApplicationContext IOC Container is represented in the form of the following predefined interface. "org.springframework.context.ApplicationContext".
     Spring Framework has provided ApplicationContext as a child interface to BeanFactory interface. Spring Framework has provided the following three implementation classes for ApplicationContext.
1. ClassPathXmlApplicationContext
     It able to get all the beans configuration details from configuration file which is existed in application class path.
2. FileSystemXmlApplicationContext
     It able to get all the beans configuration details from Configuration file which is existed at our system hard disk.
3. WebXmlApplicationContext
     It able to get all the beans configuration details from configuration file which is existed in web application.
E.g.
Bean Class
package com.ashok.spring.core.ioc.applicationcontext.beans;

/**
 * 
 * @author Ashok Kumar
 *
 */
public class Employee {
   private String empName;
   private String empId;
   private String empAddress;
   private double salary;

   public String getEmpName() {
      return empName;
   }

   public void setEmpName(String empName) {
      this.empName = empName;
   }

   public String getEmpId() {
      return empId;
   }

   public void setEmpId(String empId) {
      this.empId = empId;
   }

   public String getEmpAddress() {
      return empAddress;
   }

   public void setEmpAddress(String empAddress) {
      this.empAddress = empAddress;
   }

   public double getSalary() {
      return salary;
   }

   public void setSalary(double salary) {
      this.salary = salary;
   }

   @Override
   public String toString() {
      return "Employee [empName=" + empName + ", empId=" + empId + ", empAddress=" + empAddress + ", salary=" + salary
            + "]";
   }
}
Config File (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"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id = "emp" class = "com.ashok.spring.core.ioc.applicationcontext.beans.Employee">
      <property name = "empName" value = "Ashok Kumar"/>
      <property name = "empId" value = "Emp0087"/>
      <property name = "empAddress" value = "Bhimavaram"/>
      <property name = "salary" value = "50000"/>
   </bean>
</beans>
Client Application
package com.ashok.spring.core.ioc.applicationcontext.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ashok.spring.core.ioc.applicationcontext.beans.Employee;

/**
 * 
 * @author Ashok Kumar
 *
 */
public class TestSpringApplication {
   @SuppressWarnings("resource")
   public static void main(String[] args) {
      String configFile = "/com/ashok/spring/core/ioc/applicationcontext/config/applicationContext.xml";
      ApplicationContext context = new ClassPathXmlApplicationContext(configFile);
      Employee emp = (Employee) context.getBean("emp");
      System.out.println(emp);
   }
}
     In the above application, when we activate ApplicationContext container then ApplicationContext Container will perform the following actions.
1. It will take bean configuration file name and location from Container class constructor.
2. It will search for the respective bean configuration file at the specified location.
3. If the respective bean configuration file is available then ApplicationCntext container will load that xml file to the memory.
4. After XML file loading, ApplicationContext Container will parse that xml file, that is, it will check all the tags in XML file are provided properly or not, all attributes are available properly or not.
5. After the XML file parsing, ApplicationContext Container will read data from Beans configuration file.
6. If any bean configuration is identified in beans configuration file the ApplicationContext container will take beans classes and their locations.
7. ApplicationContext Container will search for the respective beans at the specified locations, if they are available then IOC Container will load all the bean classes bytecode to the memory.
8. ApplicationContext Container will create Objects for the loaded bean classes and their dependent bean objects.
9. ApplicationContext Container will store all the bean objects and their dependent objects in Container object in the form of Key-Value pairs, where keys must be the "id" attribute values which we specified in beans configuration file.
     In the above context, if we access getBean("--") method over Container reference then ApplicationContext Container will search for the Bean object on the basis of the provided bean identity, if it is available then AppliationContext Container will return Bean object.
Differences between BeanFactory and ApplicationContext IOC Containers
1. BeanFactory is fundamental IOC Container, it able to provide fundamental functionalities to the spring applications like creating and maintaining bean objects.
     ApplicationContext IOC Container is an extension of BeanFactory IOC Container, it able to provide some advanced features like Internationalization, Event Handling etc. along with fundamental functionalities what BeanFactory is providing.

2. BeanFactory is not supporting to integrate AOP services like Security, JTA etc. to the spring applications.
     ApplicationContext is supporting to integrate AOP services like Security, JTA etc. to the spring applications.

3. BeanFactory is not suitable for web applications which we are going to prepare on the basis of Spring web module.
     ApplicationContext is suitable for the web applications which we want to prepare on the basis of Spring web module.

4. BeanFactory is able to prepare Singleton objects when we send first request for bean, that is, Lazy Instantiation/Initialization.
     ApplicationContext is able to prepare Singleton objects when we activate Container, that is, early Instantiation/Initialization.

5. BeanFactory is supporting only the scopes like Singleton and Prototype.
     ApplicationContext is supporting almost all the Spring scopes like Singleton, Prototype, request, session, globalSession, webSocket etc.

6. BeanFactory is mainly for Standalone Applications.
     ApplicationContext is for all the types of Spring framework applications.

7. BeanFactory is an outdated Container in Spring applications.
     ApplicationContext is not outdated Container.

Next Tutorial : Bean Definition

Previous Tutorial : Steps to prepare Spring application

No comments:

Post a Comment