一尘不染

将Yaml中的列表映射到Spring Boot中的对象列表

spring

在我的Spring Boot应用程序中,我具有以下内容的application.yaml配置文件。我想将其作为带有通道配置列表的Configuration对象注入:

available-payment-channels-list:
  xyz: "123"
  channelConfigurations:
    -
      name: "Company X"
      companyBankAccount: "1000200030004000"
    -
      name: "Company Y"
      companyBankAccount: "1000200030004000"

我想用PaymentConfiguration对象列表填充@Configuration对象:

    @ConfigurationProperties(prefix = "available-payment-channels-list")
    @Configuration
    @RefreshScope
    public class AvailableChannelsConfiguration {

        private String xyz;

        private List<ChannelConfiguration> channelConfigurations;

        public AvailableChannelsConfiguration(String xyz, List<ChannelConfiguration> channelConfigurations) {
            this.xyz = xyz;
            this.channelConfigurations = channelConfigurations;
        }

        public AvailableChannelsConfiguration() {

        }

        // getters, setters


        @ConfigurationProperties(prefix = "available-payment-channels-list.channelConfigurations")
        @Configuration
        public static class ChannelConfiguration {
            private String name;
            private String companyBankAccount;

            public ChannelConfiguration(String name, String companyBankAccount) {
                this.name = name;
                this.companyBankAccount = companyBankAccount;
            }

            public ChannelConfiguration() {
            }

            // getters, setters
        }

    }

我使用@Autowired构造函数将其作为普通bean注入。xyz的值正确填充,但是当Spring尝试将yaml解析为对象列表时,

   nested exception is java.lang.IllegalStateException: 
    Cannot convert value of type [java.lang.String] to required type    
    [io.example.AvailableChannelsConfiguration$ChannelConfiguration] 
    for property 'channelConfigurations[0]': no matching editors or 
    conversion strategy found]

任何线索这是怎么了?


阅读 1200

收藏
2020-04-14

共1个答案

一尘不染

原因可能在其他地方。仅使用Spring Boot 1.2.2,无需配置即可使用,它可以正常工作。看看这个仓库-你能打破它吗?

https://github.com/konrad-garus/so-yaml

你确定YAML文件看起来与你粘贴的方式完全一样吗?是否没有多余的空格,字符,特殊字符,缩进或类似的东西?是否有可能在搜索路径中的其他位置使用了另一个文件,而不是你期望的文件?

2020-04-14