I want to create a Spring ConversionService with custom Converters, but the return value of ConversionServiceFactoryBean#getObject is
Thanks to the comment of Sotirios Delimanolis I came to the following solution:
@Bean
public ConversionServiceFactoryBean conversionService(Set<Converter<?, ?>> converters) {
final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
factory.setConverters(converters);
return factory;
}
This is essentially a shorthand for the following configuration:
@Bean
public ConversionService conversionService(Set<Converter<?, ?>> converters) {
final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
factory.setConverters(converters);
factory.afterPropertiesSet(); // necessary
return factory.getObject();
}
The factory remains in an unfinished state until afterPropertiesSet (explanation) is called. However, one doesn't need to call it, if the ConversionServiceFactoryBean itself is returned instead of the ConversionService. Since the factory is a InitializingBean and a FactoryBean Spring will call afterPropertiesSet and getObject internally, if a ConversionService instance is needed.