@PropertySource读取nacos的yaml的配置
时间: 2024-02-25 08:52:51 浏览: 115
可以使用Spring Cloud Alibaba提供的Nacos Config来实现@PropertySource读取Nacos的YAML配置。下面是一个简单的示例:
1. 引入依赖
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
```
2. 在启动类上添加注解 @EnableNacosConfig
```java
@SpringBootApplication
@EnableNacosConfig
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
3. 在 application.yml 中添加 Nacos 配置
```yaml
spring:
application:
name: example
cloud:
nacos:
config:
server-addr: localhost:8848
file-extension: yaml
group: DEFAULT_GROUP
refreshable-dataids: example.yml
```
4. 在代码中使用@Value注解读取配置
```java
@RestController
public class ExampleController {
@Value("${example.name}")
private String name;
@GetMapping("/hello")
public String hello() {
return "Hello " + name;
}
}
```
在上面的示例中,@Value("${example.name}")会自动读取Nacos配置中的example.yml文件中的example.name属性。注意:需要在Nacos控制台中创建一个名为example.yml的配置文件,并设置example.name属性的值。
阅读全文
相关推荐










