Master Java Validation: @NotNull, @NotBlank, @NotEmpty, @Valid vs @Validated
This article explains the differences and proper usage of Java validation annotations such as @NotNull, @NotBlank, @NotEmpty, and compares @Valid with @Validated in Spring Boot applications, providing code examples and import details for effective data validation.
1. Add Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>The validation annotations are located in
import javax.validation.constraints.*;2. Annotation Differences
@NotNull
Applicable to basic data types (Integer, Long, Double, etc.). When used on a String, it only forbids null values, but empty strings are allowed.
Note: Fields annotated with @NotNull can also use @Size, @Max, @Min for value constraints.
@NotBlank
Applicable to String types; the value cannot be null and must contain at least one non‑whitespace character after trim().
@NotEmpty
Applicable to String, collections, maps, arrays, etc.; the value cannot be null or have a length of zero.
3. Usage Example
@Data
public class BigPeople {
@ApiModelProperty(value = "id", required = true)
@NotNull(message = "id cannot be null")
@Length(message = "id length cannot exceed {max}", max = 10)
private Integer id;
@ApiModelProperty(value = "name", required = true)
@NotBlank(message = "name cannot be blank")
@Size(message = "name max length is {max}", max = 10)
private String name;
@ApiModelProperty(value = "age", required = true)
@NotNull(message = "age cannot be null")
@Range(message = "age must be between {min} and {max}", min = 5, max = 10)
private Integer age;
@ApiModelProperty(value = "treeNode", required = true)
@NotEmpty(message = "treeNode cannot be empty")
private List<String> treeNode;
}Import statements for validation groups:
import javax.validation.Valid; import org.springframework.validation.annotation.Validated;4. Controller Methods
@ApiOperation(value = "Add or update a person's information")
@PostMapping("/updateOrInsert")
public Result updateOrInsert(@Valid @RequestBody Person person) {
Boolean success = personService.updateOrInsert(person);
if (success) {
return new Result(ResultCode.SUCCESS, success);
}
return new Result(ResultCode.ERROR, "Failed to add or update person");
}
@ApiOperation(value = "Add or update a person's information")
@PostMapping("/updateOrInsert")
public Result updateOrInsert(@Validated @RequestBody Person person) {
Boolean success = personService.updateOrInsert(person);
if (success) {
return new Result(ResultCode.SUCCESS, success);
}
return new Result(ResultCode.ERROR, "Failed to add or update person");
}The three annotations above must be used together with @Valid or @Validated to trigger validation of controller input parameters.
5. @Valid vs @Validated Comparison
1. Both trigger validation of fields annotated with constraints such as @NotNull, @NotEmpty, etc.
2. @Valid requires a BindingResult to capture validation results; if validation fails and the result is not returned, the method continues execution.
3. @Validated throws a 400 error automatically when validation fails, halting method execution; a global exception handler is needed to return custom error messages.
4. Overall, @Validated is more convenient because it reduces boilerplate code and makes the method signature cleaner.
6. Other Common Validation Annotations
Additional annotations in the javax.validation.constraints package can be used for size, range, pattern matching, and more.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
