springboot 读取nacos配置
要在Spring Boot中读取Nacos配置,你需要按照以下步骤进行操作:
- 添加Nacos依赖:在
pom.xml文件中添加以下依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
- 配置Nacos连接信息:在
application.properties或application.yml文件中添加Nacos的连接信息:
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=
- 创建配置类:创建一个用于读取配置的类,例如
NacosConfig.java:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@Component
@RefreshScope
public class NacosConfig {
@Value("${your.config.key}")
private String yourConfigValue;
public String getYourConfigValue() {
return yourConfigValue;
}
}
- 使用配置:在需要使用配置的地方注入
NacosConfig类,并使用其中的配置值:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YourController {
@Autowired
private NacosConfig nacosConfig;
@GetMapping("/your-config")
public String getYourConfig() {
return nacosConfig.getYourConfigValue();
}
}
现在你可以通过访问/your-config接口来获取Nacos中的配置值。
请注意,使用@RefreshScope注解可以实现动态更新配置,如果你修改了Nacos中的配置,可以通过调用/actuator/refresh接口来刷新配置
原文地址: http://www.cveoy.top/t/topic/h9ZN 著作权归作者所有。请勿转载和采集!