<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.3.RELEASE</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
因为nacos的配置要优先加载,所以放到bootstrap.yml中,而不是application.yml中
server:
port: 9000
# 在Nacos Spring Cloud 中,dataId 的完整格式如下:${prefix}-${spring.profiles.active}.${file-extension}
spring:
application:
name: config1 # 配置名
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848 # 配置中心地址
file-extension: yaml # 后缀名
namespace: 32210854-b7f7-40b9-8321-96bb7fb38f07 # 命名空间ID
group: DEFAULT_GROUP # 指定要获取配置的组
@RefreshScope
@RestController
public class NacosServerController {
@Resource
private ConfigurableApplicationContext configurableApplicationContext;
@Value("${student.name:null}")
private String name;
/**
* 如果只是通过@Value获得的配置信息,不会随着Nacos的修改操作而获得最新配置信息。那么,实时获取最新配置信息有两种方式:
* 方式1:添加@RefreshScope注解。
* 方式2:通过getProperty的方式,获得最新的配置信息。
*
* @return
*/
@GetMapping("/name")
public String getName() {
String name1 = configurableApplicationContext.getEnvironment().getProperty("student.name");
return String.format("name=%s, name1=%s", name, name1);
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有