springboot项目将@ConfigurationProperties(prefix = "spring.datasource")改为从nacos取值,保留@ConfigurationProperties
时间: 2023-07-25 10:44:39 浏览: 151
可以使用 Nacos 提供的 `@NacosConfigurationProperties` 注解来实现从 Nacos 中取值,同时保留 `@ConfigurationProperties` 注解。
具体步骤如下:
1. 在 pom.xml 中添加 Nacos 的依赖:
```xml
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.4.0</version>
</dependency>
```
2. 在启动类中添加 `@NacosPropertySource` 注解,指定 Nacos 的配置文件:
```java
@SpringBootApplication
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
3. 在需要读取配置的类中使用 `@ConfigurationProperties` 和 `@NacosConfigurationProperties` 注解,并指定前缀和数据 ID:
```java
@Component
@ConfigurationProperties(prefix = "spring.datasource")
@NacosConfigurationProperties(dataId = "example", prefix = "spring.datasource", autoRefreshed = true)
public class DataSourceProperties {
// ...
}
```
这样,当 Nacos 中的配置文件发生变化时,`DataSourceProperties` 中的属性值会自动刷新。
阅读全文
相关推荐


















