Spring IOC Container Types

Spring Container Types –

The Spring container is the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.

Spring mainly provides following two types of containers – 

  1. BeanFactory container
  2. ApplicationContext container

1. BeanFactory container

A BeanFactory is essentially nothing more than the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. The BeanFactory enables you to read bean definitions and access them using the bean factory. When using just the  you would create one and read in some bean definitions in the XML format.

Below are the ways to create BeanFactory –

InputStream is = new FileInputStream("beans.xml");
BeanFactory factory = new XmlBeanFactory(is);
//Get bean
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");

Resource resource = new FileSystemResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
//Get bean
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");

ClassPathResource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
//Get bean
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");

2. ApplicationContext container

This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.

The ApplicationContext container includes all functionality of the BeanFactory container, so it is generally recommended over the BeanFactoryBeanFactory can still be used for lightweight applications like mobile devices or applet based applications where data volume and speed is significant.

The most commonly used ApplicationContext implementations are:

  1. FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. You need to provide the full path of the XML bean configuration file to the constructor.
  2. ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. You do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
  3. WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.

A sample code for application context instantiation is as below.

ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

 

Cheers!!!!!!

Leave a Comment

Bitnami