The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • Others
          • Views
          • Indexing - TBU
          • Transactions - TBU
          • Triggers - TBU
      • Vendor-Specific Concepts
        • Oracle Specific
          • Rownum vs Rowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
      • Other Commands
    • Workflows
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism and Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
        • Service Layer (Business Logic)
        • Repository Layer (Data Access)
        • Dependency Injection & Configuration
        • Validation & Binding
        • Caching
        • AOP (Aspect-Oriented Programming)
        • Scheduling
        • Testing - TBU
        • Security
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
        • Apache Camel - TBU
          • Local Docker Setup for SFTP Server
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
        • Context Propagation - TBU
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Distributed Tracing
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Low-Level Design (LLD)
      • Programming Paradigms
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Enhancements
        • Fluent API Design
          • Examples
    • High-Level Design (HLD)
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Architecture
        • Event Driven Architecture
          • Event-Driven Microservices
          • Handling Failures & Retry Mechanisms
          • Event Schema Design (Avro, JSON, Protobuf)
          • Persistence & Non-Persistence Queues
          • Technologies & Frameworks
            • ActiveMQ - TBU
            • Kafka - TBU
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 1 - Maths theory & Pattern
          • Set 2 - Arrays
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • General Interview Preparation Tips - TBU
      • Flowchart - How to Solve Coding Problem?
  • Personal Projects
    • Hackathon
Powered by GitBook
On this page
  • About
  • Why is Jakarta Bean Validation important in Spring ?
  • Jakarta Bean Validation Components
  • 1. Constraint Annotations
  • 2. Meta Annotations
  • 3. Interfaces
  • 4. Bootstrap API
  • How Spring Integrates with Jakarta Validation ?
  • Spring Validation Flow
  • 1. Controller-level Validation on @RequestBody DTO
  • 2. Controller-level Validation on @RequestParam, @PathVariable
  • 3. Nested (Recursive) Validation with @Valid
  • 4. Service-layer (Method-level) Validation using @Validated
  • 5. Validation Groups Internally
  • 6. Manual Validation using Validator
  • When and How Validation is Triggered ?
  • Example
  • How to Trigger Validation ?
  • Validation Groups
  • Custom Constraints
  • 1. Define annotation
  • 2. Implement logic
  • 3. Use it in our bean

Was this helpful?

  1. Spring
  2. General Concepts
  3. Validations in Spring Framework

Jakarta Validation

About

Bean Validation is a standard framework for declaring and enforcing validation rules on JavaBeans (POJOs) using annotations. It provides a way to validate the state of objects either automatically (e.g., during web requests in Spring) or manually (programmatically).

It originated as JSR-303, evolved to JSR-380 (Bean Validation 2.0), and now resides under the Jakarta EE umbrella as jakarta.validation.

This API does not implement validation logic itself. It defines metadata (annotations) and interfaces. The actual logic is implemented by a provider, most commonly Hibernate Validator.

Why is Jakarta Bean Validation important in Spring ?

  • It integrates seamlessly with Spring Web MVC and Spring Boot.

  • It supports both automatic validation of controller inputs and manual validation in service layers.

  • It enables declarative and reusable constraint definitions.

  • It standardizes validation across frameworks and layers.

Jakarta Bean Validation Components

1. Constraint Annotations

These are placed on class fields or method parameters:

  • @NotNull: Value must not be null.

  • @NotEmpty: Value must not be null or empty (for strings, collections).

2. Meta Annotations

  • @Constraint: Used when defining custom constraints.

  • @Valid: Triggers recursive validation on associated objects or collections.

3. Interfaces

  • jakarta.validation.Validator: The core interface to validate beans.

  • jakarta.validation.ConstraintValidator<A extends Annotation, T>: Interface for implementing custom constraint logic.

  • jakarta.validation.ConstraintViolation<T>: Represents a single validation error.

4. Bootstrap API

  • Validation.buildDefaultValidatorFactory() creates a ValidatorFactory which provides a Validator.

How Spring Integrates with Jakarta Validation ?

