Create and test REST services with Spring MVC


The first part of this example shows how to create and test REST services using Spring MVC. The controller contains CRUD operations on warehouses and its products. For this example, the repository is a stub that simulates access to the database.
The second part will access these services using the RestTemplate class and test them.
Source code available at the github spring rest repository.


 The context configuration is quite simple. It is split in two xml files. The parent context:


And the servlet context, which contains the stub repository:


The web.xml file just contains basic Spring configuration:


And finally the pom.xml with all the dependencies, which can be found in the repository pom.xml file.

Creating the RESTful services

 The controller has the following methods:
getWarehouse: Returns an existing warehouse.


This method uses several MVC annotations, explained below:
  • @RequestMapping: This annotation maps requests based on method onto specific handlers, in this case, the getWarehouse method, but only if the HTTP request method is GET. Specifying the method, you can have multiple methods mapped to the same uri. For example, the following request will be handled by this method and return the warehouse identified by 1:


  • @PathVariable: Extract values from request URL. In the method above, it extracts the warehouseId value from the request URL and maps it to the id parameter.
  • @ResponseBody: Bounds the return value of the method to the response body. For this task it uses HTTP message converters. The function of these converters is to convert between HTTP request/response and object.


addProduct: Adds a new product to an existing warehouse.


  • With the @ResponseStatus annotation, we are defining that there won’t be a view returned. Instead, we will return a response with an empty body.
  • Like @ResponseBody annotation, the @RequestBody annotation uses converters to transform request data into the object passed as a parameter.


 Other methods are defined in this controller but won’t put them all here. You can look up the source code linked above.

Setting the exception handler

 You can have multiple exception handlers, each one mapped to one or more exception types. Using the @ExceptionHandler annotation allows you to handle exceptions raised by methods annotated with @RequestMapping. Instead of forwarding to a view, it allows you to set a response status code. For example:


 Testing the services

 The test class is as follows:


Related posts

Share it:

Leave a Reply

Your email address will not be published. Required fields are marked *