🌟 1. What is Spring Framework?
Spring Framework is a powerful, lightweight Java platform for building enterprise-grade applications. It provides a comprehensive infrastructure support for developing Java applications.
✅ Main Goals:
Loose Coupling
Easy Testing
Better Code Maintainability
Integration with Web, Security, AOP, ORM, and Microservices (via Spring Boot)
🌀 2. What is Inversion of Control (IoC)?
📌 Definition:
#BCS403,#Object Oriented Programming with JavaInversion of Control means transferring the control of object creation and dependency management to the Spring container, instead of manually creating objects using
new
keyword.
📦 Real-Life Analogy:
-
Without IoC: You go to a restaurant, go to the kitchen, cook food, serve yourself.
-
With IoC: You sit at a table and order. Chef (Spring container) serves you everything — you just consume.
🔧 Before Spring (Tightly Coupled Code):
🌱 With Spring IoC (Loose Coupling):
And Spring container injects it for you.
🔗 3. What is Dependency Injection (DI)?
📌 Definition:
Dependency Injection is a design pattern used to achieve IoC. The object’s dependencies are injected by the container, not created manually.
✅ Types of Dependency Injection in Spring:
Type | Description | Use Case |
---|---|---|
Constructor DI | Dependencies are passed via constructor | Immutable objects |
Setter DI | Dependencies injected via setter method | Optional dependencies |
Field DI | Using annotations (@Autowired ) | Quick setup |
1️⃣ Constructor Injection (Constructor DI)
📌 Best for: Immutable dependencies (dependencies that shouldn’t change after object creation).
Code Example:
🧩 Engine.java
package com.example;
public class Engine {
public void start() {
System.out.println("🚀 Engine started via Constructor DI");
}
}
Car.java
package com.example;
public class Car { private Engine engine;
// Constructor DI public Car(Engine engine) { this.engine = engine; }
public void drive() { engine.start(); System.out.println("🏎️ Car is moving..."); }}
⚙️ applicationContext.xml