The classic Spring Boot validation trap: you have a User DTO. On create, id must be null. On update, id must be present. So you either duplicate the DTO or add conditional checks that progressively make the codebase harder to read. Validation Groups solve this cleanly. You define interface markers — OnCreate and OnUpdate — then annotate constraints with the appropriate group. @Null(groups = OnCreate.class) on id for creates. @NotNull(groups = OnUpdate.class) on id for updates. Same DTO, entirely different validation behaviour depending on which group you pass via Validated in the controller. The javax.validation spec has supported this for years, but it doesn't get discussed enough. Teams discover it after the fact, usually after spending two sprints maintaining parallel DTO hierarchies that drift out of sync. A few things worth knowing: • Default constraints (no group specified) only run when no groups are passed. Once you start using groups, be explicit everywhere. • Spring's Validated is what enables group selection — Valid doesn't support groups. • Validation Groups compose — you can pass multiple groups when needed. We've written a complete guide on Spring Boot input validation covering groups, custom validators, controller-level wiring, and the common mistakes teams make. 👉 https://lnkd.in/eypuK5b9 #SpringBoot #Java #SoftwareDevelopment #CleanCode #APIDesign
Spring Boot Validation Groups Simplify DTO Validation
More Relevant Posts
-
Last weekend I’ve been studying more about error handling and I watched a great video from Dan Vega — an interesting view on how to implement error handling and retries. 🚀 I pushed a small demo repo that captures those ideas using Spring Boot’s new RestClient and a clean error-handling pattern: 🔁 Retry transient failures with @Retryable (exponential backoff). 🧭 Centralize response-to-exception mapping via RestClient’s defaultStatusHandler (ApiException, NotFoundException). 🛡️ Serve consistent ProblemDetail (RFC 7807) responses from a GlobalExceptionHandler for clearer API errors. 🧪 Uses https://httpbin.org/ to simulate status codes and unstable endpoints for deterministic testing. Why this is valuable: - Increases reliability by handling transient errors consistently. - Keeps controllers and business logic clean — the client layer interprets remote errors. - Improves client experience with predictable, machine-readable error payloads. Inspired by Dan Vega’s walkthroughs — credit to him for the patterns and clarity. 🙏 Feel curious how that I did it, check the repo to see the config, examples, and how to adapt this pattern: https://lnkd.in/dEe3HNKr #SpringBoot #Java #Resilience #ErrorHandling #RestClient #Microservices
To view or add a comment, sign in
-
When updating data in a Spring Boot API, standard validation can be too restrictive, often requiring all fields to be sent even for minor changes. A more flexible solution is to use @Validated with validation groups. This approach allows you to define separate sets of rules. For example, you can have a "create" group that requires all fields to be present, and a "default" group that only checks the format of fields that are actually provided in the request. In your controller, you then apply the appropriate rule set: the strict rules for creating new items and the flexible rules for updating them. This allows your API to handle both full and partial updates cleanly while reusing the same data object, resulting in more efficient code. #SpringBoot #Java #API #Validation #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Spring Framework 🌱 | Day 2 – Dependency Injection (DI) Today I understood Dependency Injection not just as a concept… but as a mindset shift 💡 👉 In real life, DI is everywhere. Think about this 👇 ☕ When you order tea in an office You don’t go to the kitchen, buy milk, sugar, tea powder and make it yourself. 👉 Someone provides it to you. 🚗 When you book a cab You don’t build the car or hire a driver manually. 👉 The system injects the service you need. 🏢 In a company project A developer doesn’t create every object manually. 👉 Framework like Spring injects dependencies automatically. 💡 Same happens in Spring Instead of: ❌ Creating objects using "new" We let Spring: ✅ Create objects ✅ Manage them ✅ Inject wherever needed 🔹 How it works internally (simple view): 👉 Spring scans classes 👉 Creates beans in IOC container 👉 Finds dependencies 👉 Injects them using annotations 🔥 Why this matters? - Loose coupling - Easy testing - Clean & scalable code 👉 Small concept, but it completely changes how you build applications. #SpringFramework #Java #BackendDevelopment #LearningJourney #SpringBoot #TechGrowth
To view or add a comment, sign in
-
-
Topic of the day Dependency Injection? What is Dependency Injection (DI)? Dependency Injection (DI) is a concept where a class does not create its own dependencies, instead those dependencies are provided from outside. This helps in reducing tight coupling between classes and makes the code more flexible. For example, if a Car needs an Engine, instead of creating it using new Engine(), we pass the Engine object from outside: class Car { Engine engine; Car(Engine engine) { this.engine = engine; } } Why do we use Dependency Injection? Dependency Injection makes our code: =>Flexible (easy to change implementations) =>Maintainable (less impact when modifying code) =>Testable (we can use mock objects) How it works in Spring Boot? In Spring Boot, the IOC container handles Dependency Injection. When the application starts, Spring creates objects (beans) for classes annotated with @Component, @Service, etc., and injects them wherever needed. Types of Dependency Injection? # Constructor Injection – Dependencies are provided through constructor # Setter Injection – Dependencies are set using setter methods # Field Injection – Dependencies are injected directly using @Autowired Which is Best? Constructor Injection is considered the best approach because: It ensures all dependencies are available at object creation,Prevents null issues, makes unit testing easier. #java #spring #springboot #leraning #javadevelopment #microservices #kafka #hibernate #jpa
To view or add a comment, sign in
-
Understanding Request Mapping in Spring Boot While working on my Spring Boot projects, I explored how request mapping plays a crucial role in handling client requests efficiently. 🔹 @RequestMapping This is a general-purpose annotation used to map HTTP requests to handler methods. It can be applied at both class and method level and supports multiple HTTP methods. 🔹 @GetMapping Specifically designed for handling HTTP GET requests. It makes the code more readable and is commonly used for fetching data from the server. 🔹 @PostMapping Used for handling HTTP POST requests. Ideal when sending data from client to server, such as form submissions or creating new records. Why use specific mappings? Using @GetMapping, @PostMapping, etc., improves code clarity and makes APIs more expressive compared to using @RequestMapping for everything. In real projects, choosing the right mapping annotation helps in building clean and maintainable REST APIs. #SpringBoot #Java #BackendDevelopment #RESTAPI #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
🔄 Spring Bean Lifecycle – From Creation to Destruction While working with Spring, one concept that really helped me understand how things run internally is the Bean Lifecycle. A Spring Bean goes through multiple stages from the moment it is created till it gets destroyed. Knowing this flow makes debugging and customization much easier. 👉 1. Instantiation Spring container creates the bean instance using constructor or factory method. 👉 2. Dependency Injection All required dependencies are injected (via constructor/setters/fields). 👉 3. Initialization Spring calls lifecycle callbacks like: @PostConstruct InitializingBean.afterPropertiesSet() custom init-method 👉 4. Bean Ready for Use Now the bean is fully initialized and ready to serve the application. 👉 5. Destruction Before removing the bean, Spring calls: @PreDestroy DisposableBean.destroy() custom destroy-method 💡 Why it matters? Understanding lifecycle hooks allows better control over resource management, logging, and custom initialization logic. 📌 For me, learning this made Spring feel less like “magic” and more predictable. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #LearningJourney
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
-
-
New to Spring Boot? You'll see these annotations in every project. Here's what they actually do: @SpringBootApplication → Entry point. Combines @Configuration, @EnableAutoConfiguration, @ComponentScan @RestController → Marks a class as an HTTP request handler that returns data (not views) @Service → Business logic layer. Spring manages it as a bean @Repository → Data access layer. Also enables Spring's exception translation @Autowired → Inject a dependency automatically (prefer constructor injection instead) @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → Maps HTTP methods to your handler methods @RequestBody → Deserializes JSON from request body into a Java object @PathVariable → Extracts values from the URL path Bookmark this. You'll refer back to it constantly. Which annotation confused you the most when starting out? 👇 #Java #SpringBoot #Annotations #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
Day 84 of 100 — Logging with SLF4J & Logback in Spring Boot 📌 Objective Today I learned how to implement logging in Spring Boot using SLF4J and Logback to track application behavior, debug issues, and monitor performance. 🚀 What is Logging? Logging is used to record application events such as: ✔ Errors ✔ Debug information ✔ Application flow ✔ System activities 🌱 What is SLF4J? SLF4J (Simple Logging Facade for Java) is a logging API that provides a standard interface for different logging frameworks. ✔ Decouples logging implementation ✔ Supports multiple logging frameworks 🌱 What is Logback? Logback is the default logging framework used in Spring Boot. ✔ High performance ✔ Flexible configuration ✔ Supports file & console logging 📘 Using Logger in Spring Boot import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RestController public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @GetMapping("/test") public String test() { logger.info("Test API called"); logger.debug("Debugging information"); logger.error("Error occurred"); return "Logging working!"; } } 📊 Log Levels Level. Purpose TRACE. Detailed information DEBUG. Debugging INFO. General info WARN. Warning ERROR. Errors ⚙️ Configuration (application.properties) Properties logging.level.root=INFO logging.level.com.example=DEBUG 📁 Log Output Example INFO - Test API called DEBUG - Debugging information ERROR - Error occurred 🧠 What I Learned ✔ Importance of logging in applications ✔ Difference between SLF4J and Logback ✔ Using Logger in Spring Boot ✔ Managing log levels for debugging and monitoring 💬 Post Description Day 84 of my 100 Days of Code Challenge! Today I implemented logging in Spring Boot using SLF4J and Logback. Logging helps track application behavior, debug issues, and improve system monitoring. #Day84 #100DaysOfCode #SpringBoot #Logging #SLF4J #Logback #JavaBackend #BackendDevelopment #CodingJourney #LearnJava
To view or add a comment, sign in
-
-
🚀 30 Days of Spring Boot – Day 2 Today I explored one of the core foundations of Spring — Beans & Their Management. 🔹 What I learned: ✅ Spring Bean A Bean is a Java object managed by the Spring IoC container. Instead of creating objects using new, Spring handles creation, lifecycle, and dependency injection. ✅ @Bean Annotation Used to manually define a Bean inside a @Configuration class. It gives full control over object creation — especially useful for third-party classes or custom configurations. 💡 Even though we use new inside a @Bean method, it is executed only once by Spring (Singleton scope by default) and reused across the application. ✅ Bean Scope Defines how many instances Spring creates: Singleton → Single shared instance (default) Prototype → New instance every time Request → Per HTTP request Session → Per user session 🔥 Key Takeaway: “Write new once, let Spring manage and reuse the object everywhere.” 📌 Strengthening fundamentals step by step. #SpringBoot #Java #BackendDevelopment #LearningJourney #100DaysOfCode #Microservices
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