Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring AI structured output: validate the parsed object before any write

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A model-produced object can satisfy a JSON shape while still violating business rules, access rules or current state.

Download Spring source kit

Parse, then validate

Suppose a model extracts a receipt reservation request with receipt ID RC-47 and seven units. Parsing into a Java record establishes shape, not permission or stock availability. Apply Bean Validation, verify caller scope and tenant, check the current version, then perform a guarded write. A negative quantity, stale version or receipt outside the caller's tenant must fail even if the model returns syntactically perfect JSON. Request validation is the same distinction at an HTTP boundary.

Keep the model out of the commit path

Do not make a database transaction wait for a remote model response. Accept model output as proposed input, show it for review when the action is sensitive, then execute a separate idempotent command. Structured-output support and provider behavior differ; the current source kit does not verify a model's schema adherence.

Boundary sketch

Java
record ReservationDraft(String receiptId, int units, long expectedVersion) {}
ReservationDraft draft = parsedModelOutput;
if (draft.units() <= 0 || draft.units() > 47) {
    throw new InvalidReservationException();
}
receiptService.reserveForTenant(caller.tenantId(), draft.receiptId(),
    draft.units(), draft.expectedVersion(), replayKey);

Cost and verification

Validation is cheap compared with a model call. A review step adds user latency but prevents uninspected model output from becoming a durable mutation. This sketch is not executed by the current Spring source kit; verify it against the chosen dependencies and deployment.

Common Mistakes

  • Do not equate schema-conforming JSON with an authorized command.
  • Do not hold a database transaction open during model generation.
  • Do not silently retry a write when parsing or network response is uncertain.

Read next

Spring MVC validation errors: one public ProblemDetail for two failure paths, Spring AI tools: authorize each requested action after model selection, Spring JDBC versioned tenant update: inspect the affected row count, Spring POST idempotency keys: bind replay to tenant and command.

spring
spring-boot
spring-ai
ai-structured-output
Storage details