Spring Boot 数据可视化与图表集成

核心概念
在 Java 开发中,数据可视化是提升系统交互体验的关键。简单来说,就是把枯燥的数据通过图表、地图或仪表盘直观呈现,帮助用户快速发现规律并辅助决策。
常用的图表工具包括 ECharts(百度开源)、Highcharts、D3.js 以及商业化的 Tableau 等。对于 Spring Boot 项目而言,ECharts 因其轻量且功能强大,往往是首选方案。它不仅能实现图表的创建与展示,还能显著提升数据的可读性。
集成实战:Spring Boot + ECharts
将图表嵌入 Spring Boot 应用,通常涉及后端接口准备和前端页面渲染两部分。下面我们以产品销量统计为例,梳理整个流程。
1. 项目依赖配置
首先确保项目中引入了 Web 和 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
# 服务器端口
server.port=8080
# Thymeleaf 配置
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
2. 后端数据层设计
我们需要定义实体类来承载数据,并通过 Repository 模拟数据访问。这里以 Product 为例,包含 ID、名称、价格和销量等信息。
Product.java
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 方法省略,实际开发中建议使用 Lombok 简化
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public int getSales() { return sales; }
public void setSales(int sales) { this.sales = sales; }
}
ProductRepository.java
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;
}
}
ProductService.java
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();
}
}
ProductController.java
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 getAllProducts(Model model) {
List<Product> products = productService.getAllProducts();
model.addAttribute("products", products);
return "product-list";
}
}
3. 前端页面与图表渲染
使用 Thymeleaf 处理模板,并在页面中引入 ECharts 库。注意 JS 代码需要正确获取后端传递的数据。
product-list.html
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>产品列表</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
</head>
<body>
<h1>产品列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>产品名称</th>
<th>价格</th>
<th>销量</th>
</tr>
</thead>
<tbody>
<tr th:each="product : ${products}">
<td th:text="${product.id}"></td>
<td th:text="${product.productName}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.sales}"></td>
</tr>
</tbody>
</table>
<h2>产品销量图表</h2>
<div id="salesChart" style="width: 800px;height: 400px;"></div>
<script>
var chartDom = document.getElementById('salesChart');
var myChart = echarts.init(chartDom);
// 从后端获取的数据准备
var productNames = [];
var productSales = [];
<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%'],
data: [
<th:block th:each="product : ${products}">
{value: <span th:text="${product.sales}"></span>, name:'<span th:text="${product.productName}"></span>'},
</th:block>
]
}]
};
myChart.setOption(option);
</script>
</body>
</html>
启动应用后,访问 http://localhost:8080/api/products/ 即可看到产品列表及对应的饼图分析。
应用场景
这种集成模式在实际业务中非常灵活,常见场景包括:
- 产品信息看板:展示商品库存、价格分布。
- 用户行为分析:统计用户活跃度、登录频次。
- 订单监控:实时展示订单量趋势。
- 销售报表:多维度对比销售业绩。
关键在于根据具体业务需求选择合适的图表类型(如折线图看趋势,饼图看占比),并将后端数据准确映射到前端配置项中。
小结
通过上述步骤,我们完成了 Spring Boot 与 ECharts 的集成。核心在于后端提供结构化数据,前端利用 JavaScript 库进行渲染。掌握这一流程,就能轻松应对各类数据展示需求。后续可进一步探索微服务架构下的图表性能优化问题。

