langchain4j-spring-boot-integration by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-spring-boot-integration要实现 LangChain4j 与 Spring Boot 应用程序的集成,请遵循这份全面的指南,涵盖自动配置、声明式 AI 服务、聊天模型、嵌入存储以及用于构建 AI 驱动应用程序的生产就绪模式。
在以下情况下实现 LangChain4j 与 Spring Boot 的集成:
LangChain4j Spring Boot 集成通过 Spring Boot starter 提供声明式 AI 服务,能够根据属性自动配置 AI 组件。该集成结合了 Spring 依赖注入的强大功能与 LangChain4j 的 AI 能力,允许开发者使用基于接口的定义和注解来创建 AI 驱动的应用程序。
实现 LangChain4j 与 Spring Boot 的基本设置:
添加依赖:
<!-- Core LangChain4j -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring-boot-starter</artifactId>
<version>1.8.0</version> // Use latest version
</dependency>
<!-- OpenAI Integration -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
配置属性:
# 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
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
创建声明式 AI 服务:
@AiService
interface CustomerSupportAssistant {
@SystemMessage("You are a helpful customer support agent for TechCorp.")
String handleInquiry(String customerMessage);
}
按照以下分步说明将 LangChain4j 集成到 Spring Boot 中:
在你的 pom.xml 或 build.gradle 中包含必要的 Spring Boot starter:
<!-- 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>
在 application.properties 或 application.yml 中设置 AI 模型配置:
# 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
或使用 YAML:
langchain4j:
open-ai:
chat-model:
api-key: ${OPENAI_API_KEY}
model-name: gpt-4o-mini
temperature: 0.7
timeout: 60s
max-tokens: 1000
使用注解定义一个 AI 服务接口:
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 the following text to {{language}}: {{text}}")
String translate(String text, String language);
}
确保 AI 服务位于 Spring 扫描的包中:
@SpringBootApplication
@ComponentScan(basePackages = {
"com.yourcompany",
"dev.langchain4j.service.spring" // For AiService scanning
})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Service
public class CustomerService {
private final CustomerSupportAssistant assistant;
public CustomerService(CustomerSupportAssistant assistant) {
this.assistant = assistant;
}
public String processCustomerQuery(String query) {
return assistant.handleInquiry(query);
}
}
实现 LangChain4j 的 Spring Boot 配置:
基于属性的配置: 通过应用程序属性为不同的提供商配置 AI 模型。
手动 Bean 配置: 对于高级配置,使用 @Configuration 手动定义 bean。
多提供商支持: 支持多个 AI 提供商,在需要时进行显式装配。
实现基于接口的 AI 服务定义:
基础 AI 服务: 使用 @AiService 注解创建接口,并使用消息模板定义方法。
流式 AI 服务: 使用 Reactor 或 Project Reactor 实现流式响应。
显式装配: 使用 @AiService(wiringMode = EXPLICIT, chatModel = "modelBeanName") 指定要使用的模型。
实现 RAG 系统:
嵌入存储: 配置各种嵌入存储(PostgreSQL/pgvector、Neo4j、Pinecone 等)。
文档摄取: 实现文档处理和嵌入生成。
内容检索: 为知识增强设置内容检索机制。
实现 AI 工具集成:
Spring 组件工具: 使用 @Tool 注解将工具定义为 Spring 组件。
数据库访问工具: 创建用于数据库操作和业务逻辑的工具。
工具注册: 自动向 AI 服务注册工具。
@AiService
public interface ChatAssistant {
@SystemMessage("You are a helpful assistant.")
String chat(String message);
}
@AiService
public interface ConversationalAssistant {
@SystemMessage("You are a helpful assistant with memory of conversations.")
String chat(@MemoryId String userId, String message);
}
@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);
}
// Spring automatically registers the Calculator tool
@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);
}
要了解实现模式,请参考 references/examples.md 中的综合示例。
实现生产就绪的 AI 应用程序:
有关详细的 API 参考、高级配置和其他模式,请参阅:
每周安装量
343
代码仓库
GitHub 星标数
173
首次出现
2026年2月3日
安全审计
安装于
claude-code270
gemini-cli263
opencode262
cursor261
codex257
github-copilot242
To accomplish integration of LangChain4j with Spring Boot applications, follow this comprehensive guidance covering auto-configuration, declarative AI Services, chat models, embedding stores, and production-ready patterns for building AI-powered applications.
To accomplish integration of LangChain4j with Spring Boot when:
LangChain4j Spring Boot integration provides declarative AI Services through Spring Boot starters, enabling automatic configuration of AI components based on properties. The integration combines the power of Spring dependency injection with LangChain4j's AI capabilities, allowing developers to create AI-powered applications using interface-based definitions with annotations.
To accomplish basic setup of LangChain4j with Spring Boot:
Add Dependencies:
<!-- Core LangChain4j -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring-boot-starter</artifactId>
<version>1.8.0</version> // Use latest version
</dependency>
<!-- OpenAI Integration -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
Configure 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
Create Declarative AI Service:
@AiService
interface CustomerSupportAssistant {
@SystemMessage("You are a helpful customer support agent for TechCorp.")
String handleInquiry(String customerMessage);
}
Follow these step-by-step instructions to integrate LangChain4j with Spring Boot:
Include the necessary Spring Boot starters in your pom.xml or build.gradle:
<!-- 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>
Set up the AI model configuration in application.properties or application.yml:
# 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:
langchain4j:
open-ai:
chat-model:
api-key: ${OPENAI_API_KEY}
model-name: gpt-4o-mini
temperature: 0.7
timeout: 60s
max-tokens: 1000
Define an AI service interface with annotations:
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 the following text to {{language}}: {{text}}")
String translate(String text, String language);
}
Ensure the AI service is in a package scanned by Spring:
@SpringBootApplication
@ComponentScan(basePackages = {
"com.yourcompany",
"dev.langchain4j.service.spring" // For AiService scanning
})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Service
public class CustomerService {
private final CustomerSupportAssistant assistant;
public CustomerService(CustomerSupportAssistant assistant) {
this.assistant = assistant;
}
public String processCustomerQuery(String query) {
return assistant.handleInquiry(query);
}
}
To accomplish Spring Boot configuration for LangChain4j:
Property-Based Configuration: Configure AI models through application properties for different providers.
Manual Bean Configuration: For advanced configurations, define beans manually using @Configuration.
Multiple Providers: Support for multiple AI providers with explicit wiring when needed.
To accomplish interface-based AI service definitions:
Basic AI Service: Create interfaces with @AiService annotation and define methods with message templates.
Streaming AI Service: Implement streaming responses using Reactor or Project Reactor.
Explicit Wiring: Specify which model to use with @AiService(wiringMode = EXPLICIT, chatModel = "modelBeanName").
To accomplish RAG system implementation:
Embedding Stores: Configure various embedding stores (PostgreSQL/pgvector, Neo4j, Pinecone, etc.).
Document Ingestion: Implement document processing and embedding generation.
Content Retrieval: Set up content retrieval mechanisms for knowledge augmentation.
To accomplish AI tool integration:
Spring Component Tools: Define tools as Spring components with @Tool annotations.
Database Access Tools: Create tools for database operations and business logic.
Tool Registration: Automatically register tools with AI services.
@AiService
public interface ChatAssistant {
@SystemMessage("You are a helpful assistant.")
String chat(String message);
}
@AiService
public interface ConversationalAssistant {
@SystemMessage("You are a helpful assistant with memory of conversations.")
String chat(@MemoryId String userId, String message);
}
@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);
}
// Spring automatically registers the Calculator tool
@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);
}
To understand implementation patterns, refer to the comprehensive examples in references/examples.md.
To accomplish production-ready AI applications:
For detailed API references, advanced configurations, and additional patterns, refer to:
Weekly Installs
343
Repository
GitHub Stars
173
First Seen
Feb 3, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code270
gemini-cli263
opencode262
cursor261
codex257
github-copilot242
超能力技能使用指南:AI助手技能调用优先级与工作流程详解
40,300 周安装
AI驱动知识库搜索工具 - Nowledge Mem搜索记忆技能,提升开发效率
338 周安装
Self-Improving Agent:AI智能体自我改进与知识沉淀技能指南
338 周安装
OpenAI图像生成脚本:批量生成DALL-E 3/GPT图像,支持多模型参数与自动图库
338 周安装
Things 3 命令行工具 - 在终端管理你的待办事项,支持读写和自动化
338 周安装
Jina Reader:AI网页内容提取工具,保护IP,支持搜索与事实核查
338 周安装
Solana 命令行工具:支付、钱包与交易一站式管理 | Solana CLI 指南
338 周安装