Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Configuration and Validation

Bean Validation in Micronaut

Validate request bodies, parameters and configuration with Jakarta Bean Validation in Micronaut: constraints, @Valid, @Validated, custom constraints and error responses.

Never trust input. A request body might have a blank name, a negative quantity or an email that is not an email. If you check these by hand in every controller you will forget one. Micronaut integrates the Jakarta Bean Validation standard (annotations such as @NotBlank and @Min) so that you declare rules once, on the data, and the framework enforces them.

The real Micronaut code is read-only on this site. The runnable examples build a tiny validator with Java annotations and reflection that behaves like the real one, so you can experiment with constraints and error messages.

Setting it up

Add the micronaut-validation module (plus the processor for annotation processing) to your build. In a Gradle project that looks like:

GROOVY
annotationProcessor("io.micronaut.validation:micronaut-validation-processor")
implementation("io.micronaut.validation:micronaut-validation")

Micronaut Validation does most of its work at compile time: instead of reflecting over fields at runtime, it generates the checking code during compilation. That is faster and, importantly, compatible with GraalVM native images.

Constraining a bean

Put constraint annotations on the fields or record components of a request type:

Java
import io.micronaut.core.annotation.Introspected;
import jakarta.validation.constraints.*;

@Introspected
public record NewNote(
        @NotBlank @Size(max = 80) String title,
        @NotBlank String body,
        @Min(1) @Max(5) int priority,
        @Email String notifyEmail) {}

Common constraints:

Annotation Meaning
@NotNull value must not be null
@NotBlank text has at least one non-space character
@NotEmpty collection or string is not empty
@Size(min, max) length of text or collection
@Min, @Max numeric bounds
@Positive, @PositiveOrZero sign of a number
@Pattern(regexp) text matches a regular expression
@Email looks like an email address
@Past, @Future date constraints

@Introspected tells Micronaut to generate metadata for the type at compile time, which is what the validator uses.

Validating requests

On a controller, add @Valid to the body and the framework rejects bad input before your method runs:

Java
import io.micronaut.http.annotation.*;
import io.micronaut.http.HttpStatus;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.validation.Validated;
import jakarta.validation.Valid;

@Validated
@Controller("/notes")
class NoteController {

    @Post
    @Status(HttpStatus.CREATED)
    Note create(@Body @Valid NewNote body) {
        return service.save(body);
    }

    @Get("/{id}")
    Note get(@PathVariable @Min(1) long id) {
        return service.find(id);
    }
}

Parameters can carry constraints too (@Min(1) long id). The class-level @Validated enables checks on method parameters and return values. A violation produces an HTTP 400 response in the standard JSON error shape, listing each failing field and message.

Services and configuration

Validation is not just for controllers. Any bean can be validated: annotate the class with @Validated and the method parameters with constraints, and a violation throws jakarta.validation.ConstraintViolationException. Typed configuration classes can use the same annotations, which means a misconfigured port or missing URL stops the application at startup:

Java
@ConfigurationProperties("app.mail")
public record MailSettings(@NotBlank String host, @Min(1) @Max(65535) int port) {}

Custom constraints

Micronaut lets you write a constraint as a simple bean-based check without defining a full annotation and validator pair. Use ConstraintValidator with a @Singleton, or the @Constraint annotation with a factory bean:

Java
import jakarta.inject.Singleton;
import io.micronaut.validation.validator.constraints.ConstraintValidator;

@Singleton
class SlugValidator implements ConstraintValidator<Slug, String> {
    @Override
    public boolean isValid(String value, AnnotationValue<Slug> annotation,
                           ConstraintValidatorContext context) {
        return value == null || value.matches("[a-z0-9]+(-[a-z0-9]+)*");
    }
}

By convention, a null value is considered valid by custom constraints, so you combine them with @NotNull; this keeps each rule about one thing.

Try it: a miniature validator

This stand-in uses runtime annotations and reflection. Real Micronaut generates equivalent code at compile time, but the behaviour you see (all violations collected, grouped per field) is the same idea.

Java Collecting violations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: turning violations into a 400 response

A good API returns an error that a client can show. This stand-in turns the violations into a small JSON-like body and picks the status code, which is what Micronaut's built-in exception handler does for you.

Java From violations to a response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Validate at the edge (controllers and configuration) and keep your domain code free from repeated checks. A client then sees all problems in one response instead of fixing them one at a time.

Common mistakes

  • Forgetting @Valid on @Body: the constraints on the record are silently ignored.
  • Using @NotNull on text when you mean @NotBlank; an empty string passes @NotNull.
  • Forgetting @Introspected (or the annotation processor) on types that are validated, which leaves nothing for the validator to inspect.
  • Putting business rules, such as "stock must be available", into annotations. Those depend on state, so they belong in service code that throws a proper exception.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Micronaut Validation do at compile time?

    Compile-time processing makes validation fast and compatible with native images.
  2. 2. Which constraint rejects the empty string and a string of spaces?

    @NotBlank requires at least one non-whitespace character.
  3. 3. What must you add to a controller parameter so the body's constraints are checked?

    @Valid on the @Body parameter triggers cascading validation of the object.
  4. 4. What is the normal HTTP status when request validation fails?

    A constraint violation is the client's mistake, so the response is 400 Bad Request with the failing paths.
  5. 5. Which rule does NOT belong in an annotation?

    Stock depends on changing data, so it is a business rule handled in service code.

Summary

  • Declare rules with Jakarta annotations on records and parameters; @Valid and @Validated switch checking on.
  • Micronaut generates validation code at compile time (@Introspected).
  • Violations become a 400 response; services throw ConstraintViolationException.
  • Configuration classes can be validated too, so bad settings stop startup.
  • Keep state-dependent business rules in code, not annotations.

Next: Security Fundamentals