Spring Boot 4.0 与 Spring Cloud Alibaba 2025 整合指南
介绍 Spring Boot 4.0 与 Spring Cloud Alibaba 2025 版本的整合方案。涵盖环境配置、Maven 依赖管理、Nacos 服务注册与配置中心集成、Sentinel 流量控制、OpenFeign 服务调用及 Docker 容器化部署。通过示例代码演示了服务提供者、消费者、动态配置刷新及异常处理等关键步骤,提供了一套完整的微服务开发实践参考。

介绍 Spring Boot 4.0 与 Spring Cloud Alibaba 2025 版本的整合方案。涵盖环境配置、Maven 依赖管理、Nacos 服务注册与配置中心集成、Sentinel 流量控制、OpenFeign 服务调用及 Docker 容器化部署。通过示例代码演示了服务提供者、消费者、动态配置刷新及异常处理等关键步骤,提供了一套完整的微服务开发实践参考。

本文将详细介绍如何在 Spring Boot 4.0 中整合 Spring Cloud Alibaba 2025 最新版本。Spring Cloud Alibaba 为分布式应用开发提供了一站式解决方案,包含服务发现、配置管理、流量控制等核心功能。
springboot4-sc-alibaba-demo/
├── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ ├── Springboot4ScAlibabaApplication.java
│ │ ├── controller/
│ │ ├── service/
│ │ └── config/
│ └── resources/
│ ├── application.yml
│ └── bootstrap.yml
├── pom.xml
└── README.md
访问 https://start.spring.io/ 创建基础项目,选择:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.0</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>springboot4-sc-alibaba-demo</artifactId>
<version>1.0.0</version>
<name>springboot4-sc-alibaba-demo</name>
<description>Spring Boot 4.0 with Spring Cloud Alibaba 2025</description>
<properties>
<java.version>21</java.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Spring Cloud 版本 -->
<spring-cloud.version>2025.0.0</spring-cloud.version>
<!-- Spring Cloud Alibaba 版本 -->
<spring-cloud-alibaba.version>2025.0.0</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Cloud 依赖管理 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud Alibaba 依赖管理 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Spring Cloud Alibaba Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Spring Cloud Alibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- Spring Cloud Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- Spring Cloud OpenFeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- Spring Cloud LoadBalancer -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!-- Spring Boot Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
spring:
application:
name: demo-service
profiles:
active: dev
cloud:
nacos:
config:
server-addr: localhost:8848
file-extension: yaml
namespace: dev-namespace
group: DEFAULT_GROUP
extension-configs:
- data-id: shared-config.yaml
group: SHARED_GROUP
refresh: true
discovery:
server-addr: localhost:8848
namespace: dev-namespace
group: DEFAULT_GROUP
metadata:
version: 1.0
sentinel:
transport:
dashboard: localhost:8080
eager: true
datasource:
ds1:
nacos:
server-addr: localhost:8848
data-id: ${spring.application.name}-sentinel
group-id: DEFAULT_GROUP
data-type:
server:
port: 8081
servlet:
context-path: /demo
spring:
main:
allow-bean-definition-overriding: true
mvc:
throw-exception-if-no-handler-found: true
web:
resources:
add-mappings: false
management:
endpoints:
web:
exposure:
include: health,info,metrics
endpoint:
health:
show-details: always
feign:
sentinel:
enabled: true
client:
config:
default:
connect-timeout: 5000
read-timeout: 5000
logger-level: basic
logging:
level:
com.example: debug
com.alibaba.nacos: warn
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现
@EnableFeignClients(basePackages = "com.example.service") // 启用 Feign 客户端
public class Springboot4ScAlibabaApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot4ScAlibabaApplication.class, args);
}
}
package com.example.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class DemoController {
@Value("${server.port}")
private String port;
@GetMapping("/hello")
public String hello(@RequestParam String name) {
return String.format("Hello %s, from port: %s", name, port);
}
@GetMapping("/health")
public String health() {
return "Service is healthy";
}
}
package com.example.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "demo-service", path = "/demo/api")
public interface DemoServiceClient {
@GetMapping("/hello")
String sayHello(@RequestParam String name);
@GetMapping("/health")
String healthCheck();
}
package com.example.service;
import org.springframework.stereotype.Component;
@Component
public class DemoServiceFallback implements DemoServiceClient {
@Override
public String sayHello(String name) {
return "Fallback: Hello " + name;
}
@Override
public String healthCheck() {
return "Fallback: Service unavailable";
}
}
@FeignClient(
name = "demo-service",
path = "/demo/api",
fallback = DemoServiceFallback.class
)
public interface DemoServiceClient {
// 接口方法保持不变
}
package com.example.controller;
import com.example.service.DemoServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
@Autowired
private DemoServiceClient demoServiceClient;
@GetMapping("/call-hello")
public String callHello(@RequestParam String name) {
return demoServiceClient.sayHello(name);
}
}
package com.example.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/config")
@RefreshScope // 支持配置动态刷新
public class ConfigController {
@Value("${app.config.demo:defaultValue}")
private String demoConfig;
@Value("${app.feature.enabled:false}")
private boolean featureEnabled;
@GetMapping("/demo")
public String getDemoConfig() {
return "Current config: " + demoConfig + ", Feature enabled: " + featureEnabled;
}
}
在 Nacos 控制台创建 Data ID: demo-service-dev.yaml,配置内容:
app:
config:
demo: "This is dynamic config from Nacos"
feature:
enabled: true
server:
port: 8081
logging:
level:
com.example: info
package com.example.config;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class SentinelConfig {
@Bean
public BlockExceptionHandler sentinelBlockExceptionHandler() {
return new CustomBlockExceptionHandler();
}
static class CustomBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
Map<String, Object> result = <>();
(e FlowException) {
result.put(, );
result.put(, );
} (e DegradeException) {
result.put(, );
result.put(, );
} (e ParamFlowException) {
result.put(, );
result.put(, );
} (e SystemBlockException) {
result.put(, );
result.put(, );
} (e AuthorityException) {
result.put(, );
result.put(, );
} {
result.put(, );
result.put(, );
}
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setCharacterEncoding();
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
().writeValue(response.getWriter(), result);
}
}
}
package com.example.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/sentinel")
public class SentinelController {
@GetMapping("/resource")
@SentinelResource(
value = "protectedResource",
blockHandler = "handleBlock",
fallback = "handleFallback"
)
public String protectedResource() {
return "This is a protected resource";
}
// 限流处理
public String handleBlock(BlockException ex) {
return "请求过于频繁,请稍后重试";
}
// 降级处理
public String handleFallback(Throwable ex) {
return "服务暂时不可用,请稍后重试";
}
}
package com.example.config;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;
import java.util.Arrays;
import java.util.List;
@Configuration
public class LoadBalancerConfig {
@Bean
public ServiceInstanceListSupplier serviceInstanceListSupplier() {
return new DemoServiceInstanceListSupplier("demo-service");
}
static class DemoServiceInstanceListSupplier implements ServiceInstanceListSupplier {
private final String serviceId;
public DemoServiceInstanceListSupplier(String serviceId) {
this.serviceId = serviceId;
}
@Override
public String getServiceId() {
return serviceId;
}
@Override
public Flux<List<ServiceInstance>> get() {
// 这里可以自定义服务实例发现逻辑
return Flux.just(Arrays.asList());
}
}
}
package com.example.config;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public Map<String, Object> handleException(Exception e) {
Map<String, Object> result = new HashMap<>();
result.put("code", 500);
result.put("message", "系统异常:" + e.getMessage());
return result;
}
}
# 启动 Nacos (需要提前下载)
sh nacos/bin/startup.sh -m standalone
# 启动 Sentinel Dashboard (需要提前下载)
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -jar sentinel-dashboard.jar
package com.example;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.core.env.Environment;
import java.util.Objects;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.example.service")
public class Springboot4ScAlibabaApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(Springboot4ScAlibabaApplication.class).bannerMode(Banner.Mode.CONSOLE).run(args);
}
public void printInfo(Environment env) {
String port = env.getProperty("server.port");
String contextPath = Objects.requireNonNullElse(env.getProperty("server.servlet.context-path"), "");
System.out.println("\n----------------------------------------------------------");
System.out.println("Application is running! Access URLs:");
System.out.println("Local: \t\thttp://localhost:" + port + contextPath);
System.out.println("External: \thttp://" + getHostAddress() + ":" + port + contextPath);
System.out.println("Profile(s): \t" + String.join(, env.getActiveProfiles()));
System.out.println();
}
String {
{
java.net.InetAddress.getLocalHost().getHostAddress();
} (Exception e) {
;
}
}
}
package com.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/actuator")
public class ActuatorController {
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/services")
public List<String> getServices() {
return discoveryClient.getServices().stream()
.map(service -> service + ": " + discoveryClient.getInstances(service))
.collect(Collectors.toList());
}
@GetMapping("/info")
public String info() {
return "Spring Boot 4.0 with Spring Cloud Alibaba 2025";
}
}
FROM openjdk:21-jdk-slim
# 设置工作目录
WORKDIR /app
# 复制 JAR 文件
COPY target/springboot4-sc-alibaba-demo-1.0.0.jar app.jar
# 暴露端口
EXPOSE 8080
# 设置 JVM 参数
ENV JAVA_OPTS="-Xmx512m -Xms256m -Djava.security.egd=file:/dev/./urandom"
# 启动应用
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]
version: '3.8'
services:
nacos:
image: nacos/nacos-server:latest
container_name: nacos-server
environment:
- MODE=standalone
ports:
- "8848:8848"
networks:
- sc-alibaba-net
sentinel:
image: bladex/sentinel-dashboard:latest
container_name: sentinel-dashboard
ports:
- "8080:8080"
networks:
- sc-alibaba-net
demo-app:
build: .
container_name: demo-service
ports:
- "8081:8081"
environment:
- SPRING_PROFILES_ACTIVE=docker
- SPRING_CLOUD_NACOS_CONFIG_SERVER-ADDR=nacos:8848
- SPRING_CLOUD_NACOS_DISCOVERY_SERVER-ADDR=nacos:8848
- SPRING_CLOUD_SENTINEL_TRANSPORT_DASHBOARD=sentinel:8080
depends_on:
- nacos
- sentinel
networks:
-
本文详细介绍了 Spring Boot 4.0 与 Spring Cloud Alibaba 2025 最新版本的完整整合方案,包括:
通过这套完整的微服务解决方案,您可以快速构建高可用、可扩展的分布式应用系统。记得根据实际生产环境需求调整配置参数和安全设置。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online