Spring › Spring-AI

Using Spring AI ChatClient with Google GenAI for sync calls

Configure spring-ai-starter-model-google-genai in Spring Boot 4 and Spring AI 2.0.1 for synchronous text generation and structured Kotlin DTO mapping.

Using Spring AI ChatClient with Google GenAI for sync calls

Spring Boot 4.1 and Spring AI 2.0.1 ship with the official spring-ai-starter-model-google-genai starter and the ChatClient Fluent API. This post walks through configuring gemini-3.5-flash-lite, injecting system prompts, and mapping model responses directly into Kotlin data classes with .entity().

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, and gemini-3.5-flash-lite.

How Spring AI 2.0.1 ChatClient works

In early Spring AI 1.x codebases, calling a model meant injecting a provider-specific ChatModel (such as GoogleGenAiChatModel) and manually assembling Prompt, Message, and ChatOptions objects. Spring AI 2.0.x standardizes on ChatClient, a fluent API modeled after RestClient and WebClient.

Under the hood, ChatClient builds an immutable request spec, runs any registered advisors (logging, memory, RAG), delegates to the underlying ChatModel, and optionally applies a StructuredOutputConverter to deserialize the response into a typed DTO.

flowchart TD
    Builder["ChatClient.Builder"] --> Client["ChatClient (Thread-Safe Bean)"]
    Client --> Prompt["prompt().system(...).user(...)"]
    Prompt --> Call["call() — Sync HTTP to Gemini"]
    Call --> Content["content() → String"]
    Call --> Entity["entity(DTO::class.java) → Kotlin Object"]
API choiceReturn typeBest fitTrade-off
ChatClient.call().content()StringShort summaries, background jobs, internal toolsBlocks the caller thread until generation completes
ChatClient.call().entity(T)Typed DTOStructured extraction, classification, formsAdds schema instructions; fails if JSON is malformed
ChatClient.stream().content()Flux<String>Interactive chat UIsHarder to parse into a single DTO mid-stream
Raw ChatModelChatResponseLow-level metadata/token inspectionVerbose prompt assembly; bypasses ChatClient advisors

When not to use synchronous call(): Don’t use blocking call() for user-facing chat interfaces where responses take 3–8 seconds. Holding a Servlet thread open while the user stares at a blank spinner hurts both perceived latency and thread-pool capacity—use SSE streaming instead.

Project setup and auto-configuration

All snippets below come from the generate-text module in spring-ai-examples.

1. Gradle dependencies (build.gradle.kts)

Import spring-ai-bom:2.0.1 and add spring-ai-starter-model-google-genai:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

extra["springAiVersion"] = "2.0.1"

dependencyManagement {
    imports {
        mavenBom("org.springframework.ai:spring-ai-bom:${property("springAiVersion")}")
    }
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}

2. Model and API key configuration (application.yaml)

Wire in the API key issued in Setting up Google AI Studio keys with monthly developer credits via an environment variable, and set gemini-3.5-flash-lite as the default model:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
server:
  port: 8081

spring:
  application:
    name: generate-text
  ai:
    google:
      genai:
        api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY}
        chat:
          options:
            model: gemini-3.5-flash-lite
            temperature: 0.7

At startup, GoogleGenAiAutoConfiguration reads these properties and registers both GoogleGenAiChatModel and a prototype ChatClient.Builder bean:

ChatClient Builder auto-configuration log Figure 1. Spring Boot startup log showing GoogleGenAiChatModel auto-configured with gemini-3.5-flash-lite.

Registering a shared ChatClient bean

ChatClient is immutable and thread-safe once built, so registering a shared bean with a default system prompt keeps your service classes concise:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package io.github.cmsong111.generate_text

import org.springframework.ai.chat.client.ChatClient
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean

@SpringBootApplication
class GenerateTextApplication {

    @Bean
    fun chatClient(builder: ChatClient.Builder): ChatClient {
        return builder
            .defaultSystem("You are a helpful and concise backend software engineering assistant.")
            .build()
    }
}

fun main(args: Array<String>) {
    runApplication<GenerateTextApplication>(*args)
}

Implementing text generation and structured output

Next, I built a service covering three common patterns: a plain prompt, a per-request system prompt override, and structured DTO deserialization.

1. Kotlin DTO for structured output

1
2
3
4
5
6
7
8
9
package io.github.cmsong111.generate_text.dto

data class BookRecommendation(
    val title: String,
    val author: String,
    val genre: String,
    val summary: String,
    val reasonsToRead: List<String>
)

2. Service implementation (TextGenerationService)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package io.github.cmsong111.generate_text.service

import io.github.cmsong111.generate_text.dto.BookRecommendation
import org.springframework.ai.chat.client.ChatClient
import org.springframework.stereotype.Service

@Service
class TextGenerationService(
    private val chatClient: ChatClient
) {

    // Plain synchronous text generation with a user prompt
    fun generateSimple(prompt: String): String {
        return chatClient.prompt()
            .user(prompt)
            .call()
            .content() ?: ""
    }

    // Overrides the default system prompt for a single request
    fun generateWithSystem(systemPrompt: String, userPrompt: String): String {
        return chatClient.prompt()
            .system(systemPrompt)
            .user(userPrompt)
            .call()
            .content() ?: ""
    }

    // Deserializes the model's JSON response directly into a Kotlin DTO
    fun recommendBook(topic: String): BookRecommendation? {
        return chatClient.prompt()
            .system("You are a technical book curator. Return book details in the requested JSON format.")
            .user("Recommend one top book for the following topic or interest: '$topic'")
            .call()
            .entity(BookRecommendation::class.java)
    }
}

