跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
Java大前端java

Spring Boot 集成 ECharts 实现数据可视化实战

Spring Boot 结合 ECharts 和 Thymeleaf,通过后端提供产品销量数据,前端渲染饼图展示。示例涵盖依赖配置、实体类定义、服务层逻辑及前端图表初始化,实现了从数据获取到可视化的完整链路,适用于后台管理系统中的报表需求。

怪力乱神发布于 2026/3/24更新于 2026/10/789 浏览
Spring Boot 集成 ECharts 实现数据可视化实战

Spring Boot 集成 ECharts 实现数据可视化实战

在开发后台管理系统时,我们经常需要将枯燥的数据转化为直观的图表。Spring Boot 配合 ECharts 是 Java 生态中非常经典的组合,既能利用后端强大的业务处理能力,又能发挥前端图表库的交互优势。

核心工具选型

数据可视化的本质是将抽象数据具象化。常见的工具有 ECharts、Highcharts 和 D3.js 等。对于国内项目,ECharts 因其文档完善、社区活跃且对中文支持友好,通常是首选。它基于 JavaScript,轻量级且功能强大,非常适合嵌入到 Web 应用中。

项目搭建与依赖配置

首先,我们需要创建一个标准的 Spring Boot 项目。为了渲染页面,推荐使用 Thymeleaf 模板引擎,这样可以直接在后端传递数据给前端。

在 pom.xml 中添加以下核心依赖:

<dependencies>
    <!-- Web 模块 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Thymeleaf 模板引擎 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

同时,在 application.properties 中配置一下服务器端口和 Thymeleaf 缓存(开发环境建议关闭):

server.port=8080
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/

后端数据层设计

为了让示例更聚焦于可视化逻辑,这里使用内存列表模拟数据库。实际项目中请替换为 JPA 或 MyBatis。

实体类 Product

public class Product {
    private Long id;
    private String productId;
    private String productName;
    private double price;
    private int sales;

    public Product() {}

    public Product(Long id, String productId, String productName, double price, int sales) {
        this.id = id;
        this.productId = productId;
        this.productName = productName;
        this.price = price;
        this.sales = sales;
    }

    // Getter 和 Setter 方法省略,保持标准规范即可
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getProductId() { return productId; }
    public void setProductId(String productId) { this.productId = productId; }
    public String getProductName() { return productName; }
    public void setProductName(String productName) { this.productName = productName; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
    public int getSales() { return sales; }
    public void setSales(int sales) { this.sales = sales; }
}

仓储层 (Repository)

import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ProductRepository {
    private List<Product> products = new ArrayList<>();

    public ProductRepository() {
        products.add(new Product(1L, "P001", "手机", 1000.0, 100));
        products.add(new Product(2L, "P002", "电脑", 5000.0, 50));
        products.add(new Product(3L, "P003", "电视", 3000.0, 80));
        products.add(new Product(4L, "P004", "手表", 500.0, 200));
        products.add(new Product(5L, "P005", "耳机", 300.0, 150));
    }

    public List<Product> getAllProducts() {
        return products;
    }
}

服务层 (Service)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List<Product> getAllProducts() {
        return productRepository.getAllProducts();
    }
}

控制器 (Controller)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;

@Controller
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping("/")
    public String listProducts(Model model) {
        List<Product> products = productService.getAllProducts();
        model.addAttribute("products", products);
        return "product-list";
    }
}

前端页面与图表渲染

这是最关键的一步。我们需要引入 ECharts 的 CDN 资源,并在 HTML 中定义容器,最后通过 JavaScript 将后端传来的数据填充进去。

Thymeleaf 模板 (product-list.html)

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>产品销量看板</title>
    <!-- 引入 ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
</head>
<body>
    <h1>产品销量统计</h1>
    
    <!-- 图表容器 -->
    <div id="salesChart" style="width: 800px; height: 400px;"></div>

    <script>
        // 初始化图表实例
        var chartDom = document.getElementById('salesChart');
        var myChart = echarts.init(chartDom);
        
        // 准备数据:从后端传入的列表中解析
        var productNames = [];
        var productSales = [];
        
        // 注意:这里使用了 Thymeleaf 语法遍历后端对象
        <th:block th:each="product : ${products}">
            productNames.push('<span th:text="${product.productName}"></span>');
            productSales.push(<span th:text="${product.sales}"></span>);
        </th:block>

        var option = {
            title: {
                text: '各产品销量分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center'
            },
            series: [{
                name: '销量',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 20,
                        fontWeight: 'bold'
                    }
                },
                data: [
                    <th:block th:each="product : ${products}">
                        {value: <span th:text="${product.sales}"></span>, name: '<span th:text="${product.productName}"></span>'},
                    </th:block>
                ]
            }]
        };

        // 渲染图表
        if (option && typeof option === 'object') {
            myChart.setOption(option);
        }
    </script>
</body>
</html>

运行与验证

启动应用后访问 http://localhost:8080/api/products/,你将看到一个动态加载的产品列表以及右侧的饼图。点击饼图中的扇区,还能看到具体的数值高亮效果。

这种模式不仅适用于产品销量,用户活跃度、订单状态占比等场景都可以复用。关键在于后端提供结构化的 JSON 数据,前端负责将其映射为图表配置项。

目录

  1. Spring Boot 集成 ECharts 实现数据可视化实战
  2. 核心工具选型
  3. 项目搭建与依赖配置
  4. 后端数据层设计
  5. 前端页面与图表渲染
  6. 运行与验证

更多推荐文章

查看全部
  • 如何在 Windows 本地部署开源大语言模型:基于 Ollama 与 Open WebUI
  • MyBatisPlus 与 Thymeleaf 全栈分页整合方案
  • Whisper.cpp 量化版本清单与 ggml 格式模型下载指南
  • 分布式文件系统 HDFS 存储原理
  • 深入解析 Linux 内存管理:三大分配器原理
  • Whisper.cpp 量化模型清单与 ggml 格式下载指南
  • 利用 AI 工具组合高效完成文献综述的实践指南
  • OpenAI 回击马斯克骚扰指控;微软清华提出 Diff Transformer
  • 基于 AI 辅助的在线图书借阅平台设计与实现
  • Cardinal:macOS 极简本地文件检索工具深度解析
  • MusePublic Art Studio 镜像免配置:开箱即用的开源 AI 绘画工具部署
  • ASP.NET 图片上传与缩略图生成实战
  • 大语言模型(LLM)学习路径与核心资源指南
  • AI 大模型:国内外发展现状与趋势分析
  • Java 哈希数据结构与经典用法
  • OpenClaw 对接 Stable Diffusion 教程
  • 12 大主流 AI 前端组件库盘点:Ant Design X ChatUI 等
  • 基于 DeepSeek R1 和 Ollama 构建 RAG 系统实战
  • 使用阿里开源 CoPaw 在魔搭创空间部署个人 AI 助理
  • RISC-V 处理器实战:Verilog RTL 设计与 FPGA 原型验证

相关免费在线工具

  • Keycode 信息

    查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online

  • Escape 与 Native 编解码

    JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online

  • JavaScript / HTML 格式化

    使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online

  • JavaScript 压缩与混淆

    Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online