springboot无法将占位符解析为hashmap

6mzjoqzu  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(329)

我有一个springboot配置yaml文件,其中包含以下键:

grpc:
  channels:
    service1:
      hostname: localhost
      port: 50015
    service2:
      hostname: localhost
      port: 50016

我想将这些键加载到hashmap:

@Configuration
public class ChannelProperties {

    @Value("${grpc.channels}")
    private Map<String, ChannelConfiguration> channels;

    public ChannelProperties() {
    }

    public static class ChannelConfiguration {

        private String hostname;
        private String port;

    }
}

但是当我运行代码时,我得到以下错误:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'grpc.channels' in value "${grpc.channels}"

我仍然无法在我的配置中找到我想要的任何建议

46qrfjad

46qrfjad1#

您可能应该使用@configurationproperties而不是 @Value 注解。此外,还需要为属性添加getter和setter。
像这样的方法应该会奏效:

@Configuration
@ConfigurationProperties(prefix = "grpc")
public class ChannelConfig {

    private Map<String, ChannelConfiguration> channels;

    public Map<String, ChannelConfiguration> getChannels() {
        return this.channels;
    }

    public void setChannels(Map<String, ChannelConfiguration> channels) {
        this.channels = channels;
    }

    public static class ChannelConfiguration {
        private String hostname;
        private String port;

        public String getHostname() {
            return hostname;
        }

        public void setHostname(String hostname) {
            this.hostname = hostname;
        }

        public String getPort() {
            return port;
        }

        public void setPort(String port) {
            this.port = port;
        }
    }
}
sczxawaw

sczxawaw2#

你为什么不使用 @ConfigurationProperties ,它很好用

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "grpc")
public class ChannelProperties {

    private Map<String, ChannelConfiguration> channels;

    @Getter
    @Setter
    public static class ChannelConfiguration {
        private String hostname;
        private String port;
    }
}
ippsafx7

ippsafx73#

您是否在主类上添加了以下配置。

@PropertySource(value = "classpath:foo.yml", factory = 
YamlPropertySourceFactory.class)

相关问题