A prompt template is a reusable prompt structure that combines static instructions with placeholders for values that change between invocations. Spring AI fills those placeholders before sending the completed prompt to an LLM, making complex prompts easier to read and maintain. section 1.3 section 3.1
Build a template incrementally:
- Replace String concatenation with a static template containing placeholders such as {game} and {question}. section 3.1.1
- Pass the template through ChatClient’s user specification and provide each placeholder value with param(). section 3.1.1
- Move the template into a .st file under src/main/resources and inject it as a Spring Resource with @Value. section 3.1.2
- Add instructions and context to guide response behavior, formatting, language, or refusal when the supplied information is insufficient. section 3.6 section 4.4.2
Tabletop-game question template
Define a template such as “Answer this question about {game}: {question}”, then bind the game title and question before calling the LLM. A resource-backed variant can instruct the model to answer only from supplied game rules and return “I don't know” otherwise.
Listing 3.2 Using a prompt template to avoid clumsy String concatenation
package com.example.boardgamebuddy;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
@Service
public class SpringAiBoardGameService implements BoardGameService {
private final ChatClient chatClient;
public SpringAiBoardGameService(ChatClient.Builder chatClientBuilder) { #1
this.chatClient = chatClientBuilder.build(); #2
}
private static final String questionPromptTemplate = """
Answer this question about {game}: {question}
""";
@Override
public Answer askQuestion(Question question) {
var answerText = chatClient.prompt()
.user(userSpec -> userSpec
.text(questionPromptTemplate) #2
.param("gameTitle", question.gameTitle())
.param("question", question.question())) #3
.call()
.content(); #4
return new Answer(question.gameTitle(), answerText);
}
}
Inspect the complete Spring service implementation that replaces concatenated strings with a parameterized prompt template. section 3.1.1




















