Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate Converter in Spring ConversionService?

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?

like image 787
deamon Avatar asked Sep 06 '25 13:09

deamon


1 Answers

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.

like image 128
deamon Avatar answered Sep 09 '25 08:09

deamon