swathi bommidi’s Post

💡 Types of Dependency Injection in Spring Framework: In 🌱 Spring, Dependency Injection (DI) is used to provide objects (dependencies) to a class instead of creating them manually. The two main types are: 🔹 1. Setter Injection 👉 Dependencies are injected using setter methods after the object is created. ✔️ Uses @Autowired on setter ✔️ Allows optional dependencies ✔️ Easy to modify dependencies at runtime 📌 Example: @Component public class Car { private Engine engine; @Autowired public void setEngine(Engine engine) { this.engine = engine; } } 🧠 Working Mechanism: 1️⃣ Spring Container creates the Car object 2️⃣ Then it creates the Engine object 3️⃣ Calls setter method → injects dependency 🔹 2. Constructor Injection 👉 Dependencies are injected through the constructor at the time of object creation. ✔️ Preferred approach in modern Spring ✔️ Ensures required dependencies are not null ✔️ Supports immutability 📌 Example: @Component public class Car { private final Engine engine; @Autowired public Car(Engine engine) { this.engine = engine; } } 🧠 Working Mechanism: 1️⃣ Spring identifies constructor dependencies 2️⃣ Creates required objects (Engine) first 3️⃣ Injects them while creating Car object 🚀 Setter vs Constructor Injection 🔸 Setter Injection Optional dependencies ✔️ More flexible ✔️ Slightly less safe ❗ 🔸 Constructor Injection Mandatory dependencies ✔️ More secure & immutable ✔️ Recommended by Spring ✔️ #SpringFramework #Java #DependencyInjection #BackendDevelopment #Coding Anand Kumar Buddarapu

  • timeline

To view or add a comment, sign in

Explore content categories