配置管理
1. 添加依赖
2. 配置
在 application.yml 中配置 Nacos Server 的地址和应用名:
spring.application.name 是构成 Nacos 配置管理 dataId 字段的一部分。
在 Nacos Spring Cloud 中,dataId 的完整格式如下:
prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。
spring.profiles.active 即为当前环境对应的 profile。当 spring.profiles.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension}。
file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型。
注意
与 Spring Cloud Config 一样,spring-cloud-starter-alibaba-nacos-config 在加载配置的时候,不仅仅加载了以 dataId 为 ${spring.application.name}.${file-extension:properties} 为前缀的基础配置,还加载了 dataId 为 ${spring.application.name}-${profile}.${file-extension:properties} 的基础配置。
3. 通过注解 @RefreshScope 实现配置自动更新
注意
如果想要完整地利用 nacos 相关的配置,必须将所有配置放在 bootstrap.yml 或 bootstrap.properties 文件中,并且必须引入 bootstrap 相关依赖(或者通过将系统环境变量 spring.cloud.bootstrap.enabled 设为 true):
只有这样,才能够省略 spring.config.import 配置,进而充分利用 nacos 特定的配置。
spring cloud config 文档中的原文如下:Unless you are using config first bootstrap, you will need to have a spring.config.import property in your configuration properties with an optional: prefix. For example:
Config First BootstrapTo use the legacy bootstrap way of connecting to Config Server, bootstrap must be enabled via a property or the spring-cloud-starter-bootstrap starter. The property is spring.cloud.bootstrap.enabled=true. It must be set as a System Property or environment variable.
Last updated