I’m trying to manually convert a set of configuration properties to an object using Spring.
My target class looks like this:
class ComplexConfigurationProperties {
private final Map<String, ComplexObject> objects;
public ComplexConfigurationProperties(Map<String, ComplexObject> objects) {
this.objects = objects;
}
}
And my Converter looks like this:
class CustomConverter implements Converter<Map<String, Object>, ComplexObject> {
@Override
public ComplexObject convert(Map<String, Object> source) {
ComplexObject result;
// do some stuff
return result;
}
}
My test for this looks like this:
@Test
void test() {
DefaultConversionService conversionService = new DefaultConversionService();
conversionService.addConverter(new CustomConverter());
ComplexConfigurationProperties props = new Binder(
Collections.singleton(
new MapConfigurationPropertySource(
Map.of(
"prefix.objects.a.property1", "property1",
"prefix.objects.a.property2", "property2"
)
)
), null,
conversionService
).bind("prefix", ComplexConfigurationProperties.class).get();
assertNotNull(props);
}
The binding result is always null
and my custom converter is never used. Now my question is: what did I do wrong? Do I need to use a different source type in the converter? Is what I’m trying to do not possible?
I couldn’t find anything regarding the conversion of complex types in the documentation.