连接nacos配置中心
第一步:导入依赖
<!--添加spring-cloud阿里巴巴管理依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--引入nacos配置管理依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-config</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
第二步:在nacos控制台编写配置文件
1.
2.
dataId格式为:服务名称-环境-配置文件格式
点击发布。
第三步:在服务中获取nacos配置中心的配置
1.在resource目录下新建一个bootstrap.yml配置文件
bootstrap.yml配置文件的加载顺序是在application.yml之前的
2.编写bootstrap.yml
#告诉spring去读nacos配置中心的配置文件
spring:
application:
name: userservice
profiles:
active: dev #配置环境
cloud:
config:
server-addr: http://nacos:8848 #nacos配置中心地址
file-extension: yaml #文件后缀
# namespace:
完成
获取配置中心配置文件内容
方式一:使用@Value()注解
同时在类上添加**@RefreshScope**注解可以动态获取配置中心的配置内容
例如:
方式二:使用@ConfigurationProperties(prefix=“***”)
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author Watching
* * @date 2022/9/7
* * Describe:用于接收bootstrap.yaml的配置
*
*/
@ConfigurationProperties(prefix="csdn")
@Component
@Data
public class PatternProperties {
private String name;
}
然后使用自动注入将该类注入,就可以调用其中的属性了。
别忘记添加 @Component @Data