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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
