Artificial Intelligence 9 min read

Build AI-Powered Spring Boot Apps with Alibaba Tongyi: A Hands‑On Guide

This tutorial walks through setting up Spring AI 0.8.1 with Spring Boot 3.1.1, configuring Alibaba Tongyi model access, and implementing chat, streaming, image, and audio generation endpoints using Java code and vector database integrations.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Build AI-Powered Spring Boot Apps with Alibaba Tongyi: A Hands‑On Guide

Environment: Spring Boot 3.1.1 + Spring AI 0.8.1.

1. Introduction

Spring AI simplifies adding AI capabilities to applications without adding unnecessary complexity, offering abstractions that enable easy component swapping.

Key features include support for major model providers (OpenAI, Microsoft, Amazon, Google, Huggingface), chat and text‑to‑image models, a portable API for chat and embedding models, POJO mapping of model outputs, and integration with major vector databases such as Azure Vector Search, Chroma, Milvus, Neo4j, PostgreSQL/PGVector, Pinecone, Qdrant, Redis, and Weaviate.

Spring Boot auto‑configuration and starters are provided for AI models and vector stores, along with an ETL framework for data engineering.

2. Practical Example – Alibaba AI

Alibaba AI is built on Spring AI and uses the Tongyi model service (Model‑as‑a‑Service) to provide chat, image, and speech capabilities.

2.1 Dependency & Configuration

<code>&lt;dependency&gt;
  &lt;groupId&gt;com.alibaba.cloud&lt;/groupId&gt;
  &lt;artifactId&gt;spring-cloud-starter-alibaba-ai&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependencyManagement&gt;
  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.alibaba.cloud&lt;/groupId&gt;
      &lt;artifactId&gt;spring-cloud-alibaba-dependencies&lt;/artifactId&gt;
      &lt;version&gt;${spring.cloud.alibaba.version}&lt;/version&gt;
      &lt;type&gt;pom&lt;/type&gt;
      &lt;scope&gt;import&lt;/scope&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/dependencyManagement&gt;</code>

Manual download of spring-ai-core-0.8.1 may be required from https://repo.spring.io/ui/native/milestone/org/springframework/ai/spring-ai-core/0.8.1/ .

<code>spring:
  cloud:
    ai:
      tongyi:
        apiKey: sk-xxxoooxxxooo</code>

Obtain the Tongyi API key at https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key .

2.2 Chat Service

<code>@Service
public class AiService {
  private final ChatClient chatClient;
  private final StreamingChatClient streamChatClient;

  public AiService(ChatClient chatClient, StreamingChatClient streamChatClient) {
    this.chatClient = chatClient;
    this.streamChatClient = streamChatClient;
  }

  public String normalCompletion(String message) {
    Prompt prompt = new Prompt(new UserMessage(message));
    return this.chatClient.call(prompt).getResult().getOutput().getContent();
  }

  public Flux&lt;ChatResponse&gt; streamCompletion(String message) {
    Prompt prompt = new Prompt(new UserMessage(message));
    return this.streamChatClient.stream(prompt);
  }
}</code>

Streaming requires the spring-boot-starter-webflux dependency.

<code>private final AiService aiService;
public AiController(AiService aiService) {
  this.aiService = aiService;
}

@GetMapping("/normal")
public String normal(String message) {
  return this.aiService.normalCompletion(message);
}

@GetMapping("/stream")
public Flux&lt;ChatResponse&gt; stream(String message) {
  return this.aiService.streamCompletion(message);
}</code>

Test the endpoints with message=什么是Spring AI . The streaming endpoint returns incremental output resembling a typing effect.

2.3 Image Generation

<code>private ImageClient imageClient;
/**
 * @param instructions Image description
 * @param options       Image specifications (size, count, format)
 */
public ImageResponse genImage(String instructions, ImageOptions options) {
  ImagePrompt request = new ImagePrompt(instructions, options);
  return this.imageClient.call(request);
}</code>
<code>public class ImageOptionsDTO extends TongYiImagesOptions {
  /**图片描述*/
  private String instructions;
  // getter, setter
}</code>
<code>@PostMapping("/image")
public void image(@RequestBody ImageOptionsDTO image) {
  ImageResponse resp = this.aiService.genImage(image.getInstructions(), image);
  resp.getResults().forEach(imgGen -> {
    Image img = imgGen.getOutput();
    System.out.println(img.getB64Json());
    System.out.println(img.getUrl());
  });
}</code>

Generated images are returned as Base64 strings or temporary URLs.

2.4 Speech Generation

<code>private final ModelClient&lt;SpeechPrompt, SpeechResponse&gt; modelClient;
/**
 * @param instructions Text to synthesize
 * @param options       Speech configuration
 */
public SpeechResponse genAudio(String instructions, ModelOptions options) {
  if (options instanceof TongYiAudioSpeechOptions speechOptions) {
    SpeechPrompt request = new SpeechPrompt(instructions, speechOptions);
    return this.modelClient.call(request);
  }
  return null;
}</code>
<code>public class AudioOptionsDTO extends TongYiAudioSpeechOptions {
  /**文本描述*/
  private String instructions;
  // getter, setter
}</code>
<code>@PostMapping("/audio")
public void audio(@RequestBody AudioOptionsDTO audio) {
  SpeechResponse resp = this.aiService.genAudio(audio.getInstructions(), audio);
  resp.getResults().forEach(speech -> {
    ByteBuffer buffer = speech.getOutput();
    Path path = Paths.get("e:/aaaa.wav");
    try (FileChannel channel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
      while (buffer.hasRemaining()) {
        channel.write(buffer);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  });
}</code>

The generated audio file is saved locally and can be played back.

Images illustrating the normal, streaming, image, and audio results are shown below.

JavaSpring BootSpring AIimage generationSpeech SynthesisChatAlibaba AI
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.