java - 如何将 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]
解决方案
你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
推荐阅读
- for-loop - 通过 for 循环在特定列上合并.xts
- ssl - nginx反向代理上的无限重定向循环
- javascript - 如何将浏览器的 confirm() 与 Angular 模板语句一起使用?
- php - PHP通过AJAX上传图片数据
- sed - 将 markdown 代码块标记转换为criticMarkup 语法
- node.js - 在本地运行firebase功能时如何使https工作并添加自签名SSL证书?
- angular - Docker Compose 与 Angular、Express.js 和 Nginx - 502 响应
- node.js - 如何在 node.js 中添加标题
- python - 在pygame中让玩家在每个间隔移动的最佳方法是什么?
- c++ - 是否存在具有外部元素分配的序列容器(在 STL 中)?