Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring ConversionService adding Converters

I searched for the below problem, but couldn't find an answer.

I want to use spring's conversion service by writing my custom converter that implements org.springframework.core.convert.converter.Converter.

Then i add my custom converter as below:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean id="StringToLoggerConverter" class="com.citi.spring.converter.LoggerConverter" />
       </list>
   </property>
</bean>

When doing the above my application initialization fails, because i am overriding bean conversionService and registering only my custom converter.

How can i not override the conversionService and only add my custom converter to the list of converters, at the same time keeping the existing ones?

Thanks in advance.

like image 510
nikkatsa Avatar asked Oct 08 '12 09:10

nikkatsa


People also ask

Does spring convert all values to target data types?

Spring provides out-of-the-box various converters for built-in types; this means converting to/from basic types like String, Integer, Boolean and a number of other types.

What is converter in spring boot?

A converter converts a source object of type S to a target of type T . Implementations of this interface are thread-safe and can be shared.

How do you implement a converter in Java?

First create a class which will implements the Converter interface and the java. lang. Class object of an application class (such as the class which need to be converted and incoming string value to be converted) should be accepted by convert() method.


1 Answers

For anyone who stumbles on this now via a google search or similar 2+ years after the question was originally posted, adding converters has been made much easier through Java Config: WebMvcConfigurerAdapter provides the addFormatters(FormatterRegistry) method that can be used to specify additional custom converters.

like image 195
Christopher Avatar answered Sep 18 '22 12:09

Christopher