Skip to content

Module 1: Spring Core & IoC (The Magic Hand)

📚 Module 1: Spring Core & IoC

Focus: Moving from “Building” to “Providing.”

In standard Java, you use the new keyword to build everything. In Spring Boot, we let the framework build things for us. This is called Inversion of Control (IoC).


🏗️ Step 1: The “Manual” Problem

Imagine you are building a Coffee Shop App.

  • To have a Shop, you need a CoffeeMachine.
  • In normal Java, you write: CoffeeMachine machine = new CoffeeMachine();
  • The Problem: If you decide to upgrade to a SuperEspressoMachine, you have to find every single place you wrote new and change it manually.

🏗️ Step 2: The Spring Container (The “Butler”)

In Spring, the framework acts like a Personal Butler (The Spring Container).

  1. The Butler looks at your classes and sees which ones are marked with @Component.
  2. The Butler builds them all for you when the app starts.
  3. The Butler stores them in a giant box called the Application Context.

🧩 The Analogy: The Restaurant Kitchen

  • You are the Head Chef.
  • You don’t build the stove, the fridge, or the sink yourself.
  • You just arrive at the kitchen, and The Owner (Spring) has already placed everything you need in the correct spot.

🏗️ Step 3: Dependency Injection (The “Plumbing”)

Once Spring has built your objects (called Beans), it needs to connect them. This is Dependency Injection.

🧩 The Analogy: The Coffee Machine Plumbing

  • Instead of the Chef carrying buckets of water to the machine, the Owner (Spring) connects the water pipes directly to the machine.
  • The machine doesn’t care where the water comes from; it just knows that when it needs water, it’s there.

In Code:

@Component
public class CoffeeMachine {
    public void brew() { System.out.println("Brewing coffee..."); }
}

@Component
public class CoffeeShop {
    private final CoffeeMachine machine;

    // @Autowired tells Spring: "Hey Butler, bring me a CoffeeMachine!"
    @Autowired 
    public CoffeeShop(CoffeeMachine machine) {
        this.machine = machine;
    }

    public void startDay() {
        machine.brew();
    }
}

🏗️ Step 4: Beans (The “Managed Objects”)

In Spring, an object that is managed by the Butler is called a Bean.

  • Bean Lifecycle: Born (Created by Spring) -> Grows Up (Injected with data) -> Works (Runs your app) -> Dies (App shuts down).

🥅 Module 1 Review

  1. IoC (Inversion of Control): Let Spring build the objects instead of you using new.
  2. Dependency Injection (DI): Spring “injects” the tools your classes need.
  3. Application Context: The giant box where Spring keeps all your Beans.
  4. @Component: The label that tells Spring “Please manage this class for me.”
  5. @Autowired: The label that says “I need this tool, please bring it to me.”