Prompt Engineering with Spring AI – System Prompts, User Prompts and Templates

In Spring AI, prompt engineering is treated as a first-class software engineering discipline rather than simple string concatenation. Instead of passing raw text strings to an AI provider, Spring AI models prompts as structured, multi-message objects managed through dedicated message roles, parameterized templates, and externalized resources.

1. The Prompt and Message Architecture

At its core, Spring AI represents a conversation with an LLM using a Prompt container, which holds an ordered list of Message objects alongside runtime ChatOptions (such as temperature or model overrides).
Because modern LLMs distinguish between instructions, user inputs, and conversation history, Spring AI enforces role separation through four primary Message implementations:
  • System Message (SystemMessage): Sets the high-level behavioral contract, persona, domain boundaries, formatting rules, and operational constraints for the AI. It carries higher instruction priority than user inputs and remains active throughout the interaction.

  • User Message (UserMessage): Represents the end-user’s actual query, task request, or dynamic input data. In addition to text, UserMessage supports multimodal attachments (images, audio, or PDF documents) via Spring AI’s Media abstraction.

  • Assistant Message (AssistantMessage): Represents previous responses generated by the LLM. Supplying prior AssistantMessage and UserMessage pairs enables multi-turn conversational context and few-shot prompting (providing input/output examples to guide model behavior).

  • Tool Response Message (ToolResponseMessage): Carries structured results returned from local Java methods or external APIs back to the LLM during tool/function-calling workflows.

2. System Prompts vs. User Prompts

Separating instructions from untrusted user input is essential for both response quality and security:

Dimension System Prompt (SystemMessage) User Prompt (UserMessage)
Primary Purpose Defines how the AI should behave, act, and format output Defines what specific task or question the AI must answer right now
Lifespan & Scope Persistent across an entire session or configured globally on a ChatClient bean Ephemeral; changes with every individual user request
Content Examples Persona (“You are a senior financial analyst”), tone, language rules, negative constraints (“Do not speculate”) Specific questions, raw text to summarize, documents to analyze, or user parameters
Security Role Establishes guardrails and boundaries against prompt injection Treated as untrusted external input that must adhere to system rules

Default vs. Runtime Overrides in ChatClient

  • Default System Prompts: Configured once when building a ChatClient bean (defaultSystem(...)), ensuring every call made through that client automatically inherits the baseline persona and rules.

  • Runtime Parameterization: Even default system prompts can contain placeholders (e.g., {role} or {language}) that are populated dynamically per request without rewriting the core instruction template.

3. Prompt Templates (PromptTemplate)

Hardcoding prompts with string concatenation becomes unmanageable as prompts grow complex. Spring AI solves this with PromptTemplate, which separates prompt structure from runtime data.

How PromptTemplate Works?

  1. Template Engine: Built on top of the StringTemplate (ST4) engine by default, allowing named placeholders wrapped in curly braces ({variableName}).

  2. Variable Binding: Accepts a Map<String, Object> of key-value pairs at runtime, validating that required placeholders are supplied before rendering the final Prompt or Message.

  3. Specialized Template Variants:

    • SystemPromptTemplate: Renders a SystemMessage directly from parameterized system instructions.

    • AssistantPromptTemplate: Renders an AssistantMessage, useful for constructing dynamic few-shot examples.

    • PromptTemplate: General-purpose template capable of producing a plain string, a UserMessage, or a complete Prompt object.

  4. Custom Delimiters (TemplateRenderer): Because prompts frequently include raw JSON schemas or programming syntax that naturally use { and }, Spring AI allows configuring custom delimiters (such as <variableName> or $variableName$) via StTemplateRenderer to prevent syntax collisions.

4. Externalizing Prompts as Resources

Rather than embedding large prompt texts inside Java classes, Spring AI integrates directly with Spring’s Resource abstraction (classpath:/prompts/...):
  • Clean Separation of Concerns: Prompts are stored as external .st (StringTemplate), .txt, or .md files in src/main/resources.

  • Declarative Injection: Loaded via Spring’s @Value("classpath:/prompts/system-prompt.st") annotation or passed directly as a Resource into ChatClient and PromptTemplate.

  • Operational Benefits: Enables version control diffs on prompt changes, simplifies A/B testing of prompt variations, and allows prompt engineers or domain experts to refine instructions without modifying compiled Java code.

5. Prompt Engineering Best Practices in Spring AI

  • Role & Persona Anchoring: Always define clear expertise, audience level, and tone in the SystemMessage rather than burying them inside the UserMessage.

  • Delimiter Isolation for Untrusted Data: Wrap dynamic user-supplied text inside clear XML-style tags (such as <user_input>...</user_input>) within templates so the LLM clearly distinguishes instructions from data to be processed.

  • Few-Shot Prompting via Message Lists: Instead of describing complex formatting rules purely in prose, supply two or three pairs of sample UserMessage and AssistantMessage objects before the live UserMessage to anchor the expected pattern.

  • Offload Formatting Instructions to Converters: Rather than manually writing verbose JSON schema instructions inside your prompt templates, let Spring AI’s Structured Output Converters (.entity()) automatically append accurate schema formatting instructions to the prompt.

  • Guard Against Prompt Injection: Keep sensitive business rules in the SystemMessage and reinforce instructions at the end of the prompt when processing large blocks of external user text.


