Spring IoC Containers

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Container is used to explain any component that can contain other components inside it. The IoC container is responsible to instantiate, configure and assemble the objects. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. The IoC container gets information from the XML file and works accordingly.

Configuration metadata required for container can be provided in the below form.

  • XML
  • Java Code
  • Java Annotations

There are two types of IoC containers.

1. BeanFactory

2. ApplicationContext

1. BeanFactory

BeanFactory interface is an implementation of the Factory design pattern enables objects to be created and retrieved by name.

BeanFactory supports two object modes

1. Singleton mode provides a shared instance of the object with a particular name, which will be retrieved on lookup. Singleton is the default and most often used object mode. It is ideal for stateless service objects.

2. Prototype mode ensures that each retrieval will result in the creation of an independent object. Prototype mode would be best used in a case where each user needed to have his own object.

The most commonly used BeanFactory definition is the XmlBeanFactory, which loads beans based on definitions in an XML file.

BeanFactory Example:

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

Beans defined in XML files are lazily loaded, which means that the beans themselves will not be instantiated until they are needed. To retrieve a bean from BeanFactory you can simply call the getBean() method passing in the name of the bean you want to retrieve.

2. ApplicationContext

Some of the useful ApplicationContext implementations that you use in the application

  • AnnotationConfigApplicationContext: If you are using Spring in standalone java applications and using annotations for Configuration, then you can use this to initialize the container and get the bean objects.
  • ClassPathXmlApplicationContext: If you have spring bean configuration xml file in standalone application, then you can use this class to load the file and get the container object.
  • FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
  • AnnotationConfigWebApplicationContext and XmlWebApplicationContext are used for the web applications.

ApplicationContext Example:

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