Dependency injection-interview
Q1. What is Invresion of Control (IoC) in Spring ?
Inversion of Control (IoC) means you do not crate objects manually in your code. Instead, the Spring IoC Container creaes, manges and supplies the objects whenever your applicatoin needs them.
Normally in Java, you write
But in Spring, you do not create objects yourself. Spring creates them and gives them to you.
Normally in Java, you write
A a = new A();But in Spring, you do not create objects yourself. Spring creates them and gives them to you.
Real World Analogy
Think of a restaurant.
You do not cook your own food you order it, and the kitchen prepares everything.
Similarly:So control is inverted --> from your code --> to Spring.
- You --> need objects
- Spring Container --> prepares & delivers them
Q2. What s Dependency Injection (DI) ?
Dependency Injection is a technique where Spring provides the required objects (dependencies) to a class from outside, instead of the class creating them internally.
Without DI (Tight Coupling)
A creaets B --> hard to test, modify and maintain.
With DI (Loose Coupling)
Now A receives B from outside --> easy to test and maintain.
DI = objects injected automatically by Spring.
Without DI (Tight Coupling)
class A { private B b = new B();}A creaets B --> hard to test, modify and maintain.
With DI (Loose Coupling)
class A { private B b;
public A(B b) { this.b = b; }}Now A receives B from outside --> easy to test and maintain.
DI = objects injected automatically by Spring.
Q3. Why are IoC and DI important ?
IoC and DI make your applicatoin
- Loose coupled
- Easier to test
- More readable
- Easier to maintain
- Flexible for future changes
- Suitable for large & Comples systems