IoC and DI in Spring


IoC(Inversion of Control):

Normally, in Java, we create references/variables by declaring them and then assigning a value to them or if reference by creating an object by calling its constructor with new. In this process, the total control of instantiating, configuring the variables/references(or)beans is with the developer.
Instead, if this given to some other component, the task of providing the developer with objects meaning the task of creating objects is taken away from developer(can do if wishes to, but, won't be IoC), the normal process is inverted, hence called 'Inversion of Control'.

Now, in Spring, this is done by IoC Container-ApplicationContext. The Spring Container is responsible for instantiating, configuring and managing lifecycle of beans.
Spring framework provides several implementations of ApplicationContext- ClassPathXmlApplicationContext, FileSystemXmlApplicationContext and WebApplicationContext(for web applications).

DI (Dependency Injection): 

DI is the process of providing dependencies.
DI is one of the ways in which IoC is achieved.

Let's understand the terms literally,
dependency- what you need/depend upon- in this context its, the objects a class is depended upon(specially the other class objects).
Injection- inserting, putting in place etc.

So, when you create the objects required you are doing the job of providing/getting dependencies, when its done by something else which means it is injecting the dependencies.

This DI can be done through two ways-
1. XML Configuration
2. Annotation based Configuration

And these in turn can be injected at variable level or constructor level or method level(setter).
---------------------------------------------------------------------
These help in creating loosely-coupled applications with Spring.



Comments

Popular posts from this blog

Creation of Spring + Hibernate + Maven Application