Integrating Spring AI Framework in Your Java Application

This blog post will integrate the Spring AI framework into a Java application. We’ll use a simple project that includes a ChatService and a ChatController to demonstrate using the Spring AI framework to generate text & image responses and horoscopes based on user input.

Update 12/28/2025 – Updated from M1 release to Spring AI 1.1.0 GA

Prerequisites

Before we start, make sure you have the following:

  • Java Development Kit (JDK) installed
  • Familiarity with Spring Framework
  • Basic understanding of RESTful APIs
  • An OpenAI API key

Obtaining an OpenAI API Key

To use the OpenAI API, you’ll need to sign up for an API key:

  1. Go to the OpenAI website.
  2. Sign up for an account if you don’t already have one.
  3. Navigate to the API section and generate a new API key.

Once you have your API key, set the OS environment variable OPEN_API_KEY to this value. We will refer to it in the spring application.properties file

Setting Up the Project

First, let’s set up our project. Create a new Spring Boot project and add the necessary dependencies for Spring AI.

Maven Dependencies

Add the following dependencies to your pom.xml:

Configuring the API Key

Point to the OpenAI API key in the application.properties file. Please make sure to set the environment variable OPENAI_API_KEY to the API key. Avoid hardcoding the API key directly in the properties file.

Implementing the ChatService

The ChatService class contains methods to process AI prompts and generate horoscopes. Here’s the complete implementation:

  • processPrompt: This method takes a prompt, model name, and temperature as parameters and returns the AI-generated text response.
  • getMyHoroscope: This method generates a horoscope based on the user’s zodiac sign and the specified number of days for which you want to know your future. Note: I do not have to say this, but I will — this is a generic response and nothing to do with your real life or what you should expect in the future (just saying!)l
  • generateImage: This method generates an image based on the provided message. It returns the URL where you can view the generated image.

Implementing the ChatController

The ChatController class exposes REST endpoints to interact with the ChatService. Here’s the complete implementation:

 

Running the Application

To run the application, use the following command line from your Mac OS terminal.

I have included a Postman collection in the Git project repository.

Conclusion

In this blog post, we demonstrated how to integrate the Spring AI framework into a Java application. We created a ChatService to handle AI prompts and horoscope generation, and exposed REST endpoints through a ChatController. This should give you a good starting point for building more advanced AI-powered Spring AI applications. The code is at https://github.com/thomasma/spring-ai