When jakarta.validation (or javax.validation) API and a provider like Hibernate Validator is on the classpath, Spring Boot auto-configures:

  • LocalValidatorFactoryBean: A Spring Validator that delegates to Jakarta Validator.

  • MethodValidationPostProcessor: Enables method-level validation using @Validated.

Dependencies

<!-- Required for Bean Validation -->
<dependency>
  <groupId>org.hibernate.validator</groupId>
  <artifactId>hibernate-validator</artifactId>
</dependency>

Spring Boot starter spring-boot-starter-web includes Hibernate Validator by default.

Spring Validation Flow

Spring integrates with the Jakarta Bean Validation API via the LocalValidatorFactoryBean and auto-wires it as a global validator.

There are two major validation triggers in Spring:

  1. Method-level validation (Spring MVC controllers, service beans, etc.)

  2. Manual (programmatic) validation using Validator

Spring internally:

  • Detects the @Valid or @Validated annotations

  • Delegates to the jakarta.validation.Validator interface (via Hibernate Validator)

  • Collects ConstraintViolations and throws exceptions like:

    • MethodArgumentNotValidException (for body-bound beans)

    • ConstraintViolationException (for method parameter validation)

    • BindException (for form data)

1. Controller-level Validation on @RequestBody DTO

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public class UserDto {

    @NotBlank(message = "Username must not be blank")
    @Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters")
    private String username;

    @NotBlank(message = "Email must not be blank")
    @Email(message = "Email must be a well-formed email address")
    private String email;

    // Constructors
    public UserDto() {}

    public UserDto(String username, String email) {
        this.username = username;
        this.email = email;
    }

    // Getters and Setters
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody UserDto userDto) {
    return ResponseEntity.ok("Created");
}

Internal Workflow:

  1. Deserialization: JSON request body is deserialized into UserDto using Jackson.

  2. Validation Trigger: Spring detects @Valid on the parameter.

  3. Validator Bean: Calls validator.validate(userDto) using LocalValidatorFactoryBean.

  4. Hibernate Validator executes all constraints like @NotBlank, @Email.

  5. Failure: If constraints fail:

    • Spring throws MethodArgumentNotValidException.

    • Handled globally with @ExceptionHandler or @ControllerAdvice.

Example:

POST /users
{
  "username": "",
  "email": "abc"
}

Response:

{
  "status": 400,
  "errors": [
    {"field": "username", "message": "Username must not be blank"},
    {"field": "email", "message": "Email must be a well-formed email address"}
  ]
}

2. Controller-level Validation on @RequestParam, @PathVariable

@GetMapping("/users/{id}")
public ResponseEntity<?> getUser(@PathVariable @Positive Long id) {
    ...
}

Internal Workflow:

  • Uses method-level validation.

  • Triggers via Spring’s MethodValidationPostProcessor.

  • Detects @Validated on the class or method.

  • Calls executableValidator.validateParameters(...)

  • If invalid: throws ConstraintViolationException.

Important: @Validated must be applied at class level for method parameter validation:

@RestController
@Validated
public class UserController { ... }

3. Nested (Recursive) Validation with @Valid

public class OrderDto {
    @Valid
    private AddressDto address;

    @Valid
    private List<ItemDto> items;
}

Internal Workflow:

  • During traversal, Spring checks if a field has @Valid.

  • If yes, it descends into that object and applies all constraints.

  • Recursion happens automatically.

public class ItemDto {
    @NotNull
    private String name;
}

If one ItemDto has null name, it’s picked up as a nested constraint violation.

4. Service-layer (Method-level) Validation using @Validated

Service-layer validation using @Validated allows us to validate method parameters or return values in any Spring-managed bean—especially in the service layer, where we might not rely on Spring MVC controller-level validation. It’s part of the Method Validation feature provided by Jakarta Bean Validation and integrated into Spring via proxies.

When we annotate a class with @Validated, Spring uses AOP (Aspect-Oriented Programming) to create a proxy that intercepts method calls and performs validation before the actual method runs. Internally, Spring uses the MethodValidationPostProcessor bean which wraps beans with a proxy capable of method validation.