Calling .entity(BookRecommendation::class.java) triggers BeanOutputConverter, which appends a generated JSON Schema to the prompt and deserializes the model’s JSON output with Jackson. Including jackson-module-kotlin ensures Kotlin’s non-null primary constructors bind cleanly without extra annotations.

3. REST controller (TextGenerationController)

Expose all three service methods over HTTP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package io.github.cmsong111.generate_text.controller

import io.github.cmsong111.generate_text.dto.BookRecommendation
import io.github.cmsong111.generate_text.dto.GenerationRequest
import io.github.cmsong111.generate_text.service.TextGenerationService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/generate")
class TextGenerationController(
    private val textGenerationService: TextGenerationService
) {

    @GetMapping
    fun generateSimple(@RequestParam prompt: String): ResponseEntity<Map<String, String>> {
        val result = textGenerationService.generateSimple(prompt)
        return ResponseEntity.ok(mapOf("result" to result))
    }

    @PostMapping("/custom")
    fun generateCustom(@RequestBody request: GenerationRequest): ResponseEntity<Map<String, String>> {
        val result = if (request.systemPrompt != null) {
            textGenerationService.generateWithSystem(request.systemPrompt, request.prompt)
        } else {
            textGenerationService.generateSimple(request.prompt)
        }
        return ResponseEntity.ok(mapOf("result" to result))
    }

    @GetMapping("/book")
    fun recommendBook(@RequestParam topic: String): ResponseEntity<BookRecommendation> {
        val recommendation = textGenerationService.recommendBook(topic)
            ?: return ResponseEntity.notFound().build()
        return ResponseEntity.ok(recommendation)
    }
}

Verifying with integration tests and curl

To verify both plain text generation and DTO deserialization against the live Gemini API, I wrote a @SpringBootTest integration suite:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package io.github.cmsong111.generate_text

import io.github.cmsong111.generate_text.service.TextGenerationService
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest

@SpringBootTest
class TextGenerationIntegrationTests {

    @Autowired
    private lateinit var textGenerationService: TextGenerationService

    @Test
    fun `generates plain text from live Gemini API`() {
        val prompt = "Summarize the main value of combining Spring Boot with Spring AI in one sentence."
        val result = textGenerationService.generateSimple(prompt)

        println("=== [TextGeneration] Simple Generation Result ===")
        println(result)
        assertThat(result).isNotBlank()
    }

    @Test
    fun `parses structured book recommendation into DTO`() {
        val topic = "Object-oriented design and refactoring"
        val recommendation = textGenerationService.recommendBook(topic)

        println("=== [TextGeneration] Structured Output Result ===")
        println(recommendation)
        assertThat(recommendation).isNotNull
        assertThat(recommendation?.title).isNotBlank()
    }
}

Running ./gradlew test completes in about 4 seconds on the standard paid tier and confirms both the plain text response and BookRecommendation deserialization:

TextGeneration integration test pass output Figure 2. JUnit 5 integration test passing with live Gemini responses and DTO binding.

Sample console output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
=== [TextGeneration] Simple Generation Result ===
Combining Spring Boot with Spring AI lets backend engineers integrate LLM features using familiar Spring abstractions without rewriting their existing Java or Kotlin stack.
=================================================

=== [TextGeneration] Structured Output Result ===
BookRecommendation(
  title=Refactoring: Improving the Design of Existing Code (2nd Edition),
  author=Martin Fowler,
  genre=Software Engineering,
  summary=A practical catalog of refactoring techniques for improving internal code structure without changing external behavior.,
  reasonsToRead=[
    Teaches concrete steps to keep code readable and maintainable.,
    Shows how object-oriented principles apply to real-world codebases.,
    Builds habits for improving legacy code incrementally.
  ]
)
=================================================

Starting the server and hitting /api/generate and /api/generate/book with curl returns clean JSON payloads:

cURL HTTP API response console Figure 3. Live curl responses from /api/generate and /api/generate/book.

Production caveats and checklist

Synchronous ChatClient calls are easy to wire up, but keep these operational details in mind before shipping:

  • Guard live API tests in CI: Annotate live @SpringBootTest classes with @EnabledIfEnvironmentVariable(named = "SPRING_AI_GOOGLE_GENAI_API_KEY", matches = ".+") or a dedicated JUnit tag so PR builds don’t fail or burn credits unexpectedly.
  • Handle JSON conversion failures: Prompt-based .entity() conversion can still fail if a model wraps JSON in extra prose; for strict schemas, pair it with Gemini’s native structured output mode.
  • Set explicit timeouts and retries: External LLM calls can stall for several seconds; configure HTTP client timeouts so slow completions don’t exhaust your Tomcat thread pool.
  • Move interactive chat to SSE: When users wait on multi-paragraph answers, switch from .call() to reactive streaming—see Streaming Gemini chat responses with Spring AI and SSE.

Full source code is available in cmsong111/spring-ai-examples/generate-text.

This post is licensed under CC BY 4.0 by the author.