For those out there who due to constraints cannot use an application.properties files and need the properties provided as a YAML file:
As many answers say here, there is no default way for Spring to parse YAML property files. The default DefaultPropertySourceFactory implementation is only capable of parsing .properties and .xml files.
You need to create a custom factory class implementing PropertySourceFactory to let the framework know how to parse a specific configuration source.
Here is a basic example on how to do that:
public class YamlPropertySourceFactoryExample implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(final String name, final EncodedResource resource) throws IOException {
final Properties propertiesFromYaml = loadYamlIntoProperties(resource);
final String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(final EncodedResource resource) {
final YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
}
With it you are accomplishing two things:
- Loading the
YAML configurations into a Properties object.
- Returning a
PropertiesPropertySource object which wraps the loaded Properties.
After that you can reference it in a factories atribute of any @PropertyResource:
@PropertySource(value = "classpath:path/to/your/properties.yml", factory = YamlPropertySourceFactoryExample.class)
Edit: It cannot be used with @TestPropertySource, it does not support any factories at the moment.