Hands-on Experiment: AI Prompt Engineering Playground using Spring AI

Aim: To build a Spring Boot application that sends system prompts, user prompts and reusable prompt templates to an LLM and stores the results in MySQL.

Description: Prompt engineering is the practice of writing instructions that guide an LLM toward accurate, well-formed answers. System prompts set the model’s role and rules, user prompts carry the actual question, and templates insert variables into reusable prompt text. Spring AI supports this through PromptTemplate, system and user messages, and placeholders filled at runtime. It is used to get consistent tone, format and quality without hardcoding prompts in business logic.

Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman, and an OpenAI API key.

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven | Language: Java | Packaging: Jar | Java: 17
  • Spring Boot: 3.4.x (Spring AI 1.0 needs 3.4 or higher, so 3.3.x will not work here)
  • Group: com.example | Artifact: prompt-playground
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, OpenAI

Step 2: Project Structure

prompt-playground
├── pom.xml
└── src/main
    ├── java/com/example/promptplayground
    │   ├── PromptPlaygroundApplication.java
    │   ├── entity       (PromptTemplateEntity, PromptHistory)
    │   ├── repository   (PromptTemplateRepository, PromptHistoryRepository)
    │   ├── service      (PlaygroundService)
    │   └── controller   (PlaygroundController)
    └── resources/application.properties

Step 3: Create the files according to the project structure

package com.example.promptplayground.entity;

import jakarta.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "prompt_history")
public class PromptHistory {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String mode;

    @Column(columnDefinition = "TEXT")
    private String systemPrompt;

    @Column(columnDefinition = "TEXT")
    private String userPrompt;

    @Column(columnDefinition = "TEXT")
    private String aiResponse;

    private LocalDateTime createdAt = LocalDateTime.now();

    public PromptHistory() {
    }

    public PromptHistory(String mode, String systemPrompt, String userPrompt, String aiResponse) {
        this.mode = mode;
        this.systemPrompt = systemPrompt;
        this.userPrompt = userPrompt;
        this.aiResponse = aiResponse;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getMode() { return mode; }
    public void setMode(String mode) { this.mode = mode; }
    public String getSystemPrompt() { return systemPrompt; }
    public void setSystemPrompt(String systemPrompt) { this.systemPrompt = systemPrompt; }
    public String getUserPrompt() { return userPrompt; }
    public void setUserPrompt(String userPrompt) { this.userPrompt = userPrompt; }
    public String getAiResponse() { return aiResponse; }
    public void setAiResponse(String aiResponse) { this.aiResponse = aiResponse; }
    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.promptplayground.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "prompt_templates")
public class PromptTemplateEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String name;

    private String description;

    @Column(columnDefinition = "TEXT")
    private String systemText;

    @Column(columnDefinition = "TEXT")
    private String userText;

    public PromptTemplateEntity() {
    }

    public PromptTemplateEntity(Long id, String name, String description, String systemText, String userText) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.systemText = systemText;
        this.userText = userText;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
    public String getSystemText() { return systemText; }
    public void setSystemText(String systemText) { this.systemText = systemText; }
    public String getUserText() { return userText; }
    public void setUserText(String userText) { this.userText = userText; }
}
package com.example.promptplayground.repository;

import com.example.promptplayground.entity.PromptHistory;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface PromptHistoryRepository extends JpaRepository<PromptHistory, Long> {

    List<PromptHistory> findAllByOrderByCreatedAtDesc();
}
package com.example.promptplayground.repository;

import com.example.promptplayground.entity.PromptTemplateEntity;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface PromptTemplateRepository extends JpaRepository<PromptTemplateEntity, Long> {

    Optional<PromptTemplateEntity> findByName(String name);
}
package com.example.promptplayground.service;

