我试过了,没用,我哪里出错了?
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]
最佳答案
您的 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
关于java - 如何将 application.properties 转换为 map 的 application.yml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59210260/