Monday, November 30, 2026 - 07:00
  • Share this article:

AI is transforming software development. In addition to generating code and enhancing productivity, AI can now be integrated directly into products, allowing applications to interpret context, generate responses, recommend actions, and interact through intelligent agents.

For Java developers, this presents a new integration challenge: how can we add these capabilities to enterprise applications without increasing complexity?

In this tutorial, we will create an enterprise Java integration using LangChain4j, a declarative API for AI orchestration. By combining its AI abstractions with Jakarta EE, we will maintain a familiar, composable, and adaptable application architecture.

Java is well positioned for AI. The next step is to put this into practice.

To demonstrate the integration, we will build a REST API that accepts a book title and uses an LLM to recommend three related books. This straightforward example will help us focus on the core concepts of LangChain4j and its integration with Jakarta EE.

Creating the initial Project

Begin by creating the Jakarta EE project structure. The Jakarta EE Starter tool streamlines this process and saves time.

For this tutorial, select the following options:

  • Jakarta EE version: Jakarta EE 11
  • Profile: Core Profile
  • Java version: Java 21
  • Runtime: Open Liberty

Next, select the Group and Artifact names for your application, then download the generated project.

Once the Jakarta EE structure is set up.

After downloading the project, add the LangChain4j dependencies and MicroProfile Config support to the pom.xml.

<dependency>
   <groupId>dev.langchain4j.cdi</groupId>
   <artifactId>langchain4j-cdi-portable-ext</artifactId>
   <version>${langchain4j-cdi.version}</version>
</dependency>

<dependency>
   <groupId>dev.langchain4j.cdi.mp</groupId>
   <artifactId>langchain4j-cdi-config</artifactId>
   <version>${langchain4j-cdi.version}</version>
</dependency>

<dependency>
   <groupId>dev.langchain4j</groupId>
   <artifactId>langchain4j-open-ai</artifactId>
   <version>1.16.0</version>
</dependency>

<dependency>
   <groupId>io.smallrye.config</groupId>
   <artifactId>smallrye-config</artifactId>
   <version>3.17.2</version>
</dependency>

 

LangChain4j serves as the orchestration layer between the application and the AI model. It acts as an abstraction, similar to a repository, allowing the application to interact with a higher-level API rather than the underlying infrastructure.

Unlike a repository that abstracts a database, LangChain4j abstracts interactions with AI models and providers.

In this tutorial, we use OpenAI as the model provider through the langchain4j-open-ai module. This architecture permits the application code to remain decoupled from specific providers. You can switch providers by updating the relevant dependency and configuration, without changing the application logic.

Next, configure the chat model by creating or updating the following file:

src/main/resources/META-INF/microprofile-config.properties

dev.langchain4j.cdi.plugin.chat-model.class=dev.langchain4j.model.openai.OpenAiChatModel
dev.langchain4j.cdi.plugin.chat-model.config.api-key=${OPENAI_API_KEY}
dev.langchain4j.cdi.plugin.chat-model.config.model-name=gpt-5

 

Avoid storing credentials such as API keys in source code or configuration files under version control. Instead, provide them through environment variables:

export OPENAI_API_KEY="your-api-key"

MicroProfile Config enables the application to load configuration from various sources, including environment variables. This approach is consistent with the Twelve-Factor App principle that environment-specific configuration should remain outside the application code.

This separation is especially valuable when deploying the application across development, testing, container, and production environments.

Creating Rest Structure

With the basic project structure in place, the next step is to develop the REST application.

In this example, we will provide an API that accepts a book and returns up to three recommended books that logically follow it.

Start defining the data structures. Because these classes are simple, immutable data carriers, Java records suit this purpose well.

import java.util.List;

public record Book(
       String title,
       String author,
       String description,
       List<String> keywords
) {
}


Each recommendation includes the suggested book and a brief explanation of its relevance.

public record Recommendation(
       Book book,
       String reason
) {
}

 

The service returns a collection of recommendations:

import java.util.List;

public record NextReadBooks(
       List<Recommendation> recommendations
) {
}

 

The request includes the book that serves as the starting point for recommendations:

public record BookRequest(
       String title,
       String author
) {
}


With the domain structure complete, the next step is to connect Java to the LLM.

LangChain4j offers a declarative AI Services API. The programming model is similar to Jakarta Data or Spring Data: you define an interface and specify the desired behavior, and the framework provides the implementation at runtime.

Instead of generating database access code, LangChain4j uses the interface as an abstraction over an AI model.

In this tutorial, we will create the NextReadBookService:

import dev.langchain4j.cdi.spi.RegisterAIService;
import dev.langchain4j.service.SystemMessage;

@RegisterAIService
public interface NextReadBookService {

   @SystemMessage("""
           Recommend up to 3 books that should naturally follow
           the provided book in a learning journey.

           Recommendations should prioritize:

           - conceptual progression
           - complementary knowledge
           - technical depth
           - thematic similarity

           For each recommendation provide:

           - title
           - author
           - concise description
           - relevant keywords
           - a short recommendation reason

           Keep recommendations concise, technically relevant,
           and focused on software engineering and architecture learning.
           """)
   NextReadBooks recommend(BookRequest request);
}

 

The @RegisterAIService annotation instructs the LangChain4j CDI integration to create and register an implementation of this interface as a CDI bean.

The @SystemMessage annotation specifies the instructions that guide the model’s behavior. Rather than manually building prompts, invoking the provider API, parsing responses, and mapping them to Java objects, we define the expected interaction directly in the interface.

The method remains straightforward:

NextReadBooks recommend(BookRequest request);

 

LangChain4j uses the method input in its interaction with the model and maps the structured response to the NextReadBooks record.

This highlights the declarative nature of the integration: the application specifies its expectations, and LangChain4j manages the orchestration required to achieve the result.

The final step is to make our AI service available through a REST endpoint.

Since NextReadBookService is registered as a CDI bean, we can inject it into a Jakarta REST resource and delegate recommendation requests to LangChain4j.

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@ApplicationScoped
@Path("books")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BookResource {

   @Inject
   private NextReadBookService nextReadBookService;

   @POST
   public NextReadBooks recommend(BookRequest request) {
       return nextReadBookService.recommend(request);
   }
}

The application code is minimal. Jakarta REST manages the HTTP layer, CDI injects the AI service, and LangChain4j communicates with the configured model and converts responses into Java records.

 

You can now build and start the application using Open Liberty:

mvn clean package liberty:run

 

After the application starts, call the endpoint with a known book:

curl --location 'http://localhost:9080/rest/books' \
 --header 'Content-Type: application/json' \
 --data '{
   "title": "Domain-Driven Design with Java: Building Scalable and Maintainable Java Applications with DDD Principles",
   "author": "Otávio Santana"
 }'

 

The request is received by the Jakarta REST endpoint and delegated to NextReadBookService. LangChain4j sends the request to the configured LLM and maps the result to NextReadBooks.

The response includes up to three books, each with its title, author, description, keywords, and an explanation of why it is a suitable next step in the learning journey.

With just a REST resource, a declarative Java interface, and minimal configuration, you now have an enterprise Java application that interacts with an LLM while keeping the AI provider separate from the application logic.

 

Reference:

About the Author

Otávio Santana

Otávio Santana

Otavio is an award-winning software engineer and architect who is passionate about empowering other engineers with open source best practices to build highly scalable and efficient software. He is a renowned contributor to the Java and open-source ecosystems and has received numerous awards and accolades for his work. Otavio's interests include history, the economy, travel, and fluency in multiple languages, all seasoned with a great sense of humour.