Spring / Spring AI interview questions
How do you create and use a ChatClient in a Spring Boot application?
ChatClient is obtained from an auto-configured ChatClient.Builder bean that Spring Boot registers when a chat model starter is on the classpath. You inject the builder (not the client itself) so each service can establish its own default system prompt and advisor chain before constructing its client instance.
@Service public class TutorService { private final ChatClient chatClient; public TutorService(ChatClient.Builder builder) { this.chatClient = builder .defaultSystem("You are a concise Java tutor. Keep answers under 100 words.") .build(); } public String explain(String concept) { return chatClient.prompt() .user("Explain " + concept) .call() .content(); } }
The .prompt() call starts building the request. .user() sets the user turn. .call() sends the request synchronously and returns a CallResponseSpec. .content() extracts the first choice's text. For structured output, replace .content() with .entity(MyRecord.class). For streaming, replace .call() with .stream().
If you want a single shared ChatClient bean across the whole application (no per-service customisation), you can declare one directly in a @Configuration class using the builder. But injecting the builder per service is the more flexible pattern used in most production codebases.
More Related questions...