1.引入依赖
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-spring-boot-starter</artifactId>
<version>1.0.0-beta3</version>
</dependency>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring-boot-starter</artifactId>
<version>1.0.0-beta3</version>
</dependency>
2.声明用于封装聊天方法的接口
package com.shenma.service;
/**
* @author 军哥
* @version 1.0
* @description: 声明用于封装聊天方法的接口
* @date 2026/4/3 16:05
*/
public interface ConsultantService {
//用于聊天的方法,message为用户输入的内容
public String chat(String message);
}
3.使用AiServices为接口创建代理对象
package com.shenma.config;
import com.shenma.service.ConsultantService;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 军哥
* @version 1.0
* @description: TODO
* @date 2026/4/3 16:06
*/
@Configuration
public class CommonConfig {
@Autowired
private OpenAiChatModel model;
/**
* @description: 创建一个咨询师服务
* @params []
* @return com.shenma.service.ConsultantService
* @author 军哥
* @date 2026/4/3 16:07
*/
@Bean
public ConsultantService consultantService() {
//创建AIService
ConsultantService cs = AiServices.create(ConsultantService.class, model);
return cs;
}
}
4.在controller中注入并使用
这里的consultantService是我们创建的代理对象。
package com.shenma.controller;
import com.shenma.service.ConsultantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 军哥
* @version 1.0
* @description: TODO
* @date 2026/4/3 16:16
*/
@RestController
@RequestMapping("/chat")
public class ChatController {
@Autowired
private ConsultantService consultantService;
@PostMapping("/chat")
public String chat(@RequestParam("message") String message){
String result = consultantService.chat(message);
return result;
}
}
5.运行效果

源码仓库
https://gitee.com/ywbingchuan/server-ai-demo/tree/master/demo-ai-services