AI Hints
Home›Spring Boot Tutorial›Why Validate, Bean Validation and @Valid
Spring Boot · Lesson 74 of 120

Bean Validation

Rules as annotations.

⏱ 2 min read▶ Video at 1:39:43🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Writing if statements for every field is boring, and easy to forget. Bean validation lets us write the rules as annotations, right on the fields.

  • No more if statements
  • Rules as annotations
  • Right on the fields

Common constraints

Not Null means the value must be present. Not Blank means text must have real characters. Size limits the length. Min and max limit numbers, and Positive means above zero. Email checks the format. And Pattern checks text against a regular expression.

AnnotationRule
@NotNullmust be present
@NotBlanktext with real characters
@Size(max = 50)length limits
@Min / @Max / @Positivenumber limits
@Emaillooks like an email
@Pattern(regexp = ...)matches a pattern

A record with rules

Title must not be blank. Author must not be blank, and at most fifty characters. Price must be positive, and at most five hundred. Year must be between nineteen hundred, and twenty one hundred. And contact must look like an email.

NewBook.javajava
public record NewBook(
    @NotBlank String title,
    @NotBlank @Size(max = 50) String author,
    @Positive @Max(500) double price,
    @Min(1900) @Max(2100) int year,
    @Email String contact
) {}

Where the rules come from

These annotations are part of Jakarta Validation, a Java standard. Hibernate Validator is the library that checks them. In Spring Initializr, add the Validation dependency, and Spring Boot sets it all up.

keyvalue
StandardJakarta Validation
EngineHibernate Validator
Dependencyspring-boot-starter-validation
Setupautomatic

Summary

Constraint annotations like Not Blank, Size, Positive, and Email describe the rules, right on the fields. Next, turning them on with at Valid.

Key takeaways
  • @NotBlank, @Size
  • @Positive, @Min, @Max
  • @Email, @Pattern
Next up: @Valid — check the request body