Skip to main content
skill CX Codex

langchain4j-spring-boot-integration — Claude Code skill: setup guide

Configures LangChain4j in Spring Boot applications, setting up declarative @AiService interfaces, chat memory, and RAG pipelines with Spring Data.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill langchain4j-spring-boot-integration -a claude-code
Open on GitHub

What langchain4j-spring-boot-integration does

This skill guides the setup of LangChain4j starters in Spring Boot projects. It provides integration patterns for starter dependencies at version 1.8.0, configuration properties in YAML or properties files, and declarative @AiService interfaces.

Inside, you get configuration templates for manual @Bean definitions, streaming responses using Project Reactor Flux, and conversational memory via @MemoryId. It also covers vector store setup using PgVectorEmbeddingStore alongside custom Spring @Component tools annotated with @Tool.

If your declarative services fail to inject, you must add dev.langchain4j.service.spring to your @ComponentScan. Spring context needs that package scanned to discover generated proxy beans.

What it helps with

  • add LangChain4j starter dependencies to pom.xml
  • declare AI services using the @AiService annotation
  • set up RAG pipelines with PgVectorEmbeddingStore
  • expose Spring components as LLM tools using @Tool

Example prompts for the agent

  • Create a declarative CustomerSupportAssistant interface with @AiService and OpenAI properties
  • Set up a PgVectorEmbeddingStore bean and an OpenAiEmbeddingModel in a Spring configuration class
  • Build a Spring component with @Tool annotations to provide calculator functions to an agent

How to install langchain4j-spring-boot-integration

1Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill langchain4j-spring-boot-integration -a claude-code

2Manually: put the files in place

~/.claude/skills/langchain4j-spring-boot-integration/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/langchain4j-spring-boot-integration/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about langchain4j-spring-boot-integration

How do I install langchain4j-spring-boot-integration in Claude Code?

Run npx skills add giuseppe-trisciuoglio/developer-kit --skill langchain4j-spring-boot-integration -a claude-code in your terminal.

What does langchain4j-spring-boot-integration do?

It provides architecture patterns for LangChain4j inside Spring Boot, including model properties, @AiService declarations, chat memory, and RAG storage beans.

Why is dev.langchain4j.service.spring needed in @ComponentScan?

Spring Boot will not register declarative @AiService beans automatically unless dev.langchain4j.service.spring is explicitly included in the @ComponentScan base packages.

Source text

SKILL.md · MIT
---
name: langchain4j-spring-boot-integration
description: Provides integration patterns for LangChain4j with Spring Boot. Configures AI model beans, sets up chat memory with Spring context, integrates RAG pipelines with Spring Data, and handles auto-configuration, dependency injection, and Spring ecosystem integration. Use when embedding LangChain4j into Spring Boot applications, building Java LLM applications with @Bean configuration, or setting up Spring AI patterns.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

# LangChain4j Spring Boot Integration

Integrate LangChain4j with Spring Boot using declarative AI Services, auto-configuration, and Spring Boot starters. Configure AI model beans, set up chat memory, implement RAG pipelines with Spring Data, and build production-ready AI applications.

## When to Use

Use this skill when:
- Integrating LangChain4j into existing Spring Boot applications
- Building AI-powered microservices with Spring Boot
- Configuring AI model beans with `@Bean` annotations
- Setting up auto-configuration for AI models and services
- Creating declarative AI Services with Spring dependency injection
- Implementing RAG systems with Spring Data integrations
- Setting up chat memory with Spring context management
- Configuring multiple AI providers (OpenAI, Azure, Ollama, Anthropic)
- Building production-ready AI applications with Spring Boot

## Overview

LangChain4j Spring Boot integration provides declarative AI Services through Spring Boot starters, enabling automatic configuration of AI components based on properties. Combine Spring dependency injection with LangChain4j's AI capabilities using interface-based definitions with annotations.

## Instructions

### 1. Add Dependencies

```xml
<!-- Core LangChain4j Spring Boot Starter -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-spring-boot-starter</artifactId>
    <version>1.8.0</version>
</dependency>

<!-- OpenAI Spring Boot Starter -->
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
    <version>1.8.0</version>
</dependency>
```

