Sentiment analysis uses an LLM to classify user text along a continuous polarity scale, helping applications respond differently to positive, neutral, or negative experiences. section 11.3
A practical Spring implementation follows this shape:
- Define a prompt that requests a score from -1.0 to +1.0 and a brief explanation. section 11.3
- Represent the request with text input and return the analyzed text, score, and explanation. section 11.3
- Expose a POST endpoint and configure ChatClient with the sentiment system prompt. section 11.3
Interpreting context
“It’s the end of the world” receives -1.0, while adding “And I feel fine” changes the result to 0.5, showing that context can reverse polarity. section 11.3
Listing 11.4 Analyzing sentiment using ChatClient
package com.example.sentimentanalysis;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SentimentController {
private final ChatClient chatClient;
public SentimentController(
ChatClient.Builder chatClientBuilder,
@Value("classpath:/sentimentSystemPrompt.st") #1
Resource sentimentSystemPrompt) {
this.chatClient = chatClientBuilder
.defaultSystem(sentimentSystemPrompt)
.build();
}
@PostMapping("/sentiment")
public SentimentAnalysis getSentiment(@RequestBody TextInput textInput) {
return chatClient.prompt()
.user(userSpec -> userSpec
.text("User text: {text}")
.param("text", textInput.text())) #2
.call()
.entity(SentimentAnalysis.class);
}
}
Inspect the controller pattern connecting Spring’s ChatClient, a system prompt resource, and the POST sentiment endpoint. section 11.3











