Category: Spring Boot

Spring Boot and MySQL: Simple CRUD Application (REST Api) with Spring Data JPA


Today i am going to explain how to develop simple CRUD (Create,Retrieve,Update and Delete data) application with Spring Boot and  Spring Data JPA.  the application will be simple web application and which will expose few REST endpoints for CRUD related operations.


What is Spring Data JPA?

Spring Data JPA is a sub project that comes under the Spring Data project and it is under the umbrella/shelter of Spring family.  This will implements the JPA (Java Persistence Api) specification and have classes and methods for accessing and managing the data tier of the application. It tries to simplify the complexity associated with the data access layer of the application.  As i have already mentioned, Spring Data JPA  has following objectives.

  • provides a better implementation for the JPA Specification.
  • avoid the complexity associated with the Data Access layer of the application (by providing a framework that is easy to implement and  having robust features)


So it is enough with theories. lets explore and play with the framework.  As usual.  i have used the  for generating the project.

Screen Shot 2017-12-30 at 7.30.47 PM.png

As you can see in the generation wizard, we are using two dependencies other than web dependency. That is JPA and MySQL.

JPA – Represents the maven dependency for Spring Data JPA.

MySQL – Represents the maven dependency for mysql-jdbc-connector 


So Lets Open the pom.xml file and look at the dependency section for identifying those dependencies.


What we are going to build?

We will do CRUD related operations with a user object and ultimately we will build a REST api application with four endpoints  for CRUD related operations.

  • HTTP POST    /api/users   For creating the user
  • HTTP PUT     /api/users   For updating the user
  • HTTP DELETE    /api/users/:user_id   For deleting the user
  • HTTP GET    /api/users   For retrieving all the users


Where do we start?

Spring Data JPA is all about creating Entities and Repositories.

Entity lives in between java object (java class) and relational table. It helps to map the java object to relational table and relational table back to java object.

Repository helps to perform CRUD related operations with Entity.

The actual definition of Entity and Repository might be different from the explanation that i have given. Basically i just wanted to simply point out the exact purpose/role of Entity and Repository.

So Lets create our Entity and Repository.


Creating the Entity

The Entity class will be the following class.


Things to Remember

The most important thing that you should note here is that we have used java persistence api (JPA annotations) based annotation here. No any framework specific annotation used. This is to compatible with other JPA implemented/supported ORM frameworks. For instance, if you have developed the data layer to compliant/adherent with JPA specification, then it will be possible to switch with different JPA implementations with minimal effort.


Creating the Repository

Creating a JPA based repository is very simple. You have to create an interface that extends the JpaRepository interface by providing the generic parameter, the Entity class and ID type.  Here is the sample code for implementing UserRepository.

User – is the entity class

Long – is the data type of the ID (Primary Key).

All the methods required for the CRUD related operations will be inherited from the super level/parent interfaces. Therefore we do not have to explicitly add or implement CRUD related methods.

Now we have created both Entity class and Repository. Next step is to configure/provide the mysql connection details. It can be provided in the file.

This will try to connect to the database  “spring_examples_db” running on local mysql server “localhost”  on port “3306”  by providing the username “root” and password “test123“.  You should change these properties based on your mysql server details.


Now we should implement our REST endpoints for creating, updating, removing and listing users etc…. Please refer the below UserController.


Creating the User

POST     /api/users

Here is the sample postman request and response.

Screen Shot 2017-12-31 at 11.37.01 AM.png


 public User create(@RequestBody User user)


@RequestBody – The body of the HTTP request will be mapped to the User class.

@ResponseBody – The retuned object will be mapped to the body of the HTTP response.


Retrieving all the users

GET  /api/users

Screen Shot 2017-12-31 at 11.47.03 AM.png



Retrieving a specific User/Resource

GET  /api/users/{user_id}


Screen Shot 2017-12-31 at 11.48.44 AM.png


Updating a Specific  User/Resource

PUT  /api/users/{user_id}


