I have a custom StringToBooleanConverter
that should replace the default converter coming with Spring. So the source and target types are exactly the same. But instead of replacing the existing Spring converter, my converter is added. If I debug the application, I can see both converters in the same map entry of the Map
ConversionService#converters.
The ConversionService is configured like this:
@Bean
open fun conversionService(converters: Set<Converter<*, *>>) =
ConversionServiceFactoryBean().apply { setConverters(converters) }
@Bean
open fun stringToBooleanConverter() = MyStringToBooleanConverter()
// some more converters not relevant here ...
The problem is that sometimes the wrong converters gets used.
How can I remove/replace/hide/deactivate the converter delivered by Spring?
The trick is to define a custom ConversionServiceFactoryBean
, to override the method createConversionService
, and to remove the StringToBooleanConverter
registered by Spring itself:
class ConversionServiceFactoryWithoutStringToBooleanConverter : ConversionServiceFactoryBean() {
override fun createConversionService(): GenericConversionService {
val conversionService = super.createConversionService()
conversionService.removeConvertible(String::class.java, java.lang.Boolean::class.java)
return conversionService
}
}
However, in this case it is not necessary to remove the Spring converter because if there is more than one converter for a certain source and target type Spring tries them in order and converters registered by the user come first. The behavior that drove me to this investigation was in fact related to another bug not related to the ConversionService
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With