SpringBoot 整合 nacos 配置中心

前提

  • nacos 版本是 3.2.4

依赖与配置

pom.xml 依赖版本

xml 复制代码
 <dependencyManagement>
     <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-dependencies</artifactId>
       <version>4.0.8</version>
       <type>pom</type>
       <scope>import</scope>
     </dependency>
     <dependency>
       <groupId>com.alibaba.cloud</groupId>
       <artifactId>spring-cloud-alibaba-dependencies</artifactId>
       <version>2025.1.0.0</version>
       <type>pom</type>
       <scope>import</scope>
     </dependency>
     <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-dependencies</artifactId>
       <version>2025.1.3</version>
       <type>pom</type>
       <scope>import</scope>
     </dependency>
   </dependencies>
 </dependencyManagement>

<dependencies>
     <dependency>
         <groupId>com.alibaba.cloud</groupId>
         <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
     </dependency>
</dependencies>

application.yml 配置

yaml 复制代码
spring:
  config:
    import:
      - nacos:example-auth?refreshEnabled=true
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        group: DEFAULT_GROUP
        refresh-enabled: true
        file-extension: yaml
      username: nacos
      password: nacos

注意:

  • example-auth 是 nacos 中的 Data ID,如下图所示:

  • file-extension 是 Data ID 的文件后缀,如下图所示:

注入配置

java 复制代码
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.RestController;
@RestController
@RefreshScope  
public class TestController {

    @Value("${jwt.secret}")  // 用 @Value
    private String jwtSecret;

    @GetMapping("/test")
    public String test() {
        return jwtSecret;
    }
}
相关推荐
AI开源软件1 天前
SpringBoot信创项目怎么验收?从数据库迁移到交付证据
postgresql·springboot·达梦·opengauss·信创·企业管理系统
咖啡八杯2 天前
Redis 工具封装:RedisCache 对 Operations 体系的二次封装
java·数据库·redis·缓存·框架·springboot·若依
流烟默2 天前
从 Nacos 3.0.3 启动日志看架构演进:Server API 与 Console 分离实践
nacos·集群
我不会起名字3223 天前
服务注册了却调不通:注册中心与心跳的 3 个时间参数
微服务·nacos·注册中心·排查
西凉的悲伤5 天前
Spring Boot 条件装配注解详解
java·springboot·1024程序员节·条件装配
xieliyu.6 天前
【JavaEE进阶】Spring Boot 日志:从 System.out 到 @Slf4j,6 个级别 + 4 类配置一篇讲透
java·spring boot·spring·java-ee·springboot·logback·slf4j
AI开源软件6 天前
SpringBoot + Vue3 人力资源管理系统推荐:组织、档案与移动办公
vue3·springboot·ruoyi·oa系统·移动办公·人力资源管理系统·hrm
AI源码7 天前
社区医院儿童健康信息管理系统
springboot
AI源码7 天前
社区论坛系统
springboot
AI源码7 天前
图书馆借阅管理系统
vue3·springboot