### 2. Configure Application Properties

```properties
# application.properties
langchain4j.open-ai.chat-model.api-key=${OPENAI_API_KEY}
langchain4j.open-ai.chat-model.model-name=gpt-4o-mini
langchain4j.open-ai.chat-model.temperature=0.7
langchain4j.open-ai.chat-model.timeout=PT60S
langchain4j.open-ai.chat-model.max-tokens=1000
```

Or using YAML:

```yaml
langchain4j:
  open-ai:
    chat-model:
      api-key: ${OPENAI_API_KEY}
      model-name: gpt-4o-mini
      temperature: 0.7
      timeout: 60s
      max-tokens: 1000
```

### 3. Create Declarative AI Service

```java
import dev.langchain4j.service.spring.AiService;

@AiService
public interface CustomerSupportAssistant {

    @SystemMessage("You are a helpful customer support agent for TechCorp.")
    String handleInquiry(String customerMessage);

    @UserMessage("Translate to {{language}}: {{text}}")
    String translate(String text, String language);
}
```

### 4. Enable Component Scanning

```java
@SpringBootApplication
@ComponentScan(basePackages = {
    "com.yourcompany",
    "dev.langchain4j.service.spring"
})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
```

### 5. Inject and Use the AI Service

```java
@Service
public class CustomerService {

    private final CustomerSupportAssistant assistant;

    public CustomerService(CustomerSupportAssistant assistant) {
        this.assistant = assistant;
    }

    public String processCustomerQuery(String query) {
        return assistant.handleInquiry(query);
    }
}
```

### 6. Verify the Integration

After setup, verify the configuration:
1. Start the application and check logs for `LangChain4jSpringBootAutoConfiguration` activation
2. Confirm AI service beans are registered: look for `CustomerSupportAssistant` in Spring context
3. Test the service: invoke `assistant.handleInquiry("test")` and verify a response is returned

## Configuration

**Property-Based Configuration:** Configure AI models through `application.properties` for different providers.

**Manual Bean Configuration:** For advanced configurations, define beans manually:

```java
@Configuration
public class AiConfig {

    @Bean
    public ChatModel chatModel(@Value("${OPENAI_API_KEY}") String apiKey) {
        return OpenAiChatModel.builder()
            .apiKey(apiKey)
            .modelName("gpt-4o-mini")
            .temperature(0.7)
            .build();
    }
}
```

**Multiple Providers:** Use explicit wiring when configuring multiple AI providers:

```java
@AiService(wiringMode = WiringMode.EXPLICIT)
interface MultiProviderAssistant {
    @AiServiceAnnotation
    ChatModel openAiModel;

    @AiServiceAnnotation
    ChatModel azureModel;
}
```

## Declarative AI Services

**Basic AI Service:** Create interfaces with `@AiService` annotation and define methods with message templates.

**Streaming AI Service:** Implement streaming responses using Project Reactor:

```java
@AiService
public interface StreamingAssistant {
    @SystemMessage("You are a helpful assistant.")
    Flux<String> chatStream(String message);
}
```

**Chat Memory:** Set up conversation memory with Spring context:

```java
@AiService
public interface ConversationalAssistant {
    @SystemMessage("You are a helpful assistant with memory.")
    String chat(@MemoryId String userId, String message);
}
```

## RAG Implementation

**Embedding Stores:** Configure embedding stores for RAG pipelines with Spring Data:

```java
@Configuration
public class RagConfig {

    @Bean
    public EmbeddingStore<TextSegment> embeddingStore() {
        return PgVectorEmbeddingStore.builder()
            .host("localhost")
            .port(5432)
            .database("vectordb")
            .table("embeddings")
            .dimension(1536)
            .build();
    }

    @Bean
    public EmbeddingModel embeddingModel() {
        return OpenAiEmbeddingModel.withApiKey(System.getenv("OPENAI_API_KEY"));
    }
}

@AiService
public interface RagAssistant {
    String answer(@UserMessage("Question: {{question}}") String question);
}
```

