Reputation: 85
When using @ConfigurationProperties with @PropertySource(value = "myconfig.yml") Springboot doesn't serialize my properties into an object
If I put this same config in application.yml and remove the @PropertySource(value = "myconfig.yml"), then it works
---
testPrefix.simpleProperty: my.property.haha
testPrefix.complexProperties:
-
firstName: 'Clark'
lastName: 'Ken'
-
firstName: 'Roger'
lastName: 'Federer'
@Configuration
@ConfigurationProperties(prefix = "testPrefix")
@PropertySource(value = "testConfigFile.yml")
public class MyTestProperties {
private String simpleProperty;
private List<Person> complexProperties;
getters
setters
@SpringBootApplication
public class App implements CommandLineRunner {
MyTestProperties myProperties;
@Autowired
public App(MyTestProperties properties) {
this.properties = properties;
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication((App.class));
app.run(args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(myProperties.getSimpleProperty());
myProperties.getComplexProperties.stream.forEach(System.out::println));
}
}
Output:
my.property.haha
Upvotes: 2
Views: 1770
Reputation: 9396
You need to use jackson yaml dependency.
//pom.xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
Then create a factory class for loading yaml files as property sources.
//YamlPropertySourceFactory.java
import java.io.IOException;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s,
EncodedResource encodedResource) throws IOException {
YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
bean.setResources(encodedResource.getResource());
return new PropertiesPropertySource(
s != null ? s : encodedResource.getResource().getFilename(),
bean.getObject());
}
}
Then use PropertySource
annotation like this.
@PropertySource(factory = YamlPropertySourceFactory.class, value = "testConfigFile.yml")
public class MyTestProperties {
private String simpleProperty;
private List<Person> complexProperties;
Upvotes: 1
Reputation: 3500
To my knowledge, YAML properties cannot be loaded using a @PropertySource
. I'll look it up as I'm not sure whether the issue has been resolved in the meantime.
[edit] Apparently, it hasn't been fixed:
YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.
Upvotes: 2