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>

How Do I Build My First AI Application with Spring AI?

In Part 1, you will build a Spring Boot API that answers questions about Java. Send a question to POST /api/ask, and Spring AI’s ChatClient will pass it to an OpenAI chat model. The endpoint returns the model’s answer as JSON.

Set up the project

Use JDK 25, Maven 3.9 or later, and an OpenAI API key with access to gpt-4o-mini. Copy the complete Maven POM at the end of this article into an empty project directory. The example uses Spring Boot 4.1.2 and Spring AI 2.0.2.

Create an OpenAI API key

  1. Sign in to the OpenAI Platform API Keys page.
  2. Select your project, then click Create new secret key. You can name it kodejava-spring-ai.
  3. Copy the secret key and store it securely. The platform displays the full key only when you create it.

API usage is billed separately from ChatGPT Plus. To enable paid API usage, add a payment method in API Billing.

Configure the chat model

Create 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

Spring Boot reads the API key from the environment. Keep it out of source control. The loopback address makes the endpoint accessible on your own machine.

Create the application

Save the following class in 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);
    }
}

Create the REST controller

Save the controller in src/main/java/org/kodejava/springai/JavaAssistantController.java:

package org.kodejava.springai;

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 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 answer = chatClient.prompt()
                .system("You are a Java tutor. Explain concepts in plain English.")
                .user(request.question())
                .call()
                .content();

        return new AskResponse(answer);
    }

    public record AskRequest(String question) {}

    public record AskResponse(String answer) {}
}

Spring AI supplies the ChatClient.Builder, and the controller uses it to create a client once. The system message describes how the model should answer. The user message contains the question. The call().content() chain gets the model’s text synchronously, and Spring MVC serializes the response record as JSON.

A missing or blank question field returns HTTP 400 before the controller calls the model. Each request is independent, so include the topic when asking a follow-up question.

Run the application

On macOS or Linux:

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

Run Maven in the same terminal where you set the key. Then open a second terminal to send a request:

curl http://127.0.0.1:8080/api/ask \
  -H 'Content-Type: application/json' \
  -d '{"question":"What is the difference between List and Set in Java?"}'

A possible response:

{
  "answer": "A List is ordered and allows duplicate elements. A Set contains unique elements. Its iteration order depends on the implementation."
}

The exact wording can vary. Try sending {"question":" "} to check the HTTP 400 response.

In Part 2, you will use a prompt template to adapt the explanation to the reader’s skill level.

References

Maven artifacts

The Spring Boot parent manages the Web MVC starter and Maven plugin versions. The Spring AI BOM manages the OpenAI starter version.

<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>