Şuayb's BlogŞuayb's Blog
Home
Categories
Games
MediumAboutContact
Language
Theme
    1. Blog
    2. Programming
    3. Spring Boot AI Integration

Spring Boot AI Integration

PublishedApril 23, 2025
UpdatedApril 24, 2025
Reading time3 min read
JavaKotlinSpring BootSpring AIArtificial Intelligence
XLinkedInFacebook
Spring Boot AI Integration

Loading likes...

Spring AI is a framework for AI engineering that applies Spring’s portability and modular design principles to AI workloads. It lets you build AI-driven applications using familiar Spring idioms and POJOs.


Last updatedApril 24, 2025

Total viewsLoading hits...

Previous articleSpring Boot JPA AuditingNext articleSpring Boot Async Tasks with Virtual Thread
Şuayb Şimşek

Written by

Şuayb Şimşek

Backend-focused fullstack developer sharing practical notes on Spring Boot, security, microservices, and cloud-native architecture.

Expertise

  • Spring Boot
  • Go
  • Microservices
  • Next.js
  • Cloud Native

Connect

GitHubLinkedInMedium

Related posts

Spring Boot Configuration Properties
Programming

Spring Boot Configuration Properties

Learn how to use @ConfigurationProperties for type-safe configuration, validate settings with @Validated, and manage environment-specific values with profile-specific application-{profile}.yml files.

February 4, 20263 min read
JavaKotlinSpring BootConfiguration
Spring Boot GraphQL JWE Authentication
Programming

Spring Boot GraphQL JWE Authentication

Learn how to secure your Spring Boot GraphQL APIs with stateless encrypted JWTs (JWE) while persisting user identities and roles in a JPA-backed database.

May 17, 20256 min read
JavaKotlinSpring BootSecurityJWTJWEGraphQL
Spring Boot JWE Authentication with JPA
Programming

Spring Boot JWE Authentication with JPA

Learn how to use stateless encrypted JWTs (JWE) to secure your Spring Boot APIs while persisting user identities and roles in a JPA-backed database.

May 11, 20254 min read
JavaKotlinSpring BootSecurityJWTJWEJPA

About

Articles on Spring Boot, microservices, security, and more.

ContactStart here

Latest posts

  • Captain Tsubasa 2: World Fighters
  • Captain Tsubasa: Rise of New Champions
  • Spring Boot Configuration Properties
  • Spring Boot GraphQL JWE Authentication
  • Spring Boot JWE Authentication with JPA

Top topics

JavaKotlinSpring BootJWEJWTMicroservice

Subscribe

Get practical backend + fullstack notes when new articles are published.

Social

© 2024-2026 Şuayb's Blog. All rights reserved.

🌟 Why Use Spring AI?

In this section, we clarify Why Use Spring AI? and summarize the key points you will apply in implementation.

  • Provider-agnostic portability: Write code once and switch between AI providers (OpenAI, Anthropic, Azure, etc.) without changes.
  • POJO-based design: Model AI inputs and outputs as plain Java/Kotlin objects for type safety and easy integration.
  • Structured outputs: Automatically map model responses to your domain objects.
  • Vector store integration: Seamless support for major vector databases (Chroma, Pinecone, Redis, etc.) via a unified API.
  • Tool/function calling: Enable LLMs to invoke custom functions or services for real-time data.
  • Observability & evaluation: Built-in metrics and evaluation utilities to monitor AI operations and detect hallucinations.
  • Chat abstractions: Fluent ChatClient API, similar to Spring’s WebClient, for building conversational agents.
  • Retrieval-augmented generation (RAG): Simplify document-based QA and memory-backed chat with advisors and memory APIs.

📋 Prerequisites

Ensure you have the following:

  • ☕ Java Development Kit (JDK) 17+
  • 📦 Maven or Gradle installed
  • 🐳 Spring Boot 3+
  • 🔑 OpenAI API Key (set as environment variable OPENAI_API_KEY)

🛠️ Step 1: Add Dependencies

Include Spring AI starter for OpenAI, Spring Web, and Lombok.


🛠️ Step 2: Configuration

In application.yml, configure your OpenAI key and set the ChatClient model:

YAMLapplication.yml
spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      chat:
        options:
          model: gpt-4.1-mini

🛠️ Step 3: Implement the Service Layer

Create an AIService to wrap your ChatClient. Inject ChatClient.Builder and build the client.


🛠️ Step 4: Expose a REST Controller

Create a ChatController to expose your AIService over HTTP.


▶️ Running the Application

Start your Spring Boot app:

BASH
./mvnw spring-boot:run
# or
gradle bootRun

🧪 Testing the Integration

Call your service via HTTP:

BASH
curl -X GET "http://localhost:8080/joke?topic=dogs"
# Returns a dog joke generated by the AI model.

🏁 Conclusion

You now have a practical Spring Boot AI Integration implementation with a clear, production-friendly Spring Boot structure. As a next step, adapt configuration and tests to your own domain, then validate behavior under realistic traffic and failure scenarios.

XMLpom.xml
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
  </dependency>
</dependencies>
GROOVYbuild.gradle
plugins {
  id 'org.springframework.boot' version '3.2.0'
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  implementation 'org.springframework.ai:spring-ai-starter-model-openai'
  compileOnly 'org.projectlombok:lombok'
  annotationProcessor 'org.projectlombok:lombok'
}
JAVAAIService.java
package com.example.ai.service;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

@Service
public class AIService {
    private final ChatClient chatClient;

    public AIService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public String getJoke(String topic) {
        return chatClient.prompt()
                .user(u -> u.text("Tell me a joke about {topic}").param("topic", topic))
                .call()
                .content();
    }
}
KOTLINAIService.kt
package com.example.ai.service

import org.springframework.ai.chat.client.ChatClient
import org.springframework.stereotype.Service

@Service
class AIService(builder: ChatClient.Builder) {
    private val chatClient: ChatClient = builder.build()

    fun getJoke(topic: String): String {
        return chatClient.prompt()
            .user { it.text("Tell me a joke about {topic}").param("topic", topic) }
            .call()
            .content()
    }
}
JAVAChatController.java
package com.example.ai.controller;

import com.example.ai.service.AIService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class ChatController {

    private final AIService aiService;

    @GetMapping("/joke")
    public String getJoke(@RequestParam(defaultValue = "dogs") String topic) {
        return aiService.getJoke(topic);
    }
}
KOTLINChatController.kt
package com.example.ai.controller

import com.example.ai.service.AIService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@RestController
class ChatController(private val aiService: AIService) {

    @GetMapping("/joke")
    fun getJoke(@RequestParam(defaultValue = "dogs") topic: String): String {
        return aiService.getJoke(topic)
    }
}