Execution Flow:

  1. Spring boot automatically registers a MethodValidationPostProcessor.

  2. We annotate our class with @Validated.

  3. Spring creates a proxy of the class.

  4. Before executing our method, Spring uses the ExecutableValidator to:

    • Validate method parameters

    • Optionally validate the return value

  5. If validation fails, Spring throws a ConstraintViolationException.

Example

@Service
@Validated
public class UserService {

    public void registerUser(@NotBlank String name, @Min(18) int age) {
        // Business logic
    }

    public @NotNull String findUsernameById(@Positive Long id) {
        return "john_doe";
    }
}

Calling code:

userService.registerUser("", 15);

Result:

Spring will throw a ConstraintViolationException because:

  • name is blank (@NotBlank)

  • age is less than 18 (@Min(18))

5. Validation Groups Internally

public class UserDto {
    @NotNull(groups = Update.class)
    private Long id;

    @NotBlank(groups = {Create.class, Update.class})
    private String name;
}

How It Works:

  • Spring detects group classes passed in @Validated(Update.class)

  • Passes these group classes to the validator:

    validator.validate(userDto, Update.class)
  • Only the constraints in that group are applie

6. Manual Validation using Validator

javaCopyEdit@Autowired
private Validator validator;

public void checkUser(UserDto user) {
    Set<ConstraintViolation<UserDto>> violations = validator.validate(user);

    for (ConstraintViolation<UserDto> violation : violations) {
        System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
    }
}

When and How Validation is Triggered ?

If I Add Jakarta Validation Annotations to a DTO and Populate It — Will Constraints Be Checked Automatically?

No, the constraints will not be checked automatically just because we annotated our DTO with validation annotations (like @NotBlank, @Email, etc.). They are only enforced when explicitly triggered — either:

  • By Spring (e.g., using @Valid, @Validated)

  • Or manually by calling Validator.validate(...)

Example

1. DTO With Constraints

public class UserDto {
    @NotBlank
    private String name;

    @Email
    private String email;

    // getters and setters
}

2. Populating DTO Manually

UserDto user = new UserDto();
user.setName("");                 // Invalid: @NotBlank violated
user.setEmail("not-an-email");   // Invalid: @Email violated

System.out.println(user.getName()); // This prints "" without any error

What Happens Here?

  • Nothing is validated at this point.

  • Java doesn't throw errors just because annotations exist — they’re metadata.

  • The validation must be explicitly triggered.

if you have a custom class (e.g., an entity or DTO) annotated with Jakarta validation constraints, those constraints do nothing unless validation is explicitly triggered.

How to Trigger Validation ?

Option A: Manual Trigger

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<UserDto>> violations = validator.validate(user);

for (ConstraintViolation<UserDto> v : violations) {
    System.out.println(v.getPropertyPath() + ": " + v.getMessage());
}

This will print:

name: must not be blank
email: must be a well-formed email address

Option B: Automatically via Spring

When used in a Spring controller or service, Spring triggers validation for us.

Controller:

@PostMapping("/create")
public ResponseEntity<?> createUser(@Valid @RequestBody UserDto userDto) {
    ...
}
  • Spring will call validator.validate(userDto)

  • If any violation, it throws MethodArgumentNotValidException

Validation Groups

By default, all validations belong to the Default group. Groups allow conditional or staged validation.

Define Marker Interfaces

public interface Create {}
public interface Update {}

Apply to Fields

public class User {

    @NotNull(groups = Update.class)
    private Long id;

    @NotBlank(groups = {Create.class, Update.class})
    private String name;
}

Validate with Groups

@PostMapping("/users")
public ResponseEntity<?> create(@Validated(Create.class) @RequestBody User user) {
    ...
}

Spring uses @Validated (from org.springframework.validation.annotation) to support groups. @Valid does not support groups.

Custom Constraints

1. Define annotation

@Constraint(validatedBy = StrongPasswordValidator.class)
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface StrongPassword {
    String message() default "Weak password";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

2. Implement logic

public class StrongPasswordValidator implements ConstraintValidator<StrongPassword, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value != null && value.length() >= 8 && value.matches(".*\\d.*");
    }
}

3. Use it in our bean

@StrongPassword
private String password;
PreviousValidations in Spring FrameworkNextJakarta Bean Validation Annotations

Last updated 1 day ago

Was this helpful?