首页 > 解决方案 > 如何将 application.properties 转换为 application.yml 以获取地图

问题描述

我试过了,它不起作用,我哪里出错了?

application.properties(工作正常)

document-contact={name:'joe',email:'joe.bloggs@gmail.com'}

application.yml(不起作用;下面的堆栈跟踪)

document-contact:
  name: 'joe'
  email: 'joe.bloggs@gmail.com'

爪哇:

    @Value("#{${document-contact}}")
    private Map<String, String> contact;

堆栈跟踪:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'consolidatedSwaggerDocumentationController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'document-contact' in value "#{${document-contact}}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:403) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]

标签: javaspring-bootmapsyaml

解决方案


application.yml的不等同于application.properties你正在使用的。

而不是读取单独的属性,您只有一个名为document-contract(= ${document-contract}) 的属性,其中包含以下字符串

"{name:'joe',email:'joe.bloggs@gmail.com'}"

要将其转换为Map,您正在使用Spring Expression Language (SpEL)。这就是为什么你同时需要#{...}${...}

另一方面,您的application.yml文件没有一个名为 的属性document-contract,因此它不起作用。如果你想在 YAML 中做同样的事情,它应该是:

document-contract: "{name: 'joe', email: 'joe.bloggs@gmail.com'}"

或者,如果您想像以前那样使用多个 YAML 属性,您应该知道它@Value不支持Map结构。相反,您应该使用@ConfigurationProperties

@ConfigurationProperties(prefix = "app")
public class ApplicationProperties {
    private Map<String, String> documentContact;

    // Getters + Setters
}

使用@ConfigurationProperties,您必须使用前缀,因此您应该将 YAML 结构更改为:

app:
  document-contact:
    name: joe
    email: joe.bloggs@gmail.com

作为参考,这将是等效的属性文件:

app.document-contract.name=joe
app.document-contact.email=joe.bloggs@gmail.com

推荐阅读