@RestController annotation in Spring MVC

We usually use the @Controller annotation to develop Spring MVC applications, but since version 4.x, Spring has introduced another annotation called @RestController. What is the purpose of annotation @RestController? What is the difference between @Controller annotation and @RestController annotation? In this tutorial, let’s find out!

First, I will create a new Maven project as an example:

@RestController annotation in Spring MVC

If You do not know how to create this project, please follow the instructions of this tutorial.

The default dependencies have changed version as follows:

To run this project, I will use Maven Jetty Pluggin:

OK, let’s get started.

As you all know, in Spring MVC, the controller is the class that will be responsible for preparing the Model and selecting View to display the data in the Model to the View. In the example we just created, we have the HomeController class as a Controller class.

It adds the “serverTime” data to the Model and selects View as the home.jsp file located in /src/main/webapp/WEB-INF/views to render the interface.

The results will look like this:

@RestController annotation in Spring MVC

Beside preparation Model and selecting View, Controller class can also write data directly into the response stream without having to select any View. To do this, in the handle request method, we have to add another annotation, @ResponseBody.

For example, now, I add the @ResponseBody annotation to the home() method in the HomeController class as follows:

When running, you will no longer see results as before. Instead of the content of the home.jsp file with the Model data, the result is only “home” as the return portion of the home() method.

@RestController annotation in Spring MVC

This is what we usually do to develop RESTful Web Service applications. We only return data in formats such as JSON, XML, … and no View is needed.

For the sake of developing RESTful Web Service applications, Spring has introduced the @RestController annotation from version 4.x. With @RestController annotation replacing @Controller annotation, we do not need to declare annotation @ResponseBody anymore.

Now if I replace @Controller annotation with @RestController annotation and remove annotation @ResponseBody in the home() method:

The result is the same.

If you look at the code of @RestController annotation, you will see clearly the combination.

Add Comment