spring cloud/boot的.yml文件或.properties文件读取不到的原因

1:

没引入yaml包或读取.properties文件的包。

2:

使用eclipse导入maven项目后,没有吧resouce目录设置为source folder。

大鹏激光

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud中,可以使用@ConfigurationProperties注解读取YAML文件中的列表类型的配置。与在Spring Boot读取类似,但需要添加`@RefreshScope`注解,以便在配置更改时自动刷新。 假设你有一个名为 `config.yml` 的YAML文件,其中包含名为 `my-list` 的列表类型的配置,可以按照以下步骤读取它: 1. 引入Spring Cloud和YAML依赖包。在Maven项目中,可以在pom.xml中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-yaml</artifactId> </dependency> ``` 2. 创建一个@ConfigurationProperties类,用于映射YAML中的配置。例如: ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; import java.util.List; @Component @ConfigurationProperties(prefix = "my") @RefreshScope public class MyConfig { private List<String> list; public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } } ``` 在这个类中,我们使用`@ConfigurationProperties`注解来指示要映射的配置前缀。在这个例子中,我们使用了`my`前缀。然后,我们定义了一个`list`属性,它将映射到名为`my-list`的配置。我们还添加了`@RefreshScope`注解,以便在配置更改时自动刷新。 3. 在YAML文件中定义列表配置。例如: ```yaml my: list: - item1 - item2 - item3 ``` 在这个例子中,我们使用了`my`前缀来定义配置,然后在该前缀下定义了一个名为`list`的配置。注意,这个配置的值是一个包含三个字符串元素的列表。 4. 在应用程序中使用`MyConfig`类。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApp { @Autowired private MyConfig myConfig; public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } // 在任何地方使用 myConfig.getList() 获取列表配置 } ``` 在这个例子中,我们使用`@Autowired`注解将`MyConfig`类注入到`MyApp`类中。然后,我们可以在任何地方使用`myConfig.getList()`方法来获取YAML文件中的列表配置。在这个例子中,这个方法将返回一个包含三个字符串元素的列表,即`["item1", "item2", "item3"]`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值