要在Spring Boot中读取Nacos配置,你需要按照以下步骤进行操作:

  1. 添加Nacos依赖:在pom.xml文件中添加以下依赖:
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
  1. 配置Nacos连接信息:在application.propertiesapplication.yml文件中添加Nacos的连接信息:
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=
  1. 创建配置类:创建一个用于读取配置的类,例如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;
    }
}
  1. 使用配置:在需要使用配置的地方注入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 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录