🚀 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.
More Relevant Posts
-
🚨 Ever seen this error in Spring Boot? BeanCurrentlyInCreationException: Circular dependency detected! Let me explain it the way I wish someone had explained it to me 👇 ━━━━━━━━━━━━━━━━━ 🧑👩 Imagine two friends — Raj and Priya. Raj: "I'll come to the party only if Priya confirms first." Priya: "I'll confirm only if Raj comes first." Result? Neither moves. Party cancelled. 🪦 That's a Circular Dependency. ━━━━━━━━━━━━━━━━━ In Spring Boot, it happens like this: 🔴 OrderService needs PaymentService to be created 🔵 PaymentService needs OrderService to be created Spring tries to build them both → gets stuck in an infinite loop → throws an exception 💥 ━━━━━━━━━━━━━━━━━ ✅ HOW TO FIX IT: 1️⃣ @Lazy annotation — "Build it only when needed" → Quick fix, works in most cases 2️⃣ Setter Injection — "Build the object first, then wire it up" → More flexible than constructor injection 3️⃣ Refactor your design — "Extract shared logic into a 3rd service" → The REAL fix. Eliminates the root cause. ━━━━━━━━━━━━━━━━━ 💡 Pro Tip: If you keep hitting circular dependencies, it's a signal your classes are doing TOO MUCH. That's your code saying: "Hey, please split me up!" 🙏 Good architecture = small, focused classes with ONE job each. ━━━━━━━━━━━━━━━━━ Have you faced this before? Drop your experience in the comments 👇 #SpringBoot #Java #Programming #SoftwareEngineering #BackendDevelopment #100DaysOfCode #TechTips #CircularDependency #CleanCode
To view or add a comment, sign in
-
🚨 Why I stopped using field injection in Spring Boot I used to write this: @Autowired private UserService userService; Looks clean… but caused real issues. ❌ Problems: * Hard to test * Hidden dependencies * NullPointer risks in edge cases ✅ Now I always use constructor injection: public UserController(UserService userService) { this.userService = userService; } 💥 Real benefit: While writing unit tests, I realized I could mock dependencies easily without Spring context. 💡 Takeaway: Field injection is convenient. Constructor injection is production-safe. Small change. Big impact. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #Microservices #RESTAPI #SystemDesign #DeveloperLife #100DaysOfCode
To view or add a comment, sign in
-
Spring Boot Circular Dependency — Dangerous issue ⚠️ Example: Service A → depends on Service B Service B → depends on Service A 👉 Boom 💥 Circular dependency error 💡 Why it happens: Poor design & tight coupling Solutions 👇 ✅ Refactor logic ✅ Use constructor injection properly ✅ Introduce third service ✅ Use @Lazy (temporary fix) ⚠️ Avoid: Field injection (hard to debug) 👉 Best practice: Use constructor injection ALWAYS Clean architecture prevents these issues 🔥 #SpringBoot #Java #CleanCode
To view or add a comment, sign in
-
Just published my first technical blog! A while back I implemented MinIO in a Spring Boot project and honestly — I struggled a lot finding everything in one place. So I wrote the guide I wish I had. 📖 MinIO + Spring Boot: A Complete Guide to Object Storage in Java Here's what's covered: → What MinIO actually is (and why it's not just another S3 clone) → Why storing files inside your app folder is a bad idea → How to run MinIO locally with a single Docker command → Setting up the MinioClient as a Spring Bean → Handling MultipartFile uploads in your controller → Uploading files to MinIO with a UUID-based object key → Generating presigned URLs that expire after a set time → And the dev vs prod strategy — use MinIO locally, switch to S3 in prod with zero code changes If you're building anything with file uploads in Java, this one's for you. 🔗 Read it here: https://lnkd.in/gtyff-Xy Shoutout to MinIO for building such a clean, S3-compatible tool that actually runs on your laptop! 🙌 #Java #SpringBoot #MinIO #ObjectStorage #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
𝗢𝗽𝘁𝗶𝗼𝗻𝗮𝗹.𝗼𝗿𝗘𝗹𝘀𝗲() 𝗘𝘅𝗲𝗰𝘂𝘁𝗲𝘀 𝗘𝘃𝗲𝗻 𝗪𝗵𝗲𝗻 𝗩𝗮𝗹𝘂𝗲 𝗣𝗿𝗲𝘀𝗲𝗻𝘁 ⚠️ Looks harmless. It’s not. User user = findUserInCache(userId) .orElse(loadUserFromDatabase(userId)); Many developers read this as: 👉 "load from DB only if cache missed" But that is not what happens. 🔥 What actually happens orElse(...) is eager. That means the argument is evaluated before orElse() is called. So even when user is already present in cache, this still runs: 👉 loadUserFromDatabase(userId) Effectively: User fallback = loadUserFromDatabase(userId); // always executed User user = findUserInCache(userId).orElse(fallback); 💥 Why this hurts in production That fallback is often not cheap. It can be: 🔹 DB query 🔹 remote API call 🔹 disk read 🔹 heavy object construction So what looked like a safe fallback becomes hidden work on every request. 👉 extra CPU 👉 unnecessary IO 👉 more latency 👉 performance regression that is easy to miss in review ✅ The correct approach Use orElseGet(...) when fallback is expensive. User user = findUserInCache(userId) .orElseGet(() -> loadUserFromDatabase(userId)); Now the fallback runs only if Optional is empty. ⚠️ When orElse() is fine orElse() is still okay when the fallback is trivial: String name = maybeName.orElse("unknown"); Constant value, already computed value, or something very cheap. 🧠 Takeaway orElse() is not lazy. If you pass a method call there, that method may execute even when the value is already present. That is exactly the kind of tiny thing that later turns into: "Why is the DB getting hit so much?" 🤦 Have you ever seen a small Java convenience API cause a very non-convenient production problem? 👀 #java #springboot #performance #backend #softwareengineering #programming #coding
To view or add a comment, sign in
-
-
📌 Understanding @Primary in Spring Boot 🔍 What is @Primary? When multiple beans of the same type exist, Spring gets confused about which one to inject. That’s where @Primary comes in. 👉 Definition: @Primary marks a bean as the default choice for dependency injection. --- 💻 Real-Time Example Let’s say we have: Interface → Computer Implementations → Laptop 💻 and Desktop 🖥️ Class → Developer (depends on Computer) Now Spring has two options: Laptop or Desktop 🤔 --- ✅ How @Primary Works We mark one bean as default: Laptop is annotated with @Primary Developer simply uses: @Autowired Computer computer; 👉 Spring automatically injects Laptop --- 💡 Key Point ➡️ No need to specify anything in the Developer class ➡️ Specification was done in class. so, we have to choose either one from the bean classes by using annotations ➡️ Spring picks the default bean (Laptop) ➡️ Otherwise if we choose (desktop) as default bean means as setting @primary annotation spring picks that --- 🧠 Simple Understanding @Primary tells Spring: 👉 “Use this bean by default unless I say otherwise.” --- 🚀 When to Use ✔ When one implementation is used most of the time ✔ To reduce configuration and keep code clean --- 🔚 Conclusion @Primary simplifies dependency injection by setting a default behavior, making your code less complex and more readable. --- #SpringBoot #Java #DependencyInjection #BackendDevelopment #JavaDeveloper #Tech thanks to: Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam
To view or add a comment, sign in
-
While building a recent Spring Boot application, I realized... The Hook: Stop defaulting to .parallelStream() to make your Java code "faster." 🛑 The Insight: It’s a common misconception that parallel streams always improve performance. Under the hood, parallelStream() uses the common ForkJoinPool. If you are executing CPU-intensive tasks on a massive dataset, it’s great. But if you are doing I/O operations (like database calls or network requests) inside that stream, you will exhaust the thread pool and bottleneck your entire application. The Pro Tip: Always benchmark. For I/O bound tasks, look into asynchronous programming (like CompletableFuture) or Java 21's Virtual Threads instead of parallel streams. #Java #PerformanceOptimization #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🧠 After learning Dependency Injection, I had one big question 👀 Who actually creates these objects in Spring Boot, and when? Today I explored the Spring Bean Lifecycle 🚀 Simple flow 👇 1️⃣ Spring container starts 2️⃣ Bean object is created 3️⃣ Dependencies are injected 4️⃣ Bean becomes ready to use 5️⃣ Bean is destroyed when the app shuts down What made this even more interesting 👇 ✅ @PostConstruct → runs after bean creation ✅ @PreDestroy → runs before bean cleanup 💡 My takeaway: Spring doesn’t just inject dependencies — it also manages the entire lifecycle of the object. The more I learn this framework, the more beautifully engineered it feels ⚡ #Java #SpringBoot #BeanLifecycle #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Checked vs Unchecked Exceptions - Know the Difference ⚠️ 🔹 Checked Exceptions ▸ Checked at compile time ▸ Must be handled (try-catch or throws) ▸ Not handled → code won’t compile ▸ Examples: IOException, SQLException, FileNotFoundException 🔹 Unchecked Exceptions ▸ Occur at runtime ▸ No need to handle (but recommended) ▸ Extend RuntimeException ▸ Examples: NullPointerException, ArrayIndexOutOfBoundsException 💡 Simple Way to Remember → Checked = Compiler forces handling → Unchecked = Runtime errors 🚀 Best Practice ▸ Use Checked → for recoverable scenarios (e.g., file not found → retry) ▸ Use Unchecked → for programming bugs (e.g., null → fix the code) #Java #SpringBoot #ExceptionHandling #JavaDeveloper #BackendDeveloper
To view or add a comment, sign in
-
-
📌 Understanding @Qualifier in Spring Boot 🔍 What is @Qualifier? When multiple beans of the same type exist, and you want a specific one, use @Qualifier. 👉 Definition: @Qualifier specifies exactly which bean to inject. --- 💻 Real-Time Example We have: Interface → Computer Implementations → Laptop 💻 and Desktop 🖥️ Class → Developer Spring sees two beans and needs clarity 🤯 --- ✅ How @Qualifier Works We explicitly choose the bean: In Developer class: @Autowired @Qualifier("desktop") Computer computer; @Autowired @Qualifier("laptop") Computer computer; 👉 Spring injects Desktop --- 💡 Key Point ➡️ You control which bean is injected ➡️ Overrides any @Primary configuration ➡️ We need not to make any changes between the bean classes simply make change in dependent class (developer) --- 🧠 Simple Understanding @Qualifier tells Spring: 👉 “I don’t want the default, I want this specific one.” --- 🚀 When to Use ✔ When multiple implementations are used ✔ When you need precise control over dependency injection --- 🔚 Conclusion @Qualifier gives you fine-grained control, making your application more flexible and explicit. --- #SpringBoot #Java #DependencyInjection #BackendDevelopment #JavaDeveloper #Coding #TechLearning thanks to: Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development