在 Spring Boot 应用程序中,可以使用 Spring Cloud Nacos 来实现从 Nacos 服务注册中心和配置中心读取配置信息。以下是如何在 Spring Boot 中读取 Nacos 上的配置文件的步骤:

1. 引入依赖

首先,在 Spring Boot 项目的 pom.xml 文件中添加 Spring Cloud Nacos 的依赖:

com.alibaba.cloud

spring-cloud-starter-alibaba-nacos-config

2. 配置 Nacos 连接信息

将 Nacos 服务注册中心和配置中心的地址、命名空间等相关信息添加到 application.properties 或 application.yml 配置文件中:

spring.cloud.nacos.config.server-addr=localhost:8848

spring.cloud.nacos.config.namespace=

3. 编写配置文件

在 Nacos 配置中心创建配置文件(例如 ​application.properties​),并添加一些键值对,如:

user.name=John Doe

user.age=30

4. 读取配置信息

在 Spring Boot 的任何配置类或组件类中,可以使用 ​@Value​ 注解或 ​@ConfigurationProperties​ 注解来读取配置项:

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class ConfigController {

@Value("${user.name}")

private String userName;

@Value("${user.age}")

private int userAge;

@GetMapping("/userInfo")

public String getUserInfo() {

return "User Name: " + userName + ", Age: " + userAge;

}

}

5. 刷新配置

如果想要在配置发生变化时动态刷新配置,可以在需要动态更新的 Bean 类上添加 ​@RefreshScope​ 注解:

import org.springframework.cloud.context.config.annotation.RefreshScope;

import org.springframework.stereotype.Component;

@Component

@RefreshScope

public class MyConfigBean {

@Value("${my.config}")

private String myConfig;

// Getter and Setter

}

当配置发生变化后,可以通过访问 Actuator 端点 ​/actuator/refresh​ 来触发配置的刷新,以便及时获取最新的配置信息。

如果nacos上面有很多个配置文件,springboot中如何获取想要的配置文件?

1.在 Nacos 配置中心创建多个配置文件,例如 ​user.properties​ 和 ​database.properties​,并添加相应的键值对。

2.在 Spring Boot 项目的 ​application.properties​ 或 ​application.yml​ 中,指定需要获取的配置文件的 Data ID:

spring.cloud.nacos.config.shared-configs[0].data-id=user.properties

spring.cloud.nacos.config.shared-configs[1].data-id=database.properties

3.可以通过 ​@ConfigurationProperties​ 注解来读取指定的配置文件内容,例如:

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.stereotype.Component;

@Component

@ConfigurationProperties("user")

public class UserConfig {

private String userName;

private int age;

// Getters and Setters

}

@Component

@ConfigurationProperties("database")

public class DatabaseConfig {

private String url;

private String username;

// Getters and Setters

}

在上面的示例中,​@ConfigurationProperties​ 注解中的 value 值指定了要绑定的配置文件的前缀,可以直接读取到该配置文件中的相关属性值。

注意: 在使用 ​@ConfigurationProperties​ 注解时,需要确保属性名与配置文件中的键名一致,Spring Boot 会自动根据前缀匹配来绑定配置项。

4.多文件配置和自动刷新也可参考如下配置:

好文阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: