Sunday, August 25, 2013

What is ApplicationContext and BeanFactory in Spring?

ApplicationContext(org.springframework.context.ApplicationContext) is interface provided by Spring  and it's used for getting Configuration information about your application.Spring has many classes which implements this interface.

What are common Implementation of ApplicationContext ? - They are
  1. ClassPathXmlApplicationContext
  2. FileSystemXmlApplicationContext
  3. XmlWebApplicationContext
All comes under same package org.springframework.context.support.

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

ApplicationContext is build on top of BeanFactory so It provides all functionality of BeanFactory and some more functionality.

Which Functionalities are provided by ApplicationContext in Spring: ? - They are
  1. Bean Instantiation and Wiring - Containing,Configuring and Managing Beans - Which is also provided by BeanFactory
  2. Support for i18n - MessageSource handling
  3. Access to resources such as URL and Files
  4. Providing Automatic Registration for BeanPostProcessor and BeanFactoryPostProcessor
  5. provides support for ApplicationEvent publication 
Major  difference between ApplicationContext and BeanFactory is "How they load Singleton Beans" :

"ApplicationContext preloads all singleton beans when context startups. it won't wait for getBean('myBean') call. By preloading singleton beans means Beans are ready to use whenever needed and application do not require them to be created"

"While Bean factory loads all singleton beans via lazy loading. meaning life cycle of bean start in Spring container only when you call getBean('myBean')"

BeanFactory:

This interface has many implementation available.Out of them most used one is XmlBeanFactory(org.springframework.beans.factory.xml.XmlBeanFactory) but it's deprecated Since Spring 3.1

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

    Here, Resource can be :
    • ClassPathResource : reads the resource from defination file present in classpath.
    • FileSystemeResource : reads the resource from provided filesystem path.
    • ServletContextResource : reads the resource available in servletcontext.
    • UrlResource : reads the resource from a given URL

    Author : Anuj Patel
    Blog : http://goldenpackagebyanuj.blogspot.in/