Blue Jeans Interview Question
Principal Software EngineersCountry: India
The Inversion of Control and Dependency Injection patterns are all about removing dependencies from your code.
First ,why there is an Inversion of control in Spring Framework?
Answer would be, In java,user is responsible to instantiate an object of class. But in Spring framework, the control is taken from the user,so user is not responsible to instantiate class object. Rather user will define a component as a spring bean in XML file & after that Spring is responsible to instantiate an object of your class. So the flow is inverted & its called "Inversion of Control"
Dependency injection is a concrete example of Inversion of Control.
Here you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.
There are several advantages of IOC or dependency injection:
• It minimizes the amount of code in your application.
• It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.
• Loose coupling is promoted with minimal effort and least intrusive mechanism.
• IOC containers support eager instantiation and lazy loading of services.
Example
standrad code would look something like:
Public class sample{
private Ispell spell;
public sample(){
Ispell=new Sample();
}
}
Now in IOC ,we do something like
Public class sample{
private Ispell spell;
public sample(Ispell spell){
this.spell=spell;
}
}
Spring helps in creating loosely coupled application because of Dependency Injection.
- zealoftoday March 21, 2015In spring objects define their associations (dependencies) and do not worry about how to get those dependencies ; now it is the responsibility of Spring to provide the required dependencies for creating objects.
For example : Suppose we have an object Employee and it has a dependency on object Address. So we define a bean corresponding to Employee where it will define its dependency on object Address. When Spring try to create an Object Employee it sees that Employee has a dependency on object Address so first it will create the Address object (dependent object) and then inject this into the Employee Object.
Inversion of Control (IOC) and Dependency Injection (DI) are used interchangeably. IOC is achieved through DI. DI is the process of providing the dependencies and IOC is the end result of DI.
By DI the responsibility of creating objects is shifted from our application code to Spring container hence the phenomenon is called IOC.
Dependency Injection can be done by setter injection, constructor injection.