Understanding REST in Spring

Understanding REST in Spring




The Spring framework supports two ways of creating RESTful services:

  • using MVC with ModelAndView

  • using HTTP message converters

    The ModelAndView approach is older and much better documented, but also more verbose and configuration heavy. It tries to shoehorn the REST paradigm into the old model, which is not without problems. The Spring team understood this and provided first-class REST support starting with Spring 3.0.

    The new approach, based on HttpMessageConverter and annotations, is much more lightweight and easy to implement. Configuration is minimal, and it provides sensible defaults for what one would expect from a RESTful service.


                @Configuration
                @EnableWebMvc
                public class WebConfig{
                //
                


The new @EnableWebMvc annotation does some useful things – specifically, in the case of REST, it detects the existence of Jackson and JAXB 2 on the classpath and automatically creates and registers default JSON and XML converters. The functionality of the annotation is equivalent to the XML version: 


<mvc:annotation-driven/> 


This is a shortcut, and though it may be useful in many situations, it’s not perfect. When more complex configuration is needed, remove the annotation and extend WebMvcConfigurationSupport directly.



Using Spring Boot


If we’re using the @SpringBootApplication annotation and the spring- webmvc library is on the classpath, then the @EnableWebMvc annotation is added automatically with a default autoconfiguration.

We can still add MVC functionality to this configuration by implementing the WebMvcConfigurer interface on a @Configuration annotated class. We can also use a WebMvcRegistrationsAdapter instance to provide our own RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver implementations.


 


Post a Comment (0)
Previous Post Next Post