Screen Shot 2017-12-31 at 11.50.05 AM.png


Removing a Specific User/Resource

DELETE  /api/users/{user_id}


Screen Shot 2017-12-31 at 12.02.25 PM.png

Once the requested resource is successfully removed, it will return a list of available users.

Ok. we have completed all the REST endpoints for managing users with Spring Data JPA.

Finally we will look at the Spring Boot main configuration class.

The configuration class is very simple and we have fully utilized the advantages of spring boot and no additional configurations have been made. We have taken fully advantage of spring boot auto configuration feature.


Why didn’t we use @EntityScan or @EnableJpaRepositories annotations here?

The package that contains the main Spring Boot Application configuration class (that is annotated with @SpringBootApplication) is known as the main application package.

If the entity classes and repository classes are placed under the spring boot main application package or its sub package, the spring boot will take care of detecting and scanning of entities and repositories.  In such case wed do not have to explicitly declare the packages of Entities and Repositories with @EntityScan and @EnableJpaRepositories annotations respectively.

Please refer the below project structure.

Screen Shot 2017-12-31 at 12.30.41 PM.png

If you look at the project file structure, you can notice that entity and repository packages are sub packages of the main application package. Therefore the entities and repositories placed under those packages will be automatically scanned and detected when the spring boot application is loaded.

If you want to know more about @EntityScan and @EnableJpaRepositories annotations, please go my article publish on that.


The full source code of this article can be found at GitHub.

Click here to Download The Source Code.


Build and Running the application


Build the application

mvn clean install -DskipTests


Run The application

java -jar target/spring-boot-data-jpa-example-0.0.1-SNAPSHOT.jar


Hope this article is helpful for you.


Chathuranga Tennakoon


Spring Framework : Asynchronous task execution with @Async

Reason for Asynchronous Task Execution

In this article, i am expected discuss about the Spring’s Asynchronous task execution capability with @Async annotation. In software development, we have found some situations/scenarios where we need to execute some code segments/piece of logics asynchronously.  The following situations can be given as the examples.

  • sending email or sms for a user.
  • complex logic/data processing

Assume that you are trying to register  for and you are filling the registration form. once the registration form is summited, facebook should send you a confirmation email to activate your account. It will take considerable amount of time to send the confirmation email to the user. This is because, the facebook application may need to connect with the email server to send the email. Assume that it takes around 15 seconds to send the email. Then what will be your user experience.

Synchronous way:  You need to stay on the registration page until the application send you the confirmation email. Once the email is sent, the application will return a success response back to the application.  No choice. You have to hang on the registration page for at least 15 seconds (as we have agreed)  to get the success notification on the registration.  In the technical point of view, the caller Thread will get blocked (will have to wait) until all the logics are get executed.

Asynchronous way:  The task of sending email is delegated to a separate thread and it will be executed in the background (in a separate thread). Then the application does not wait until the email is sent and immediately send the success response back to the caller (ma be for the front end application).  In technical point of view, the caller does not have to wait until the all the logics get executed. Those will be executed in background threads.

The optimal and correct way to  execute these tasks as asynchronous background tasks.

Spring support for Asynchronous task execution

In spring it is possible to execute asynchronous tasks with @Async annotation. The logic inside the method that is annotated with @Async will be executed in a new separate thread. It does not execute in the caller’s thread.


Spring configuration for Asynchronous


This is a class level annotation and should be applied for any of the configuration class. This will enable the spring asynchronous task execution support for your application. Normally, this can be applied in the main configuration class of the application. The following code segment demonstrates the use of @EnableAsync with spring boot project.

public class SpringBootApplication{

(configuration class means a class that is annotated with @Cofiguration )


Is it required to use @EnableAsync ?

If you do not have applied this annotation for any of your configuration classes, the methods with @Async annotation will executed in the same thread. (caller thread)



This is a method level annotation. The code inside the annotated method will be executed in a new background thread (apart from the main thread).

Simply, if you need to execute a piece of code in a new background thread (Other than the calling thread), then put them inside a method that is annotated with @Async.

Few Rules with @Async

In order to apply the @Async for a method, it should meet the following requirements.

