Card 01/ 06

ConceptDifficulty: Intermediate1 min

Bean Validation: Constraints Written as Annotations

A rule such as "pickup is required" sits on the field it applies to, instead of in a separate check.

Jakarta Bean Validation is the Java standard for declaring rules about data as annotations on the fields they apply to: @NotBlank on a pickup location, @Min(1) on a passenger count. A validator reads those annotations and reports every field that breaks its rule. In Spring Boot it comes with spring-boot-starter-validation.

A ride request arrives as JSON. Before creating a ride, the service must reject a request with no pickup location or with zero passengers, and tell the client which field was wrong. Written as if statements, that is a separate method that has to be kept in step with the class; as annotations, each rule sits beside its field:

java
record RideRequest(
    @NotBlank(message = "Pickup location is required") String pickup,
    @Min(value = 1, message = "Passengers must be at least 1") int passengers
) {}
Common constraint annotations
AnnotationRequires
@NotNullNot null; says nothing about emptiness
@NotBlankNot null, not empty and not only spaces; for a String
@NotEmptyNot null and not empty; for a String or a collection
@Min / @MaxA number within a bound
@SizeA String, collection or array within a length range
@PatternA String matching a regular expression

The message attribute is the text reported when the rule is broken, so it is written for the client who has to fix the request.

@NotNull is the one that catches people out: an empty string "" passes it, because an empty string is not null. For a required text field, @NotBlank is almost always the right choice.

On their own the annotations are only labels. Nothing checks them until something asks the validator to, and in a Spring controller that something is @Valid, the annotation that tells Spring to validate a parameter before the method runs.