【问题标题】:Why I cannot load property POJO using YAML in Spring Boot?为什么我不能在 Spring Boot 中使用 YAML 加载属性 POJO?
【发布时间】:2020-02-07 11:32:35
【问题描述】:

我已经阅读了许多帖子、问题、示例以及它应该起作用的所有内容,但无论出于何种原因它都不起作用......

谁能告诉我为什么这不起作用?

@Configuration()
@PropertySource("users.yml")
@Data
@ConfigurationProperties
@EnableConfigurationProperties
public class UserConfig {


    public String test;
    public List<String> states;
    public List<User> users;

    @PostConstruct
    public void print() {
        System.out.println(this);
        System.exit(0);
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private String username;
    private String pw;
    private List<String> roles;
}

输出是 UserConfig(test='yeah im tested', states=[], users=[])

对于给定的 YAML

test: 'yeah im tested'
states:
  - 'Up'
  - 'Down'
users:
  -
    username: 'Gienek'
    pw: 'niegienek'
    roles:
      - 'rola1'
      - 'rola2'

注意: 使用states: 'Up','Down' 填充状态列表。

另请注意,它可以部分工作。

【问题讨论】:

  • 不应该是@Value("${test}") private String test;
  • 正如我已经指出的 - 这个特殊的 test 字段 - 有效。 UserConfig(test='yeah im tested', states=[], users=[])
  • 保持你的值在 yaml 中以逗号分隔,比如状态:向上、向下....... @Value("${states}") String[] states
  • 如注释中所述 - 是的,写为 states : val val 的状态有效 - 没有 @Value
  • @SwaritAgarwal 整个User 对象怎么样?

标签: spring spring-boot yaml


【解决方案1】:

更准确地说,Spring Boot 不想支持 @PropertySource 以正确支持 yml 文件是一个“已知”事实,因为这不是在 Spring Boot 项目中使用 @Propertysource 的“标准”。 ..这是讨论的链接: https://github.com/spring-projects/spring-framework/issues/18486.

您也可以尝试使用EnvironmentPostProcessor :https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-environment-or-application-context

我建议任何人尝试一下 application.yml,除非您有利用限制。

一种解决方案是将您的users.yml 的内容复制到application.yml,这绝对符合您的需求。

src/main/resources/application.yml

test: 'yeah im tested'
states:
  - 'Up'
  - 'Down'
users:
  -
    username: 'Gienek'
    pw: 'niegienek'
    roles:
      - 'rola1'
      - 'rola2'

UserConfig.java

@Data
@Configuration
@ConfigurationProperties
@EnableConfigurationProperties
public class UserConfig {
    ...
}

【讨论】:

  • 是的,我们刚刚发现对 application.yml(应用程序*命名文件)的 yaml 解析按预期工作。
【解决方案2】:

似乎这只是 Spring hadles yaml 文件的限制,如果没有自定义实现,我很不走运。

https://github.com/spring-projects/spring-framework/issues/16381

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2019-04-13
    • 2013-01-29
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多