I'm trying to read a YAML configuration file through the spring boot @PropertySource mechanism, using a factory that utilizes the provided YamlMapFactoryBean parser.
The factory's implementation is as follows:
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
YamlMapFactoryBean factory = new YamlMapFactoryBean();
factory.setResources(encodedResource.getResource());
Map<String, Object> map = factory.getObject();
return new MapPropertySource(encodedResource.getResource().getDescription(), map);
}
}
The YAML configuration file (foo.yml) is:
yaml:
name: foo
aliases:
- abc
- xyz
The corresponding entity is:
@Configuration
@ConfigurationProperties(prefix = "yaml")
@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class)
public class YamlFooProperties {
private String name;
private List<String> aliases;
// Getters and Setters...
}
And finally, my test class is:
@RunWith(SpringRunner.class)
@SpringBootTest
public class YamlFooPropertiesTest {
@Autowired
private YamlFooProperties yamlFooProperties;
@Test
public void whenFactoryProvidedThenYamlPropertiesInjected() {
assertThat(yamlFooProperties.getName()).isEqualTo("foo");
assertThat(yamlFooProperties.getAliases()).containsExactly("abc", "xyz");
}
}
When debugging the factory, I see that the YAML file is parsed correctly and added to spring boot's propertySourceNames structure. However, when accessing it from the test in an Autowired fashion, all fields are null and the test therefore fails.