Introduction to Spring Part II – Bean, BeanFactory, ApplicationContext, IOC

In this technoticle I will be explaining some of the basic concepts of Spring :

Bean – It is the basic element of the framework. It is equivalent to an object created in java. In spring bean can be created using following methods:

1)      Setter injection

2)      Constructor injection

3)      Interface injection

4)      Static factory method

5)      Instance method

The detailed explanation is Dependency Injection

BeanFactory – As the name suggest the beanfactory instantiate, configure and manages all beans defined. These beans typically collaborate with one another, and thus have dependencies between themselves. The ways by which beanFactory can be created: 

  • InputStream is = new FileInputStream(“beans.xml
    XmlBeanFactory factory = new XmlBeanFactory(is);

  • ClassPathResource res = new ClassPathResource(“beans.xml”); 
    XmlBeanFactory factory = new XmlBeanFactory(res);

  • ClassPathXmlApplicationContext appContext =  new ClassPathXmlApplicationContext (new String[] { “applicationContext.xml”,”applicationContext-part2.xml”}
    BeanFactory factory = (BeanFactory) appContext;

When any of the above lines are executed all beans present in the “configuration” file(s) are instantiated and stored in the bean factory.Once the bean factory is loaded the bean can be retrieved:


   BeanClassName beanObj = (BeanClassName) factory.getBean(“beanName”);


ApplicationContext: ApplicationContext extends BeanFactory and thus provide extra functionality than BeanFactory.

The following are the additional functionalities:

·         MessageSource, providing access to messages in, i18n-style

·         Access to resources, such as URLs and files

·         Event propagation to beans implementing the ApplicationListener interface

·         Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application

Invresion of Control – Earlier the control of interface was with the application program. For example it a typical user input application a prompt will pop up saying ‘Enter Name’ or at some place the property has to be set explicitly using the setter methods. But with the advent of IOC, now it’s the responsibility of the container in which beans are loaded to find the correct value of a property with the help of spring configuration file and now not much responsibility is left to the application program to set or get the values.IOC is too generic term, so spring generally designates it as Dependency Injection (DI). 

 A typical IOC container would look like:

IOC Container
IOC Container


  • An IOC can have multiple ApplicationContexts.
  • ApplicationContext can also refer other application context.
  • Applicationcontext can contain another applicationcontext.
  • Multiple beanfactories can be inserted in an applicationcontext.