Spring MVC - HttpMessageConverter Registration

[Updated: Sep 3, 2017, Created: Sep 3, 2017]

This example demonstrates how to register a custom HttpMessageConverter.

A custom converter

This is just an empty extension of StringHttpMessageConverter for keeping things simple.

public class TheCustomConverter extends StringHttpMessageConverter {
}

Printing list of registered converters

@Component
public class RefreshListener {
  @Autowired
  private RequestMappingHandlerAdapter handlerAdapter;

  @EventListener
  public void handleContextRefresh(ContextRefreshedEvent event) {
      handlerAdapter.getMessageConverters().stream()
                    .map(c -> c.toString())
                    .forEach(System.out::println);
  }
}

Extending WebMvcConfigurerAdapter

Overriding extendMessageConverters()

@ComponentScan
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {

   @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new TheCustomConverter());
    }
 ......
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

org.springframework.http.converter.ByteArrayHttpMessageConverter
org.springframework.http.converter.StringHttpMessageConverter
org.springframework.http.converter.ResourceHttpMessageConverter
org.springframework.http.converter.xml.SourceHttpMessageConverter
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter
org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter
com.logicbig.example.TheCustomConverter

The duplicates and other logs have been removed from above output.

Overriding configureMessageConverters()

Following configuration will replace all default converters:

@ComponentScan
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {

   @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new TheCustomConverter());
    }
 ......
}

Output

com.logicbig.example.TheCustomConverter

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 4.3.10.RELEASE: Spring Web MVC.
  • spring-test 4.3.10.RELEASE: Spring TestContext Framework.
  • javax.servlet-api 3.0.1 Java Servlet API
  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Registering HttpMessageConverter Select All Download
  • message-converters-registration
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also