Spring AI 2.0 tutorial: guardrails and PII masking

Learn four Spring AI guardrail approaches, including case-sensitive filter limits, response checks for secrets, and regex masking before model calls.

Player not loading? Watch on YouTube

Dan Vega builds a Java application to demonstrate four ways to protect data with Spring AI. The setup uses Maven, Spring Boot 4.1.0, Spring AI 2.0 and JDK 26. Vega says the model abstraction lets the application use a local LLM or a hosted provider without changing the application code.

The first example gives a banking assistant a system prompt that limits its answers to banking topics. A question about Ohio's capital receives the configured refusal. Next, SafeGuardAdvisor blocks input containing a configured substring. The demonstration exposes two limitations: a harmless Java question containing "pass" gets blocked, while a change in letter case lets a password question reach the model.

A custom advisor checks model responses for a secret discount code using lowercase comparisons. It catches the code after the model reconstructs it from spaced input and replaces the response before it reaches the caller. This example checks output, despite the source chapter's input-rail label.

The final advisor uses regular expressions to mask email addresses, credit card numbers and social security numbers before a model call. SimpleLoggerAdvisor exposes request and response text, so advisor order matters when checking what enters the logs. The demonstrated masked request still contains the person's name; the example does not establish that every kind of personal information has been removed. The custom advisors shown implement blocking calls, with stream support discussed separately.