问题
I tried this, it doesn't work, where am I going wrong?
application.properties (works fine)
document-contact={name:'joe',email:'joe.bloggs@gmail.com'}
application.yml (doesn't work; stacktrace below)
document-contact:
name: 'joe'
email: 'joe.bloggs@gmail.com'
Java:
@Value("#{${document-contact}}")
private Map<String, String> contact;
Stacktrace:
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]
回答1:
you need use follow:
tes:
maps:
key1: 15
key2: 2
and java code is:
@Data
@Component
@ConfigurationProperties(prefix = "tes")
public class MapTest {
private Map<String, String> maps;
}
回答2:
Your application.yml
is not equivalent to the application.properties
you're using.
Rather than reading separate properties, you only have a single property called document-contract
(= ${document-contract}
), which contains the following string:
"{name:'joe',email:'joe.bloggs@gmail.com'}"
To convert it to a Map
, you're using Spring Expression Language (SpEL). That's why you need both #{...}
and ${...}
.
Your application.yml
file on the other hand doesn't have a single property called document-contract
, and thus, it doesn't work. If you want to do the same kind of thing within your YAML, it should be:
document-contract: "{name: 'joe', email: 'joe.bloggs@gmail.com'}"
Alternatively, if you want to use multiple YAML properties like you did, you should be aware that @Value
doesn't support Map
structures. In stead, you should be using @ConfigurationProperties
:
@ConfigurationProperties(prefix = "app")
public class ApplicationProperties {
private Map<String, String> documentContact;
// Getters + Setters
}
With @ConfigurationProperties
, you would have to use a prefix though, so you should change your YAML structure to:
app:
document-contact:
name: joe
email: joe.bloggs@gmail.com
For the reference, this would be the equivalent properties file:
app.document-contract.name=joe
app.document-contact.email=joe.bloggs@gmail.com
来源:https://stackoverflow.com/questions/59210260/how-does-one-convert-application-properties-to-application-yml-for-maps