以下是测试项目信息
1.新增依赖(注意springboot+springCloud+nacos版本需要对应)
<properties><logback.version>1.1.7</logback.version>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR10</spring-cloud.version>
</properties>
<!-- nacos--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <version>2.2.6.RELEASE</version> <exclusions> <exclusion> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2.2.6.RELEASE</version> </dependency> <!-- <!– 读取bootstrap文件 –>--> <!-- <dependency>--> <!-- <groupId>org.springframework.cloud</groupId>--> <!-- <artifactId>spring-cloud-starter-bootstrap</artifactId>--> <!-- </dependency>--> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
高版本需要引入 spring-cloud-starter-bootstrap 依赖 我这个版本不需要
2.创建配置文件
spring: profiles: active: dev cloud: nacos: discovery: server-addr: 10.100.10.104:8848 namespace: test group: gch_group config: group: gch_group server-addr: 10.100.10.104:8848 namespace: test prefix: application file-extension: yml name: application
在nacos服务器中创建 命名空间、组、配置文件
3.使用配置&修改配置文件动态生效
测试了两种获取配置数据的方式
1)使用@RefreshScope + @Value 的方式动态获取配置数据
2)使用 @ConfigurationProperties 全局配置(这里查资料说需要使用 @NacosConfigurationProperties(dataId = "my-config", autoRefreshed = true) 但是测试后发现@ConfigurationProperties也可应并且可以动态更新配置信息)
package com.mybatis.plus.config; import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Configuration; /** * @Description: 配置文件全部变量初始化 * @Author: gch * @Date: 2023/11/9 14:11 */ public class ApplicationProperties { @Data @ConfigurationProperties(prefix = "test") @Configuration public static class Test { public static String test1; public static String test2; public void setTest1(String test1) { Test.test1 = test1; } public void setTest2(String test2) { Test.test2 = test2; } } }
标签:配置文件,spring,nacos,实时,import,public,cloud From: https://www.cnblogs.com/guanxiaohe/p/18000654