Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Spring Boot how do you register custom converters that are available when parsing application configuration?

Tags:

spring-boot

In a Spring Boot application how do you register custom converts to be used when processing application configuration?

I have made a custom convert (org.springframework.core.convert.converter.Converter) so it can be used by the ApplicationConversionService/Binder to parse @ConfiguraitonProperties defined in application.properties and application.yaml configuration files but do not know how to register it.

I have tried the solution here https://stackoverflow.com/a/41205653/45708 but it creates an instance of my converter after the application configuration parameters have been processed.

like image 983
ddcruver Avatar asked Nov 24 '25 04:11

ddcruver


1 Answers

I ran into this issue myself recently. From what I can tell, the key issue is that binding to configuration properties occurs very early in the Spring startup process, before the Application Context is fully initialized. Therefore the usual methods for registering a converter are not reliable. In fact the ConversionService used for configuration binding appear to be a one-off and not really connected to the ConversionService that is stored in the Application Context.

I was able to get something working but it feels like a hack, as it relies on internal implementation details that may work today but not tomorrow. In any case, this is the code I used:

((ApplicationConversionService) ApplicationConversionService.getSharedInstance()).addConverter(myCustomConverter);

The trick I found was to make sure this gets called as soon as possible at application startup so that it gets called before the configuration binding where it's needed. I put it in a @PostConstruct block inside my main @SpringBootApplication class as this seemed to get invoked early on, at least in my case.

like image 52
Jon Kranes Avatar answered Nov 28 '25 16:11

Jon Kranes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!