  • method should have the public access level.
  • method should have the void return type or the actual return type must be wrapped with Future interface (java.util.concurrent.Future).

The following are valid method declarations.

public void sendEmail(){}

public Future generateReport(){}


Ok.. Now it is enough with theories. Lets look at some coding examples.  The full source code of the application can be found at GitHub.

Click here to download the source code.


Project Strucure

I have assumed that you have cloned the source code and open it in your preferable IDE. Now you will see the project structure as follows.

Screen Shot 2017-11-14 at 1.17.12 AM.png

You will see that we have three workers.

  1. AsyncWorker – for demonstrating spring asynchronous method execution.
  2. NonAsyncWorker – for demonstrating the consequences of not using Spring asynchronous method execution. (executing the tasks in synchronous manner)
  3. AsyncWorkerFuture – for demonstrating how the result of asynchronous method execution is retrieved with Future interface.


Building and Running the Project


By looking at the spring boot configuration file, you can see that this application is developed to be run as a command line application. In order to invoke the relevant worker, you need to provide the matching command line argument.


command for building the application. 

mvn clean install


Executing the NonAsyncWorker

For executing the NonAsyncWorker, it is required to run the application with “non-async” as the command line argument.

java -jar target/spring-async-task-app.jar  non-async


when this command is run, the runNonAsyncWorkers() method of the WorkerService will get executed.

runNonAsyncWorkers() will repeatedly invoke the execute() method of the NonAsyncWorker five times.  once all the invocation are over, it will log the total execution time before completing the method execution.


Here is the code of the NonAsyncWorker.

NonAsyncWorker has a one method called execute(). it will print the current thread name and wait for 3 seconds before completing the method.

Here is the console output after executing the NonAsyncWorker.

Screen Shot 2017-11-14 at 2.05.18 AM.png


Now it is obvious that the WorkerService is started by the main thread and all the invocations of the NonAsyncWorker are also handled by the same thread (that is main thread). All of them will be executed in a sequential manner. Each invocation is guaranteed to be executed for at least 3 seconds.  Therefore it should take at least 15 seconds to complete all interactions.  If you properly examine the time log in console output, you will notice that our calculations has been proven.


Executing the AsyncWorker

In this way, each invocation will be handled in a separate thread apart from the calling(main) thread.

For executing the AsyncWorker, it is required to run the application with “async” as the command line argument.

java -jar target/spring-async-task-app.jar async


when this command is run, the runAsyncWorkers() method of the WorkerService will get executed.


runAsyncWorkers() will repeatedly invoke the execute() method of the AsyncWorker five times.  once all the invocation are over, it will log the total execution time before completing the method execution.


Here is the code of the AsyncWorker.


AsyncWorker has a one method called execute(). it will print the current thread name and wait for 3 seconds before completing the method. Once the sleeping time is completed, it will log the name of the thread as completed.

Here is the console output after executing the NonAsyncWorker.

Screen Shot 2017-11-26 at 7.32.23 PM.png

You can see that all the invocations has been happened in the same time (even if it is not shown here, there should be milliseconds of delay between each invocation and that can be neglected). In addition, you can notice that each invocation is handled by a separate thread apart from the main thread.  once the main thread has completed all iterations for method invocations, it will continue the main thread. you can see that all the interactions has been completed with less than 1 second. that is why it is logged as 0 seconds.(as i mentioned earlier, definitely there will be a milliseconds of duration)

each invocation has been waited/slept for 3 seconds and logged as completed with their handling thread name. If you look at the starting time and completing time of each thread, that is somewhere around 3 seconds. since all invocations has happened concurrently, it has taken only 3 seconds to complete all 5 invocations.


Executing Async work with Return (AsyncWorkerFuture)

In this way, each invocation will be handled in a separate thread apart from the calling(main) thread and main thread will wait to retrieve the result of the async task .

For executing the AsyncWorkerFuture, it is required to run the application with “async” as the command line argument.

java -jar target/spring-async-task-app.jar future


when this command is run, the  runAsyncWorkersWithFutureReturnType() method of the WorkerService will get executed.

isDone() method of the Future can be used to check whether future is completed with the returned output. if it is completed, the get() method can be used to retrieve the result.

Here is the console output of the execution.

Screen Shot 2017-11-26 at 8.09.50 PM.png


Hope you have got a good understanding of  how to handle asynchronous method execution in spring.

Spring Boot : Command Line Application

You can use  to generate the spring boot application as you are already aware.

It is very easy to create a spring boot application that is run on command line. You need to follow only two simple steps.

