How Do I Use Prompt Templates in Spring AI?

In Part 1, you built a Java assistant with POST /api/ask. Its instructions were the same for every reader. In this example, you will add a level field so a beginner receives a simpler explanation while an advanced reader receives more technical detail.

A prompt template is text with named placeholders. Spring AI fills those placeholders before sending the messages to the model. This is useful when the structure stays the same but some instructions change between requests.

Set up the project

Continue with the package org.kodejava.springai and the endpoint from Part 1. Use JDK 25 and Maven 3.9 or later. This article keeps Spring Boot 4.1.2 and Spring AI 2.0.2.

Use the complete POM at the end of this article. It uses spring-boot-starter-webmvc for the Spring Boot 4 servlet application and imports spring-ai-bom to manage the Spring AI dependencies.

Configure the model

Create or replace src/main/resources/application.properties:

server.address=127.0.0.1
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.model=gpt-4o-mini

Use an OpenAI API key with access to the selected model. Set it in the environment of the terminal running Maven. Never put a real key in this file, the POM, a request body, or a Git commit. If your account cannot use this model, select an available chat model through the same property.

The chat.model property selects the OpenAI chat model in Spring AI 2.0, matching the configuration in Part 1.

Keep the application entry point

File: src/main/java/org/kodejava/springai/JavaAssistantApplication.java

package org.kodejava.springai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JavaAssistantApplication {
    public static void main(String[] args) {
        SpringApplication.run(JavaAssistantApplication.class, args);
    }
}

Add a skill-level prompt template

Replace src/main/java/org/kodejava/springai/JavaAssistantController.java with:

package org.kodejava.springai;

import java.util.Locale;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
public class JavaAssistantController {
    private static final String SYSTEM_TEMPLATE = """
            You are a Java tutor teaching Java 25 in plain English.
            The reader's skill level is {level}.
            Follow these teaching instructions: {guidance}
            Include one short Java example when useful.
            Answer the Java question in the user message.
            """;

    private final ChatClient chatClient;

    public JavaAssistantController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @PostMapping("/api/ask")
    public AskResponse ask(@RequestBody AskRequest request) {
        if (request.question() == null || request.question().isBlank()) {
            throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST, "Question must not be blank");
        }
        String level = request.level() == null
                ? "beginner"
                : request.level().strip().toLowerCase(Locale.ROOT);
        String guidance = switch (level) {
            case "beginner" ->
                    "Define unfamiliar terms and use a small concrete example.";
            case "intermediate" ->
                    "Assume knowledge of classes and collections; explain tradeoffs.";
            case "advanced" ->
                    "Discuss relevant contracts, edge cases, and design implications.";
            default -> throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST,
                    "Level must be beginner, intermediate, or advanced");
        };

        String answer = chatClient.prompt()
                .system(system -> system.text(SYSTEM_TEMPLATE)
                        .param("level", level)
                        .param("guidance", guidance))
                .user(request.question())
                .call()
                .content();
        return new AskResponse(answer);
    }

    public record AskRequest(String question, String level) {}

    public record AskResponse(String answer) {}
}

{level} and {guidance} are placeholders. The param() calls supply their values. The lambda passed to system() configures one system message; it does not make a separate model call. Spring AI’s ChatClient uses prompt templating internally, so you do not need to create a separate PromptTemplate object here.

The question remains a separate user message. Send it through .user(request.question()) as ordinary text: do not concatenate it into the system template. This also makes questions containing Java braces easier to handle without treating them as template source.

The level is validated before the model call. Omitting it or sending null selects beginner, preserving the original one-field request. An empty level is rejected. Locale.ROOT makes case normalization independent of the machine’s locale.

The application chooses the teaching instructions from a fixed set. A caller cannot supply arbitrary guidance. Prompt instructions still do not guarantee accuracy or prevent every attempt to redirect a model; review generated Java code before using it.

Run the application

From the folder containing pom.xml, check the tools:

java -version
mvn -version

Both should report Java 25. Build with mvn clean package.

In Bash on Linux or macOS, read the key without adding it to shell history:

read -r -s -p 'OpenAI API key: ' OPENAI_API_KEY
printf '\n'
export OPENAI_API_KEY
mvn spring-boot:run

In PowerShell 7.2 or later:

$env:OPENAI_API_KEY = Read-Host 'OpenAI API key' -MaskInput
mvn spring-boot:run

The key is still held in the process environment; masking prevents it from being displayed while entering it. Stop the app with Ctrl+C. Clear the value afterward with unset OPENAI_API_KEY in Bash or Remove-Item Env:OPENAI_API_KEY in PowerShell.

Compare explanations

Open a second terminal. In a Unix shell:

curl -i http://127.0.0.1:8080/api/ask \
  -H 'Content-Type: application/json' \
  -d '{"question":"How does a HashSet detect duplicates?","level":"beginner"}'

In PowerShell:

$body = @{
    question = 'How does a HashSet detect duplicates?'
    level = 'beginner'
} | ConvertTo-Json
Invoke-RestMethod -Uri 'http://127.0.0.1:8080/api/ask' `
    -Method Post -ContentType 'application/json' -Body $body

A possible HTTP 200 body is:

{"answer":"A HashSet stores unique elements. It uses hashCode() to help find where an element belongs, then equals() to compare elements when needed. Adding the same String twice leaves one copy."}

Repeat with advanced. You might receive a discussion of the equals() / hashCode() contract, collisions, and mutable keys. The response still has one answer field; wording and example code vary between calls. The level guides the model rather than enforcing a measurable difficulty score.

Check these cases with either client:

Request body Expected result
{"question":"What is a record?"} HTTP 200, beginner guidance
{"question":"What is a record?","level":"ADVANCED"} HTTP 200, advanced guidance
{"question":"What is a record?","level":"expert"} HTTP 400, no model call
{"question":" ","level":"beginner"} HTTP 400, no model call

Do not rely on an exact error JSON body: Spring Boot error settings affect which details are exposed. Invalid JSON is also rejected by Spring MVC before this method executes.

A 401 from the provider usually requires checking the API key. For a model-access error, check the model setting and your account permissions. A 429 requires checking provider rate limits or billing. Avoid printing your key while troubleshooting.

Try it yourself

Ask the same question at all three levels. Compare whether unfamiliar terms are defined and whether the advanced answer adds useful edge cases. Then change the beginner guidance to request an analogy and repeat. Keep expectations about HTTP status and JSON shape separate from expectations about generated wording.

Part 3 will cover How Do I Map Structured AI Output to Java Records? Later articles will introduce Ollama, document question answering with PostgreSQL vector search, and Java tool calling before moving to evaluation and operational concerns.

References

Maven artifacts

File: pom.xml. Maven Central is sufficient; no milestone repository is needed. The Boot parent manages the web starter and build plugin, and the AI BOM manages the OpenAI starter.

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.2</version>
        <relativePath/>
    </parent>
    <groupId>org.kodejava</groupId>
    <artifactId>spring-ai-java-assistant</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>25</java.version>
        <spring-ai.version>2.0.2</spring-ai.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-openai</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.