如何将地图的 application.properties 转换为 application.yml

How does one convert application.properties to application.yml for maps

我试过了,不行,我哪里错了?

application.properties(工作正常)

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

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

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

Java:

    @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]

您需要使用以下内容:

tes:
  maps:
    key1: 15
    key2: 2

和java代码是:

@Data
@Component
@ConfigurationProperties(prefix = "tes")
public class MapTest {
    private Map<String, String> maps;
}

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

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

"{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