🚀 Understanding Dependency Injection in Spring Boot with a Simple Example I recently explored one of the core concepts of the Spring Framework — Dependency Injection (DI) — by building a simple Spring Boot application. 💡 What is Dependency Injection? Dependency Injection is a design pattern where the Spring container automatically provides the required dependencies to a class, instead of the class creating them manually. This helps in achieving loose coupling and better maintainability. 🔷 Project Overview In this example, I created: A Developer class that depends on a Computer A Computer interface with multiple implementations: Laptop Desktop 🔷 How it Works ✔️ The Developer class uses @Autowired to inject the dependency: Spring automatically assigns an object of a class that implements Computer ✔️ Since there are multiple implementations (Laptop & Desktop): I used @Primary on the Laptop class This tells Spring to inject Laptop by default ✔️ The application flow: Spring Boot starts and initializes the application context Beans are created automatically using @Component Dependency is injected into the Developer class The startCoding() method executes and calls computer.code() 🔷 Key Annotations Used @SpringBootApplication → Entry point of the application @Component → Marks classes as Spring beans @Autowired → Injects dependencies automatically @Primary → Resolves ambiguity when multiple beans are available 🔷 Output 👉 "Coding in laptop......" (Because Laptop is marked as @Primary) ✨ This small implementation helped me clearly understand how Spring manages dependencies behind the scenes. #SpringBoot #Java #DependencyInjection #BackendDevelopment Thanks to Anand Kumar Buddarapu Sir.

To view or add a comment, sign in

Explore content categories