top of page

Building Your First AI-Powered Spring Boot Application


ree

Introduction

Artificial Intelligence (AI) is no longer just for research labs—it’s powering real-world business applications across industries like finance, e-commerce, healthcare, and manufacturing. As a Java developer, you can bring AI into your projects using Spring Boot and Spring AI.

In this tutorial, we’ll build a simple AI-powered Spring Boot application that answers natural language questions using an LLM (Large Language Model). We’ll take an industry-grade approach, keeping scalability, maintainability, and real-world use cases in mind.

By the end of this tutorial, you’ll know how to:

  • ✅ Set up a Spring Boot project with Spring AI.

  • ✅ Connect to an AI model (like OpenAI’s GPT).

  • ✅ Build REST APIs that interact with the AI.

  • ✅ Implement industrial-level best practices (logging, error handling, and modular design).

Step 1: Project Setup

We’ll use Spring Initializr to generate a new project.

Dependencies to include:

  • Spring Web

  • Spring AI

  • Lombok (for cleaner code)

👉 Go to https://start.spring.io, select:

  • Project: Maven

  • Language: Java 17 or above

  • Dependencies: Spring Web, Spring AI, Lombok

  • Group: com.example

  • Artifact: spring-ai-app

Click Generate and unzip the project.

Step 2: Add AI Configuration

Spring AI supports OpenAI, Azure OpenAI, Ollama, and other providers. For this example, let’s use OpenAI GPT.

Add Maven dependency in pom.xml:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    <version>0.8.1</version>
</dependency>

Configure API Key in application.yml

spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY} # Set in environment variables
      chat:
        options:
          model: gpt-3.5-turbo

👉 Make sure to set your API key securely:

export OPENAI_API_KEY=your_api_key_here

Step 3: Create an AI Service

This service will call the AI model and return responses.

package com.example.springaiapp.service;

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

@Service
public class AiService {

    private final ChatClient chatClient;

    public AiService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String askQuestion(String question) {
        return chatClient.call(question).getResult().getOutput().getContent();
    }
}

Step 4: Build REST Controller

Now we’ll expose an API endpoint so clients can interact with the AI.

package com.example.springaiapp.controller;

import com.example.springaiapp.service.AiService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/ai")
public class AiController {

    private final AiService aiService;

    public AiController(AiService aiService) {
        this.aiService = aiService;
    }

    @GetMapping("/ask")
    public String askQuestion(@RequestParam String question) {
        return aiService.askQuestion(question);
    }
}

Step 5: Test the Application

Run your application:

mvn spring-boot:run

Test the API with curl or Postman:

curl "http://localhost:8080/api/ai/ask?question=What%20is%20Spring%20AI?"

✅ Expected Response (AI-generated):

"Spring AI is a framework that integrates AI capabilities like LLMs into Spring Boot applications..."

Step 6: Industrial-Level Enhancements

To make this production-ready, we add:

1. DTOs for API contracts

package com.example.springaiapp.dto;

public class QuestionRequest {
    private String question;
    // getters and setters
}

public class AnswerResponse {
    private String answer;
    // getters and setters
}

Update the controller to use DTOs:

@PostMapping("/ask")
public AnswerResponse askQuestion(@RequestBody QuestionRequest request) {
    String answer = aiService.askQuestion(request.getQuestion());
    AnswerResponse response = new AnswerResponse();
    response.setAnswer(answer);
    return response;
}

2. Error Handling with @ControllerAdvice

package com.example.springaiapp.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("Something went wrong: " + ex.getMessage(),
                                    HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

3. Logging

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger logger = LoggerFactory.getLogger(AiService.class);

public String askQuestion(String question) {
    logger.info("User asked: {}", question);
    String response = chatClient.call(question).getResult().getOutput().getContent();
    logger.info("AI response: {}", response);
    return response;
}

Real-World Example Use Cases

This setup can be applied in multiple industries:

  • E-commerce → AI-powered product Q&A chatbot.

  • Banking → Virtual assistant for customer queries.

  • Healthcare → Patient query handling (non-sensitive info).

  • Manufacturing → AI knowledge base for troubleshooting machinery.

Conclusion

You’ve built your first AI-powered Spring Boot application with Spring AI!We:

  • Set up Spring Boot with Spring AI.

  • Connected to OpenAI’s GPT model.

  • Built REST endpoints to ask AI questions.

  • Improved it with DTOs, error handling, and logging for industrial-grade quality.


Comments


bottom of page