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
Spring Boot Circular Dependency Issue
More Relevant Posts
-
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 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
-
🚨 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
-
🔍 Filters vs Interceptors in Spring Boot — and why most devs mix them up Both intercept HTTP requests. Both let you run logic before and after your controller. But they live at completely different layers — and choosing the wrong one leads to subtle bugs. Here's the mental model that clears it up: Filter = Servlet Container layer. Runs before DispatcherServlet even knows a request came in. It sees everything — including static resources. Interceptor = Spring MVC layer. Runs after DispatcherServlet, before your controller method. It knows which handler is being called. The one-line rule I use: If it needs to apply to every request, use a Filter. If it needs to know which endpoint is being called, use an Interceptor. This distinction matters for: → Security — JWT pre-checks live in Filters, role validation in Interceptors → Logging — request metadata at filter level, execution time at interceptor level → Clean architecture — putting logic at the right layer keeps things testable Swipe through the full breakdown with code examples and comparison table 👇 💬 Drop a comment: Which one do you use more in production, and for what? #SpringBoot #Java #BackendDevelopment #Microservices #SpringMVC #JavaDeveloper #SoftwareArchitecture #TechInterview #SpringFramework #Programming
To view or add a comment, sign in
-
-
🧠 After learning the Spring Bean Lifecycle, I explored another powerful concept today 👀 Singleton vs Prototype Bean Scope in Spring Boot 🚀 The default scope in Spring is singleton 👇 ✅ Only one object instance is created ✅ Shared across the whole application ✅ Best for services, repositories, controllers Then comes prototype 👇 🔁 A new object is created every time it is requested This makes it useful for: ✅ temporary objects ✅ stateful helpers ✅ per-request custom processing 💡 My takeaway: Bean scope directly changes how Spring manages memory and object reuse. Small annotations can completely change runtime behavior ⚡ #Java #SpringBoot #BeanScope #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
"Depend on things that change less often than you do." ― Practical Object-Oriented Design by Sandi Metz I need to admit it. I never spent more than a few minutes whether service X should depend on service Y or the other way round ? Two classes. Either can depend on the other. The result is the same. So the direction doesn't matter — until your codebase starts to grow. Then it matters a lot. Choosing what depends on what is a design decision with long-term consequences. Get it right and changes stay local. Get it wrong and a small tweak cascades through the entire system. This applies at every level — from two classes collaborating, to two services in a Spring application, all the way up to microservices communicating across a system. #SoftwareDesign #CleanCode #POODR #ObjectOrientedDesign #SoftwareEngineering #Java
To view or add a comment, sign in
-
🚀 Day 98/100 - Spring Boot - Creating & Listening to Custom Events As, we have discussed event-driven architecture in the previous post (https://lnkd.in/dWjTG_3j)... Now let’s implement it in Spring Boot. ➡️ Create and Listen to Custom Events it's a 3-step process: 🔹Step 1: Define a Custom Event 🔹Step 2: Publish the Event 🔹Step 3: Listen to the Event ❗See attached image for code 👇 ➡️ What’s Happening Actually? 🔹Event is published after user creation 🔹Listener automatically reacts 🔹No direct dependency between components #100Days #SpringBoot #EventDriven #Java #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
Spring Boot Custom Argument Resolver 🚀 Want to inject custom objects into controller automatically? You can 👇 public class UserArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterType().equals(User.class); } @Override public Object resolveArgument(...) { return getUserFromToken(); } } 💡 Use case: ✔ Extract user from JWT ✔ Avoid repeated code in controllers 👉 Clean & powerful approach 🔥 Real-world: Used in production for authentication context This is advanced Spring Boot design 💯 #SpringBoot #Java #Backend
To view or add a comment, sign in
-
Hi everyone, happy weekend 🤗 Today I want to discuss Constructor Injection in Spring Framework. 👉 Constructor injection is a way in Spring where all required properties are provided at the time the object is created. This ensures the object is fully initialized and ready to use immediately. 👉 We mainly use this when properties are mandatory for the class to function and when we want complete initialization at the time of object creation. 👉 The main benefits of this are: ✔ Ensures all required values are available from the start ✔ Avoids null values and incomplete objects ✔ Improves code safety and reliability ✔ Makes testing easier ✔ Supports immutability (with final fields) #SpringBoot #Java #BackendDevelopment #WeekendLearning
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
-
Explore related topics
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
@Lazy initialisation seems very lucrative as it is an instant easy fix and everything seems to work. However, I feel it should be avoided until it's the last resort. Spring invokes a proxy of the Class and not the real object. This can lead to silent runtime errors and un expected behaviours such as in cases where equals() or hascode() is used. Debugging gets harder, so do the Testing. Imagine Mocking a proxy of a class with Lazy loading. Best to refactor or have a third service & use constructor injection.