import com.example.promptplayground.entity.PromptHistory;
import com.example.promptplayground.entity.PromptTemplateEntity;
import com.example.promptplayground.repository.PromptHistoryRepository;
import com.example.promptplayground.repository.PromptTemplateRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PlaygroundService {

    private final ChatClient chatClient;
    private final PromptTemplateRepository templateRepository;
    private final PromptHistoryRepository historyRepository;

    public PlaygroundService(ChatClient.Builder builder,
                             PromptTemplateRepository templateRepository,
                             PromptHistoryRepository historyRepository) {
        this.chatClient = builder.build();
        this.templateRepository = templateRepository;
        this.historyRepository = historyRepository;
    }

    // 1. Plain user prompt only (no system prompt)
    public String askUserOnly(String userPrompt) {
        String answer = chatClient.prompt()
                .user(userPrompt)
                .call()
                .content();
        historyRepository.save(new PromptHistory("USER_ONLY", null, userPrompt, answer));
        return answer;
    }

    // 2. System prompt + user prompt
    public String askWithSystem(String systemPrompt, String userPrompt) {
        String answer = chatClient.prompt()
                .system(systemPrompt)
                .user(userPrompt)
                .call()
                .content();
        historyRepository.save(new PromptHistory("SYSTEM_USER", systemPrompt, userPrompt, answer));
        return answer;
    }

    // 3. Saved template with {placeholders} filled from variables
    public String askWithTemplate(String templateName, Map<String, Object> variables) {
        PromptTemplateEntity template = templateRepository.findByName(templateName)
                .orElseThrow(() -> new IllegalArgumentException("Template not found: " + templateName));

        String answer = chatClient.prompt()
                .system(s -> s.text(template.getSystemText()).params(variables))
                .user(u -> u.text(template.getUserText()).params(variables))
                .call()
                .content();

        historyRepository.save(new PromptHistory("TEMPLATE:" + templateName,
                fill(template.getSystemText(), variables),
                fill(template.getUserText(), variables),
                answer));
        return answer;
    }

    public PromptTemplateEntity saveTemplate(PromptTemplateEntity template) {
        return templateRepository.save(template);
    }

    public List<PromptTemplateEntity> getTemplates() {
        return templateRepository.findAll();
    }

    public List<PromptHistory> getHistory() {
        return historyRepository.findAllByOrderByCreatedAtDesc();
    }

    // Simple placeholder replacement, only used to store a readable copy in history
    private String fill(String text, Map<String, Object> variables) {
        String result = text;
        for (Map.Entry<String, Object> entry : new HashMap<>(variables).entrySet()) {
            result = result.replace("{" + entry.getKey() + "}", String.valueOf(entry.getValue()));
        }
        return result;
    }
}
package com.example.promptplayground;

import com.example.promptplayground.entity.PromptTemplateEntity;
import com.example.promptplayground.repository.PromptTemplateRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class PromptPlaygroundApplication {

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

    // Seeds two ready-made templates on first run
    @Bean
    CommandLineRunner seedTemplates(PromptTemplateRepository repository) {
        return args -> {
            if (repository.count() == 0) {
                repository.save(new PromptTemplateEntity(null, "explain-topic",
                        "Explains a topic for a given audience",
                        "You are a friendly teacher who explains concepts in a {tone} tone.",
                        "Explain {topic} to a {audience} in 5 short lines."));
                repository.save(new PromptTemplateEntity(null, "code-review",
                        "Reviews a code snippet",
                        "You are a senior {language} developer. Give a concise review.",
                        "Review this code and list 3 improvements: {code}"));
            }
        };
    }
}

application.properties

spring.application.name=prompt-playground
server.port=8080

# MySQL (create the database first: CREATE DATABASE prompt_playground;)
spring.datasource.url=jdbc:mysql://localhost:3306/prompt_playground?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

spring.ai.google.genai.api-key=gemini-api-key
spring.ai.google.genai.chat.options.model=gemini-3.8-flash
spring.ai.google.genai.chat.options.temperature=0.7Code language: PHP (php)

Step 4: Run the Application and test the below CURD operations

POST Payloads and URLs (Postman)

1. User prompt only
POST http://localhost:8080/api/playground/chat/user

json
{ "userPrompt": "Explain REST API in 3 lines" }

2. System + user prompt
POST http://localhost:8080/api/playground/chat/system-user

json
{
  "systemPrompt": "You are a pirate. Reply in pirate style.",
  "userPrompt": "Explain what a database index is"
}

3. Create a template
POST http://localhost:8080/api/playground/templates

json
{
  "name": "summarize",
  "description": "Summarizes text",
  "systemText": "You are a {role}. Be {tone}.",
  "userText": "Summarize this in {lines} lines: {text}"
}

4. Run a seeded template
POST http://localhost:8080/api/playground/chat/template/explain-topic

json
{ "variables": { "tone": "funny", "topic": "Spring Beans", "audience": "beginner" } }

5. Run your saved template
POST http://localhost:8080/api/playground/chat/template/summarize

json
{
  "variables": {
    "role": "news editor", "tone": "neutral", "lines": "2",
    "text": "Spring AI provides a ChatClient API to talk to LLMs."
  }
}

6. List templates: GET http://localhost:8080/api/playground/templates
7. View history: GET http://localhost:8080/api/playground/history

Run the same template with "tone": "funny" and then "tone": "formal" to see how the system prompt changes the answer. Avoid raw { } such as JSON inside templates, because Spring AI treats them as placeholders.

below is the sample post payload from postman,

Scroll to Top