...

/

IoC and Dependency Injection

IoC and Dependency Injection

Learn about a few interview questions regarding IoC and dependency injection.

What is Inversion of Control (IoC)?

Suppose, class A is dependent on class B. In case of tight coupling, class A is responsible for creating an object of class B. In case of loose coupling, the framework takes the responsibility of creating and populating the dependency. The control of creating dependency shifts from the class to the framework. This is called Inversion of Control (IoC).

What are the advantages of Inversion of Control?

  • IoC minimizes the amount of code in the application since the framework is now responsible for creating and wiring the dependencies.
  • Inversion of Control leads to loose coupling where it becomes easy to change implementations of an interface.
  • It leads to better testability as mock objects can be created for the application.
  • IoC supports eager instantiation as well as lazy loading.

What is the responsibility of an IoC container?

An IoC container performs the following tasks:

  • It instantiates the application class.
  • It identifies the beans along with their dependencies and wires the dependencies.
  • It manages the lifecycle of the beans from the time they are created till the time they are destroyed.

The IoC container uses the configuration metadata, in the form of an XML file or Java annotations, which contains instructions about the objects and their dependencies.

Describe the two types of IoC containers.

The two types of IoC containers are BeanFactory and ApplicationContext. These are interfaces with various implementations that act as the IoC container.

BeanFactory provides the basic functionality of an IoC container while ApplicationContext adds extra functionality like AOP, message resource handling for internationalization, and WebApplicationContext for web applications.

Spring recommends using ApplicationContext unless the resources are limited, like, for example, on a mobile device or for applet-based applications.

Give an example of the BeanFactory implementation.

The most commonly used implementation of BeanFactory is the XmlBeanFactory class. This container reads the metadata from an XML config file to create a fully configured application.

What is ApplicationContext?

ApplicationContext is a type of IoC container. It extends the BeanFactory interface. ...