🚀 Spring Boot Exception Handling with @ExceptionHandler Most developers handle errors reactively — scattering try/catch blocks everywhere. There's a cleaner way. Spring Boot's @ExceptionHandler lets you centralize error handling right where it belongs: in your controller. Here's the pattern that changes everything: @RestController @RequestMapping("/users") public class UserController { @GetMapping("/{id}") public UserDto getUser(@PathVariable Long id) { return userService.findById(id); // throws UserNotFoundException } @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) { ErrorResponse error = new ErrorResponse(404, ex.getMessage()); return ResponseEntity.status(404).body(error); } } What makes this powerful: ✅ Clean separation of business logic and error handling ✅ Consistent JSON error responses for clients ✅ No more polluted service/controller methods ✅ Type-safe — each exception type gets its own handler The key insight? @ExceptionHandler scope is per-controller. If you want application-wide handling, you'll need @ControllerAdvice — and that's exactly what we'll cover tomorrow! 🎯 #Java #SpringBoot #BackendDevelopment #ExceptionHandling #REST #CleanCode
Jānis Ošs’ Post
More Relevant Posts
-
Spent 10 minutes wondering why my Spring Boot application was not picking up environment variables. The code looked fine: @Value("${DATABASE_URL}") private String databaseUrl; No errors at startup. But the value was always null. The problem: I was using underscores in the property name, but Spring expects dots or lowercase with hyphens. The fix: @Value("${database.url}") private String databaseUrl; And in application_properties: database.url=${DATABASE_URL} One mapping. That was it. Spring does not automatically convert environment variable names to property names. You need to map them explicitly. What environment variable issue has caught you off guard? #Java #SpringBoot #EnvironmentVariables #Debugging #BackendDevelopment
To view or add a comment, sign in
-
🚀 Day 18/100: Spring Boot From Zero to Production Topic: Auto-Configuration 💡 What is Auto-Configuration? One of the most powerful features in Spring Boot Turns hours of setup into minutes Eliminates heavy XML configs and manual bean wiring ⏳ Before Auto-Configuration Manually define multiple beans Write hundreds of lines of XML Configure everything yourself → painful ⚙️ What Happens Now? Your @SpringBootApplication kicks things off Spring Boot scans the classpath Looks for dependencies like: spring-webmvc spring-data-jpa 👉 Presence/absence of JARs = signals 🧠 Behind the Scenes Reads a special file: META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports Contains hundreds of auto-config classes Each uses conditions like: @ConditionalOnClass @ConditionalOnMissingBean 👉 Result: Beans get configured automatically 🌐 Simple Example Add: spring-boot-starter-web Spring Boot assumes: You need a web app So it adds an embedded server (Tomcat) automatically 🛠️ Can You Override It? YES You can: Define your own beans Override defaults Disable auto-config if needed Auto-configuration isn’t magic. It’s just smart defaults + conditional logic working for you #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
🚀 Spring Boot Tip: @Qualifier vs @Primary (Fix Bean Ambiguity) Facing this error? 👇 "NoUniqueBeanDefinitionException" 👉 It means Spring found multiple beans of the same type and doesn’t know which one to inject. --- ✅ @Qualifier — Be Explicit Use "@Qualifier" when you want to specifically choose a bean. @Autowired @Qualifier("upiPaymentService") private PaymentService paymentService; ✔ You tell Spring exactly which implementation to inject ✔ Best when you have multiple beans and need control --- ✅ @Primary — Set a Default Use "@Primary" to mark one bean as the default choice. @Component @Primary class CreditCardPaymentService implements PaymentService {} ✔ Spring will pick this automatically ✔ Works when no "@Qualifier" is specified --- 🧠 Key Difference 👉 "@Qualifier" = Explicit selection 👉 "@Primary" = Default fallback --- ✨ Pro Tip If both are present: ➡️ "@Qualifier" overrides "@Primary" --- #SpringBoot #Java #BackendDevelopment #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
Stop using ArrayList as your default collection! 🛑 In many Spring Boot projects, ArrayList is the go-to for every single list. But as a Developer, choosing the right collection is a small decision that pays off in huge performance gains at scale. 🔹 ArrayList vs LinkedList: If you're doing frequent insertions or deletions at the beginning of a list, ArrayList is a performance killer ($O(n)$ shifts). LinkedList excels there. 🔹 HashSet / LinkedHashSet: Do you have a list of user permissions or roles? If you need contains() checks, don't iterate. Use a Set. It turns a $O(n)$ search into an $O(1)$ lookup. 🔹 CopyOnWriteArrayList: Dealing with concurrency in a multi-threaded service? This is your best friend to avoid ConcurrentModificationException. Tip: Don't just code; optimize for the data structure's behavior. Always ask: "What is the primary operation I'm doing here? Search, insertion, or iteration?" What’s your "go-to" collection for high-performance modules? Let’s talk in the comments! 👇 #Java #SpringBoot #Performance #CollectionsFramework #SoftwareEngineering #Backend #CleanCode
To view or add a comment, sign in
-
-
Understanding @RestController in Spring Boot In Spring Boot, handling client requests is a core part of building applications. @RestController But what does it actually do? @RestController is used to create RESTful web services. It handles incoming HTTP requests and returns responses (usually in JSON format). It is a combination of: @Controller + @ResponseBody This means: ✔ You don’t need to write @ResponseBody on every method ✔ All methods return data directly instead of views Key Responsibilities: 🔹 Handles HTTP requests (GET, POST, PUT, DELETE) 🔹 Maps URLs using annotations like @GetMapping, @PostMapping 🔹 Returns JSON/XML responses In simple terms: @RestController → Takes request → Processes it → Returns response Understanding this annotation is important because it is the entry point for building APIs in Spring Boot. #SpringBoot #Java #BackendDevelopment #LearningInPublic #DeveloperGrowth
To view or add a comment, sign in
-
-
Spring doesn’t just create beans- it manages their entire lifecycle. Many developers stop at "@Autowired", "@Qualifier", and "@Primary". But to build reliable and production-ready applications, understanding the Spring Bean Lifecycle is essential. ------ 🧠 What happens behind the scenes? A Spring bean goes through multiple stages: • Instantiation • Dependency Injection • Initialization (e.g., "@PostConstruct") • Ready for use • Destruction (e.g., "@PreDestroy") ------ 🔥 Key idea: • "@PostConstruct" → Used for initialization after dependencies are injected • "@PreDestroy" → Used for cleanup before the bean is destroyed ----- 💡 Why this matters: Proper lifecycle management helps you: ✔ Avoid resource leaks ✔ Manage connections effectively ✔ Write cleaner and more maintainable code ✔ Build stable, production-ready applications ----- 🎯 Best practice: Avoid placing heavy logic (such as database calls) inside constructors. Instead, use lifecycle annotations to handle initialization and cleanup in a structured way. ----- 📌 Takeaway: If your Spring knowledge ends at dependency injection, you’re only scratching the surface. 👉 Understanding the lifecycle is what separates good developers from great ones. #SpringBoot #SpringFramework #JavaDeveloper #BackendDevelopment #SoftwareEngineering #CleanCode #CodingBestPractices #LearnInPublic #Developers #Java
To view or add a comment, sign in
-
-
🚀 Stop Building "Junk Drawer" Projects: The Art of Java Backend Structure 🚀 Ever opened a repository and felt like you were looking at a digital junk drawer? We’ve all been there—Service logic leaking into Controllers, DTOs scattered like confetti, and a util package that’s basically a graveyard for "I didn’t know where else to put this." In the Java world, structure isn't just about aesthetics; it’s about survival. Whether you are using Spring Boot or Micronaut, a clean architecture saves your team hours of debugging and technical debt. Here is the "Golden Standard" for a maintainable backend: 🏗️ The Layered Blueprint Controller Layer: The "Receptionist." It handles incoming requests and validates input. Keep it thin! No business logic allowed. Service Layer: The "Brain." This is where your business rules live. If your app calculates a discount or processes a payment, it happens here. Repository Layer: The "Librarian." Pure data access. Keep your SQL or JPA logic tucked away from the rest of the app. Domain/Entity Layer: The "Core." Your database blueprints and business objects. 💡 Pro-Tips for Clean Repos: Package by Feature, not Layer: For large apps, group by user, order, and payment rather than putting 50 controllers in one folder. It scales better! DTOs are Mandatory: Never expose your Database Entities to the API. Use Data Transfer Objects to decouple your internal schema from the outside world. The Exception Handler: Centralize your errors with a @ControllerAdvice. Your future self will thank you when you don't have try-catch blocks cluttering every method. A project’s structure is a love letter to the next developer who has to maintain it. ✍️ How do you structure your projects? Are you a "Package by Layer" purist or a "Feature-Driven" fan? Let’s talk in the comments! 👇 #Java #BackendDevelopment #SoftwareArchitecture #CodingTips #SpringBoot #CleanCode
To view or add a comment, sign in
-
-
Spring Boot Interview Series — Post 9 Spring Boot fails to start when two beans depend on each other. BeanCurrentlyInCreationException - Spring tries to create DepositService, which needs PaymentService, which needs DepositService and it's stuck. From Spring Boot 2.6, circular dependencies are prohibited by default. Your app fails at startup - no silent failures. 3 ways to fix it - in order of preference: -> Refactor - circular dependency is a design smell. It usually means two classes are doing too much. Extract the shared logic into a third service. DepositService → NotificationService, PaymentService → NotificationService. No cycle. Clean design. -> @Lazy - put it on the constructor parameter of one bean. Spring injects a proxy placeholder instead of the real bean. The real bean is created only when first used. Quick fix - but doesn't solve the underlying design problem. Use only when refactoring is not practical. -> Setter injection - Spring creates both beans first, then injects dependencies via setters. Breaks the creation deadlock. Field cannot be final. Last resort only. Circular dependency is almost always a sign that two classes are too tightly coupled. Fix the design before reaching for @Lazy. #SpringBoot #Java #JavaDeveloper #BackendDevelopment #SpringFramework
To view or add a comment, sign in
-
-
🚀 Day 7 — What is Bean? (Core Spring Concept 🔥) Today I understood one important thing… 👉 Everything in Spring is a Bean 💡 What is a Bean? 👉 A Bean is an object created and managed by Spring (IoC container) (Simple: Spring creates object, we just use it) ⚙️ How Spring Creates Bean? Using XML (<bean>) Using Annotations (@Component, @Service) 👉 Spring container creates, manages, and injects beans ⚡ Bean Scope (Important 🔥) 🔹 Singleton (default) 👉 Only ONE object created 🔹 Prototype 👉 New object every time 🔍 Bean Lifecycle (Simple Flow) 👉 Create → Initialize → Use → Destroy 💡 One line I learned: 👉 In Spring, objects are called Beans and Spring manages them 💬 Which scope confused you — Singleton or Prototype? Day 7 done ✅ #Spring #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #SpringBoot #Developers
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