**Document Ingestion:** Use `ContentInjector` and `DocumentSplitter` for processing documents.
**Content Retrieval:** Configure `EmbeddingStoreContentRetriever` for knowledge augmentation.

## Tool Integration

**Spring Component Tools:** Define tools as Spring components:

```java
@Component
public class Calculator {
    @Tool("Calculate the sum of two numbers")
    public double add(double a, double b) {
        return a + b;
    }
}

@AiService
public interface MathAssistant {
    String solve(String problem);
}
```

## Examples

### Basic AI Service

```java
@AiService
public interface ChatAssistant {
    @SystemMessage("You are a helpful assistant.")
    String chat(String message);
}
```

### AI Service with Memory

```java
@AiService
public interface ConversationalAssistant {
    @SystemMessage("You are a helpful assistant with memory of conversations.")
    String chat(@MemoryId String userId, String message);
}
```

### AI Service with Tools

```java
@Component
public class WeatherService {
    @Tool("Get weather for a city")
    public String getWeather(String city) {
        return "Sunny, 22°C in " + city;
    }
}

@AiService
public interface WeatherAssistant {
    String getWeatherForCity(String city);
}
```

For more examples (including RAG configurations, streaming assistants, and multi-provider setups), refer to [references/examples.md](references/examples.md).

## Best Practices

- **Use Property-Based Configuration:** External configuration over hardcoded values
- **Use Profiles:** Separate configurations for development, testing, and production
- **Add Proper Logging:** Debug AI service calls and monitor performance
- **Implement Retry Mechanisms:** Handle transient failures with backoff strategies
- **Monitor Token Usage:** Track token consumption and implement limits

## References

For detailed API references and advanced configurations:
- [API Reference](references/references.md) - Complete API documentation
- [Examples](references/examples.md) - Comprehensive implementation examples
- [Configuration Guide](references/configuration.md) - Deep dive into configuration options

## Constraints and Warnings

- Store API keys securely using environment variables or secret management systems
- AI model responses are non-deterministic; tests should account for variability
- Rate limits may apply to AI providers; implement proper retry and backoff strategies
- Memory providers store conversation history; implement cleanup for multi-user scenarios
- Token costs accumulate quickly; monitor usage and implement token limits
- Streaming responses require proper error handling for partial failures
- Check provider-specific documentation for supported features
- Use explicit wiring mode when multiple chat models are configured
- Validate AI-generated outputs before use in production systems

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar skills

Everything for Backend and APIs →

From the same set93

unit-test-utility-methods Writes unit tests for utility classes and static methods, covering nulls, empty input, boundaries and floating-point precision. CX Codex +1 3,700installs nextjs-data-fetching Provides Next.js App Router data fetching patterns, covering Server Components, ISR caching strategies, and SWR or React Query client integration. CX Codex +1 3,700installs langchain4j-rag-implementation-patterns A coding-agent skill that scaffolds LangChain4j RAG pipelines: document ingestion, embedding stores, vector search and knowledge-base answers. CX Codex +1 3,700installs nx-monorepo A skill that walks the agent through Nx: workspace setup, generators, affected commands, Module Federation and CI. CX Codex +1 3,700installs langchain4j-tool-function-calling-patterns A skill that shows your agent how to expose Java methods with @Tool, register them in AiServices and handle tool execution errors. CX Codex +1 3,700installs unit-test-security-authorization A skill with patterns for unit testing Spring Security authorization: @PreAuthorize, @Secured, @RolesAllowed and custom permission evaluators. Useful when you need fast access-control tests without the full Spring Security context. CX Codex +1 3,700installs spring-data-neo4j Provides integration patterns for Spring Data Neo4j in Spring Boot projects. Helps set up node mappings, Cypher queries, and repository slice tests. CX Codex +1 3,800installs sonarqube-mcp Checks quality gates, finds SonarQube and SonarCloud issues, and explains rules before code is pushed. Use it when an agent needs project or pull request quality feedback. CX Codex +1 3,600installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor