Loading
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

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:

  • You --> need objects
  • Spring Container --> prepares & delivers them
So control is inverted --> from your code --> to Spring.


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)

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
Sprng applicaton scale better because objects are not tighlty tied to each other.