  1.  implements the CommandLineRunner interface.
  2.  override the run() method

if you have done above two steps, you are done with building the command line application with spring boot. here is the sample code segment.

How to build and run the application?
maven clan install

java -jar target/spring-boot-commandline-application-0.0.1-SNAPSHOT.jar


Full source code of this post can be found at GitHub

Spring Boot Custom Banner Example

In this article, i am expecting to demonstrate how to customize the spring boot banner. You may have noticed that a banner is being displayed when the application is up and running. You can customize this banner as your wish.

1.  Google for the word “ascii art generator

2.  Then you will find an ample of resources to generate ASCII characters. You can use one of the found resources to  generate the ASCII characters for your desired text. (I have used the for generating ASCII value.)


Screen Shot 2017-11-01 at 1.10.26 AM


3.  Finally copy the ASCII characters to file called banner.txt and put in the resources directory.

Screen Shot 2017-11-01 at 1.18.41 AM


4.  Then build and run the application. you will see the newly customized banner when your application is being loaded and run.

Screen Shot 2017-11-01 at 1.17.09 AM


The complete source code of the example can be found at GitHub

Converting Spring Boot JAR file into Tomcat deployable WAR file

By default, the spring boot applications are bundled into JAR regardless of its nature (web or stand alone app). Sometimes we need to create WAR file and deploy them in the tomcat server. In this article we are going to explore, how the spring boot application change in a way to create tomcat deployable WAR file.

In this application,  maven will be used as the build and dependency management tool.

The first step in producing a deployable war file is to provide a SpringBootServletInitializer subclass and override its configure method. This makes use of Spring Framework’s Servlet 3.0 support and allows you to configure your application when it’s launched by the servlet container. Typically, you update your application’s main class to extend SpringBootServletInitializer:

The next step is to update your build configuration so that your project produces a war file rather than a jar file. If you’re using Maven and using spring-boot-starter-parent (which configures Maven’s war plugin for you) all you need to do is to modify pom.xml to change the packaging to war:


The final step in the process is to ensure that the embedded servlet container doesn’t interfere with the servlet container to which the war file will be deployed. To do so, you need to mark the embedded servlet container dependency as provided.

Now you can use the below maven command to build the application.

mvn package


Securing Spring REST Api with Spring Security and JWT (Json Web Token)

In this article, i am going to demonstrate how to user JWT (Json Web Token) Authentication with Spring boot and Spring Security.  In here, i am not going to discuss the basic theory and details about the JWT and you can search google and find a lot of resources related to that.

GitHub URL :- 

I will update a screenshot of my project structure to get an idea of project structure and class/files locations. Don’t worry! This is just to get an idea. We will be doing everything one by one as we are proceeding.

Screen Shot 2017-07-17 at 3.07.00 PM

Before starting with the development, i will briefly give you an idea about the classes that we are going to develop in this article.
First step is to create spring boot web project. This can be easily created with Spring Initializer ( Remember to add web and spring security dependencies for your app.  In addition to that, it is important to add JWT dependency.

Required dependencies in pom.xml

<?xml version="1.0" encoding="UTF-8"?>





Then create a JwtService class as below. The JwtService class will be used for following two purposes.

  • Generate JWT token based on username upon successful user login.
  • Validate /Authenticate JWT token (user send along with every request)  and extract user information from the token. 

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

import static java.time.ZoneOffset.UTC;

public class JwtService {

    private static final String ISSUER = "com.chathuranga.examples";

    private SecretKeyProvider secretKeyProvider;

    public String generateToken(String username) throws IOException, URISyntaxException {
        byte[] secretKey = secretKeyProvider.getKey();
        Date expiration = Date.from(;
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, secretKey)

    public String verifyToken(String token) throws IOException, URISyntaxException {
        byte[] secretKey = secretKeyProvider.getKey();
        Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        //returning authenticated/verified username
        return claims.getBody().getSubject();

Now we need to create a LoginController for authenticating users with their credentials (username and password) and issue JWT token (using JwtService) upon successful authentication

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

public class LoginController {

    private UserAuthenticationService authenticationService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AuthenticationResponse userLogin(@RequestBody UserCredentials userCredentials) throws FailedToLoginException {

        if (userCredentials == null || (userCredentials.getUsername() == null || userCredentials.getPassword() == null)) {
            throw new FailedToLoginException("Missing login credentials ");

        String token = authenticationService.authenticateUser(userCredentials.getUsername(), userCredentials.getPassword());

        if (token != null) {
            AuthenticationResponse authenticationResponse = new AuthenticationResponse();
            return authenticationResponse;
        throw new FailedToLoginException(String.format(" unable to authenticate user [%s] ", userCredentials.getUsername()));

Here is the Implementation of the UserAuthenticationService class. For the demonstration purpose i have hard coded two user credentials. But in production environment, you need to implement JPA based user repository or some other mechanism like LDAP or OpenId.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

public class UserAuthenticationService {

    private JwtService jwtService;

    private UserService userService;

    public String authenticateUser(String username, String password) throws FailedToLoginException {
        boolean isAuthenticated = false;
        if (username.equals("chathuranga") && password.equals("test123")) {
            isAuthenticated = true;
        } else if (username.equals("bob") && password.equals("test123")) {
            isAuthenticated = true;

        if (isAuthenticated) {
            try {
                return jwtService.generateToken(username);
            } catch (URISyntaxException | IOException e) {
                throw new FailedToLoginException(e.getMessage());
        throw new FailedToLoginException(String.format("unable to authenticate user [%s]", username));

    public User authenticateToken(String jwtToken) throws JwtAuthenticationException {

        try {
            String username = jwtService.verifyToken(jwtToken);
            List<String> userRoles = userService.getUserRoles(username);

            User user = new User();
            return user;
        } catch (IOException | URISyntaxException e) {
            throw new JwtAuthenticationException(e.getMessage(), e);

One more thing! I forgot to show you the implementation of AuthenticationResponse class.
This is just a POJO class implemented to return the successful authentication response back to the client. Here is the implementation. You will notice that we are returning username and JWT token back to the client.


public class AuthenticationResponse {

    private String username;
    private String token;

    public String getToken() {
        return token;

    public void setToken(String token) {
        this.token = token;

    public String getUsername() {
        return username;

    public void setUsername(String username) {
        this.username = username;

Once this LoginController is fully developed, we should be able to authenticate users with their credentials. We have hardcoded few user credentials. I am going to test the user authentication with those credentials using Postman tool.

Username: chathuranga
Password: test123

Username: bob
Password: test123

Here is my Postman request.

Screen Shot 2017-07-17 at 4.33.39 PM

Here is the response retrieved. You can see that i am getting the username and JWT token as the response.

Now we have the JWT token. So we can use this token to show our authenticity.

Accessing Secured Api

Please refer the below secured controller. It has two methods to support for two endpoint URLs.

1. /api/admin/hello – this can be accessed only by users with ROLE_ADMIN
2. /api/user/hello – this can be accessed only by users with ROLE_USER


import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping(value = "/api")
public class WelcomeController {

    @RequestMapping(path = "/admin/hello", method = RequestMethod.GET)
    public String helloAdminController() {
        String loggedUserName = SecurityContextHolder.getContext().getAuthentication().getName();

        return "Hello Admin " + loggedUserName;

    @RequestMapping(path = "/user/hello", method = RequestMethod.GET)
    public String helloUserController() {

        String loggedUserName = SecurityContextHolder.getContext().getAuthentication().getName();

        return "Hello User " + loggedUserName;

Please refer the following Postman screenshot.

Screen Shot 2017-07-17 at 3.03.31 PM

Spring Security Related Configurations and Implementation Classes

import org.springframework.beans.factory.annotation.Autowired;

@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private JwtAuthFilter authFilter;

    private JwtAuthenticationProvider authenticationProvider;

    private JwtAuthenticationEntryPoint authenticationEntryPoint;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    protected void configure(HttpSecurity http) throws Exception {

                .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)

  • Here we have used a custom authentication provider called JwtAuthenticationProvider. It will be used to authenticate users , based on JWT token.  
  • We have disabled the CSRF token validation for URL  /login.  
  • Any request coming to /login will be permitted and any request coming to URL /api/** should be authenticated.
  • We have created a custom Filter (JwtAuthFilter) and it will be applied before executing UsernamePasswordAuthenticationFilter

Any authentication related exception will be handled using the custom authentication entry point provided.(That is JwtAuthenticationEntryPoint)

This filter will be used to capture the JWT token sent by the users through Authorization header. This will find the JWT token in the request header and set it in the Authentication object before executing the UsernamePasswordAuthenticationFilter provided by the Spring security.

(The filter creates an instance of  JwtAuthToken class with token retrieved and set it as  the current Authentication object for the request)

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

public class JwtAuthFilter implements Filter

    public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String authorization = servletRequest.getHeader("Authorization");

        if (authorization != null)
            JwtAuthToken token = new JwtAuthToken(authorization.replaceAll("Bearer ", ""));
        filterChain.doFilter(servletRequest, servletResponse);

    public void destroy()


    public void init(FilterConfig filterConfig) throws ServletException


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class JwtAuthenticationProvider implements AuthenticationProvider

    private UserAuthenticationService authenticationService;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException
      User user =  authenticationService.authenticateToken((String) authentication.getCredentials());
      return new JwtAuthenticatedUserToken(user.getUsername(),user.getUserRoles());

     Returns true if this AuthenticationProvider supports the indicated Authentication object.
    public boolean supports(Class<?> aClass)
        return JwtAuthToken.class.equals(aClass);

The JwtAuthenticationProvider receives the Authentication instance set on the SecurityContext, which in our case is the JwtAuthToken we set using the JwtAuthFilter. This token is then verified using the JwtService. If the token is valid, we return a JwtAuthenticatedUserToken (username and ACL – Access Control List) or throw an AuthenticationException if it is invalid. Any authentication related exception (an instance of AuthenticationException) will be handled by JwtAuthenticationEntrypoint.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;

public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
            throws IOException, ServletException {

        String message;
        if(e.getCause() != null) {
            message = e.getCause().getMessage();
        } else {
            message = e.getMessage();
        byte[] body = new ObjectMapper()
                .writeValueAsBytes(Collections.singletonMap("error", message));

Spring MVC : What is @RequestBody and @ResponseBody ?


@RequestBody and @ResponseBody annotations are used to convert the body of the HTTP request and response with java class objects. Both these annotations will use registered HTTP message converters in the process of converting/mapping HTTP request/response body with java objects.

The source code for this article can be found in the GitHub.

Click here to download the source code.

What is the HTTP Message Converter and Why it is used?

The client (web browser or REST client) cannot send the java objects (as it is) in the body of the HTTP request. On the other hand, the server application cannot compose the body of the HTTP response with java objects (as it is). Simply the HTTP Request and Response body cannot contains the in the form of java objects.

HTTP request and response body should contain either JSON , XML or some other type of formatted data (RSS etc).  Therefore the HTTP message converters are used to convert the HTTP request body (either in JSON or XML) to the Java objects and Java objects back to XML or JSON for embedding into the HTTP response body.


How the Message Converter Works?

you might be having a little confusion of how message converters are exactly worked. How the spring frameworks picks the right message converter that can transform the HTTP request body into the targeted java class object. On the other hand, how the server application responds back with exactly the similar type (either XML or JSON) that is expected by the client.  This is achieved by checking the headers of the HTTP request. Lets look at what are those headers in detailed.



This header informs the server application about the content type of the body of the HTTP Request. Based on the content type, the server application picks the correct message converter out of the available message converters  for converting the HTTP Request body into the java class object.


  • If the Content-Type is application/json , then it will select a JSON to Java Object converter.
  • If the Content-Type is application/xml , then it will select a XML to Java Object converter.



This header informs the server application about the Acceptable media type of the body of the HTTP Response (Simply what the client will accept from the server). Based on the value of the Accept header, the server application picks the correct message converter out of the available message converters  for converting returned java class object(s) to the requested media type.


  • If the Accept is application/json , then it will select a Java Object to JSON converter.
  • If the Accept is application/xml ,  then it will select a Java Object to XML converter.



This is used to convert the body of the HTTP request to the java class object with the aid of selected HTTP message converter. This annotation will be used in the method parameter and the body of the http request will be mapped to that method parameter. As described above, the message converter is selected based on the value of Content-Type  Header of the HTTP request.



This annotation is used to add the return value to the body of the HTTP response with the aid of selected HTTP message converter. As described above, the message converter is selected based on the value of Accept Header of the HTTP request. @RestController is the preferred way to achieve the same functionality earlier provided by @ResponseBody. Under the hood, @RestController is @Controller + @ResponseBody, and it avoids the need of prefixing every method with @ResponseBody.


Ok. enough theories. Lets do some cool stuffs with coding.  You can download the following samples from GitHub.


The following dependency has been added to configure/register the  HTTP message converter for XML type.



The source code of UserController has posted below and you can see that the single method available there. It can accept request body with both JSON and XML content types. In addition, it can produces both JSON and XML content types in response body.



@RequestBody will help to convert the body of the HTTP Request to the User object.  The method can handle a request body that is in the form of either XML or JSON.  The transformed user object will be saved to database using the userRepository. The persisted user object will be retuned by the method.

Since the class is annotated with @RestController, every method in the class is implicitly annotated with @ResponseBody.  Therefore the returned value/object will substitute the body of the HTTP Response. The body of the HTTP Response can be either XML or JSON.

Before building and running the application, make sure that you have changed the datasource configurations of  the to your development environment.



Ok lets run the application and make few api calls with Postman.


Round 1

POST   /api/users

Content-Type : application/json
Accept : application/json

Screen Shot 2018-01-01 at 11.31.51 PM.png


Request Body and Response Body

Screen Shot 2018-01-01 at 11.31.14 PM.png


Round 2

POST   /api/users

Content-Type : application/json
Accept : application/xml


Request Body and Response Body

Screen Shot 2018-01-01 at 11.35.57 PM.png


Round 3

POST   /api/users

Content-Type : application/xml
Accept : application/xml


Request Body and Response Body

Screen Shot 2018-01-01 at 11.37.49 PM.png


Round 4

POST   /api/users

Content-Type : application/xml
Accept : application/json


Request Body and Response Body

Screen Shot 2018-01-01 at 11.39.46 PM.png




I just wanted to explain you  about the ResponseEntity even if it is not mentioned in the code example.

ResponseEntity is a real deal. It represents the entire HTTP response. Good thing about it is that you can control anything that goes into it. You can specify status code, headers, and body. It comes with several constructors to carry the information you want to sent in HTTP Response.