How to Build a Java Spring AI Alibaba Chat Service with React Frontend

Learn step‑by‑step how to integrate Spring AI Alibaba into a Spring Boot backend, configure API keys, add necessary dependencies, create a CORS‑enabled chat controller, and then develop a matching React frontend that streams AI responses, enabling a complete Java‑to‑React AI chat application.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
How to Build a Java Spring AI Alibaba Chat Service with React Frontend

This article helps developers quickly master and apply Spring AI Alibaba, improving the efficiency and security of Java‑based large‑model applications.

Spring AI Introduction

When Java developers call large models, they often lack an efficient and unified application framework. Spring, a well‑known Java application framework provider, introduced Spring AI to address this gap. It adopts core ideas from LangChain and leverages Java’s object‑oriented strengths. Spring AI offers a unified interface standard, allowing developers to write code once and switch between AI service providers such as OpenAI or Alibaba Cloud. It also supports streaming output compatibility, automatic POJO mapping, and is maintained by a dedicated team for long‑term stability and security, making Java large‑model development more convenient and efficient.

Spring AI Alibaba Introduction

In domestic deployments, large models must ensure content safety while meeting business intelligence needs. Spring AI Alibaba provides strong content‑safety guarantees and is based on the Qwen‑2.5 model, which ranks top among open‑source models in the OpenCompass evaluation. It combines Alibaba Cloud best practices with the Spring AI framework, simplifying integration with various AI services and making migration and adaptation easy through a unified interface. Core advantages include support for multiple generative tasks (e.g., dialogue, text‑to‑image), compatibility with Flux stream processing, and features like Prompt Template and OutputParser, greatly enhancing development efficiency and flexibility. It also allows calling external data, enabling customized AI extensions for smarter applications.

Backend Construction Steps

1. Confirm Development Environment

Ensure JDK version is 17 or higher.

Use Spring Boot 3.3.x or later.

2. Apply for Alibaba Cloud API Key

Visit the Alibaba Cloud Bailei page and log in.

Enable the “Bailei Large Model Inference” service to obtain an API key.

Set the environment variable, e.g., export AI_DASHSCOPE_API_KEY=YOUR_API_KEY or configure it in the application properties.

3. Add Repositories and Dependencies

Because Spring AI is not yet in the Maven central repository, add the following repositories to pom.xml:

<repositories>
  <repository>
    <id>sonatype-snapshots</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    <snapshots><enabled>true</enabled></snapshots>
  </repository>
  <repository>
    <id>spring-milestones</id>
    <name>Spring Milestones</name>
    <url>https://repo.spring.io/milestone</url>
    <snapshots><enabled>false</enabled></snapshots>
  </repository>
  <repository>
    <id>spring-snapshots</id>
    <name>Spring Snapshots</name>
    <url>https://repo.spring.io/snapshot</url>
    <releases><enabled>false</enabled></releases>
  </repository>
</repositories>

Then add the following dependencies:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>3.3.4</version>
</parent>
<dependencies>
  <dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter</artifactId>
    <version>1.0.0-M2.1</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <!-- other needed dependencies -->
</dependencies>

4. Configure application.properties

Add the AI key configuration:

spring.ai.dashscope.api-key=${AI_DASHSCOPE_API_KEY}

5. Implement the Chat Controller

Create ChatController.java with CORS support and a streaming endpoint:

import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*")
public class ChatController {
    private final ChatClient chatClient;
    @Value("classpath:your-prompt-template.st")
    Resource promptTemplateResource;

    public ChatController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @GetMapping("/steamChat")
    public Flux<String> steamChat(@RequestParam String input) {
        PromptTemplate promptTemplate = new PromptTemplate(promptTemplateResource);
        Prompt prompt = promptTemplate.create(Map.of("input", input));
        return chatClient.prompt(prompt).stream().content();
    }
}

Ensure your-prompt-template.st exists under src/main/resources/, e.g.: 针对{input},给出回应。 Following these steps completes the backend integration of Spring AI Alibaba.

Frontend Construction Steps

1. Initialize a React Project

npx create-react-app frontend
cd frontend
npm install

2. Adjust Project Structure

Use the default public/index.html and src/index.js. Modify src/App.js to render a custom ChatComponent:

import React from 'react';
import ChatComponent from './components/ChatComponent';

function App() {
  return (
    <div className="App">
      <ChatComponent />
    </div>
  );
}
export default App;

3. Implement ChatComponent.js

<code>import React, { useState } from 'react';

const ChatComponent = () => {
  const [input, setInput] = useState('');
  const [messages, setMessages] = useState('');

  const handleInputChange = (event) => {
    setInput(event.target.value);
  };

  const handleSendMessage = async () => {
    if (!input.trim()) return;
    try {
      const response = await fetch(`http://localhost:8080/ai/steamChat?input=${encodeURIComponent(input)}`, { method: 'GET' });
      if (!response.ok) throw new Error('Network response was not ok');
      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let done = false;
      while (!done) {
        const { value, done: readerDone } = await reader.read();
        done = readerDone;
        const chunk = decoder.decode(value, { stream: true });
        setMessages(prev => prev + chunk);
      }
      setMessages(prev => prev + '

=============================

');
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setInput('');
    }
  };

  const handleClearMessages = () => setMessages('');

  return (
    <div>
      <input type="text" value={input} onChange={handleInputChange} placeholder="Enter your message" />
      <button onClick={handleSendMessage}>Send</button>
      <button onClick={handleClearMessages}>Clear</button>
      <div>
        <h3>Messages:</h3>
        <pre>{messages}

); }; export default ChatComponent;

4. Run the Frontend

npm start

The development server starts at http://localhost:3000. Ensure the backend is running at http://localhost:8080 and the /ai/steamChat endpoint is reachable. If CORS issues arise, verify the backend’s @CrossOrigin configuration.

Spring AI Alibaba tutorial illustration
Spring AI Alibaba tutorial illustration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring Bootspring-aiChatbot
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

0 followers
Reader feedback

How this landed with the community

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.