I want to create a ConversionService with custom converters.
Inspired by another question I've tried to create a ConversionService by creating a ConversionServiceFactoryBean and setting the converters on it:
@Bean
public ConversionService conversionService(
Set<Converter<?, ?>> converters,
ConversionServiceFactoryBean factory) {
factory.setConverters(converters);
return factory.getObject();
}
@Bean
public ConversionServiceFactoryBean conversionServiceFactoryBean() {
return new ConversionServiceFactoryBean();
}
The Spring documentation suggests more or less the same in XML:
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="example.MyCustomConverter"/>
</set>
</property>
</bean>
But configuring a ConversionService did not work in my case. Did not work means following error was thrown when i tried to use this autowired conversionService in my class;
ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.time.Duration]
I had to use a GenericConversionService and add my converters to it:
@Bean
public ConversionService conversionService(Set<Converter<?, ?>> converters) {
final GenericConversionService conversionService = new GenericConversionService();
converters.forEach(conversionService::addConverter);
return conversionService;
}
Now it works, but I want to understand why it doesn't work with ConversionServiceFactoryBean.
Why doesn't it work with ConversionServiceFactoryBean and Java config? Why does it work with GenericConversionService?