# Spring AI 最新实战系列(二)流式输出与ChatClient
2026/7/25 14:16:25 网站建设 项目流程

使用前介绍

我们以 Alibaba 的百炼平台作为Spring-AI的模型讲解,以最新稳定版作为架构。

spring-ai 的最新版本 1.1.2 ;alibaba-spring-ai 的最新版本 1.1.0.0-RC1。

需要注意一点:最新版本的 Spring Boot 4.0.0 不能适配,需要降低版本到 3.5.8。

  • 流式输出 :使得输出更流程,快捷,提升用户体验

  • ChatClient :把各个大模型的ChatModel统一接口化,使得代码中不需要依赖底层的具体模型

    注意: 1)若项目中只有一个模型,则Spring-AI 为自动装配上这个模型;

    ​ 2)若项目中有两个以上模型,则要明确指明是装配哪个模型。

代码部分

  • 项目依赖与配置:(略,上一篇有介绍)

  • Java 代码:

    packagecom.yiyi.coding.spring.ai;importcom.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;importorg.junit.jupiter.api.Test;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;@SpringBootTestpublicclassDashScopeTest{@TestpublicvoidtestChatModel(@AutowiredDashScopeChatModeldashScopeChatModel){System.out.println(dashScopeChatModel.call("你是谁"));}/** * 流式打印,输出 Flux<String> */@TestpublicvoidtestChatModelStream(@AutowiredDashScopeChatModeldashScopeChatModel){dashScopeChatModel.stream("你是谁").toStream().forEach(System.out::println);}@TestpublicvoidtestChatClient(@AutowiredChatClient.BuilderchatClientBuilder){ChatClientchatClient=chatClientBuilder.build();chatClient.prompt("你是谁").stream().content().toStream().forEach(System.out::println);}/** * 装配具体的模型 */@TestpublicvoidtestChatClient2(@AutowiredDashScopeChatModeldashScopeChatModel){ChatClientchatClient=ChatClient.builder(dashScopeChatModel).build();chatClient.prompt("你是谁").stream().content().toStream().forEach(System.out::println);}}
  • 运行后输出的其中一段内容,采用的是流式输出:

    我是 通义千 问, 由 阿里云研发的超大规模 语言模型。我可以生成 各种类型的文本,如文章 、故事、诗歌、故事 等,并能够根据不同的 场景和需求进行变换和 扩展。此外,我还能够 回答各种问题,提供帮助 和解决方案。我 被设计用来协助 用户撰写故事、诗歌 、公文, 提供信息查询, 编程等,能够 支持多种语言,满足 国际化的使用需求。很高兴 为您服务!

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

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

立即咨询