RestTemplate and <mvc:message-converters> in Spring Framework 4.3

The Spring Framework’s documentation says that RestTemplate instance created by the default constructor gets the default set of HttpMessageConverters.

But what is the default set of HttpMessageConverters? Well, this is defined in the Spring Framework Reference. Unfortunately I’ve missed it somehow and I was believing that the default set of HttpMessageConverters is affected by <mvc:message-converters> Spring XML configuration element, like in the sample below:

    <bean id="customGsonHttpMsgConverter" class="org.springframework.http.converter.json.GsonHttpMessageConverter">
        <property name="gson">
            <bean class="CustomGsonFactoryBean"/>
        </property>
    </bean>
    
    <mvc:annotation-driven>
        <mvc:message-converters>
            <ref bean="customGsonHttpMsgConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

Actually it’s not true. In the above example the RestTemplate bean will not be using this “customGsonHttpMsgConverter” bean. The default set of HttpMessageConverters for RestTemplate is… hardcoded in RestTemplate class. However one can customize it easily. This is the correct way of configuring HttpMessageConverters to be used by RestTemplate:

    <bean id="customGsonHttpMsgConverter" class="org.springframework.http.converter.json.GsonHttpMessageConverter">
        <property name="gson">
            <bean class="CustomGsonFactoryBean"/>
        </property>
    </bean>
    
    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <constructor-arg>
            <list>
                <ref bean="customGsonHttpMsgConverter"/>
            </list>
        </constructor-arg>
    </bean>

Lesson learned! RestTemplate has nothing to do with <mvc:message-converters> configuration.

About krzysztoftomaszewski

I've got M.Sc. in software engineering. I graduated in 2005 at Institute of Computer Science, Warsaw University of Technology, Faculty of Electronics and Information Technology. I'm working on computer software design and engineering continuously since 2004.
This entry was posted in Java, Spring and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s