SpringAI入门代码--从0到1搭建DeepSeek对话案例
2026/6/24 6:22:58 网站建设 项目流程

说明:这里使用SpringBoot 3.5.8版本、JDK17版本、Maven3.9.11版本。
创建一个如下的SpringBoot项目,下面说明如何配置及编写代码。

  1. 配置pom.xml文件,增加如下依赖
<!-- 导入 Spring AI BOM,用于统一管理 Spring AI 依赖的版本, --><dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>1.0.0-SNAPSHOT</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-deepseek</artifactId></dependency></dependencies><!-- 声明仓库, 用于获取 Spring AI 以及相关预发布版本--><repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><releases><enabled>false</enabled></releases></repository><repository><name>Central Portal Snapshots</name><id>central-portal-snapshots</id><url>https://central.sonatype.com/repository/maven-snapshots/</url><releases><enabled>false</enabled></releases><snapshots><enabled>true</enabled></snapshots></repository></repositories>
  1. 在resources下创建一个application.properties文件,文件内容如下:
#配置项目名称spring.application.name=SpringAIQuickStart#配置端口server.port=8080#配置 Deepseek的基础URL、密钥和使用模型#配置 URLspring.ai.deepseek.base-url=https://api.deepseek.com#配置密钥,自己去创建spring.ai.deepseek.api-key=sk-xxxxxxxxxxxxxxxxx#配置使用模型名称spring.ai.deepseek.chat.options.model=deepseek-chat# 介于0和2之间,0表示随机性最小,2表示随机性最大。spring.ai.deepseek.chat.options.temperature=0.9
  1. 创建一个com.test.controller包,并创建一个ChatController.java文件
    具体内容下入:
packagecom.test.controller;importorg.springframework.ai.deepseek.DeepSeekChatModel;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/firstAi")publicclassChatController{@AutowiredprivateDeepSeekChatModelchatModel;@GetMapping("/generate")publicStringgenerate(@RequestParam(value="message",defaultValue="你好")Stringmessage){Stringresult=chatModel.call(message);//模型返回的内容System.out.println(result);returnresult;}}
  1. 编写启动类,创建一个SpringBootAIApplication.java文件,内容如下:
packagecom.test.controller;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassSpringBootAIApplication{publicstaticvoidmain(String[]args){SpringApplication.run(SpringBootAIApplication.class,args);}}
  1. 启动项目并测试,启动项目后,浏览器输入“http://localhost:8080/firstAi/generate?message=你是谁”,看到返回结果如下:

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询