Spring

Spring MVC @Controller vs @RestController Annotation

Introduction:

In this tutorial, we’ll look at the difference between @Controller and @RestController annotations in Spring MVC.

The @Controller annotation has been part of the Spring framework from the very beginning. As its name suggests, it defines a controller: an entry-point for a Spring Web application.

Spring 4 introduced a @RestController annotation. It is a combination of @Controller and @ResponseBody annotations. With it, we no longer need to annotate every method of our REST controller using @ResponseBody. Therefore, it eases out the process of defining a RESTful service controller.

The Spring @Controller Annotation:

We are all aware of the @Controller annotation. It is used to define a controller, now mostly for Spring Web applications. It can be held responsible for both generating a model as well as rendering a specific view to the user. As per the Spring docs definition:

It is nothing but a specialization of @Component annotation.

Let’s write our own example Spring MVC Controller:

Clearly, we have used @ResponseBody annotation in our getUserDetails() method explicitly. It is responsible for serializing the returned object into a JSON/XML and then returning it as a HttpResponse.

The Spring @RestController Annotation:

Whenever we write a REST Controller, all its methods return either a JSON or an XML response. Such controllers aren’t usually responsible for rendering any view to the user. So, we can use @RestController annotation for such cases. It’s a combination of both @Controller and @ResponseBody annotations.

In the Spring docs, it’s defined as:

So we can remove @ResponseBody annotations when using @RestController:

Our RESTful controller looks a lot cleaner and readable when using @RestController.

Differences In A NutShell:

Spring @ControllerSpring @RestController
It is a specialization of @Component annotation and used to define Spring MVC controllerIt is a specialization of @Controller. It is a combination of @Controller and @ResponseBody annotations
It was defined in earlier versions of SpringIt was defined in Spring version 4.
When marking the controller with @Controller, it can either return an object or render a viewWhen we mark the controller with @RestController, it can only return a domain object.

Conclusion:

In this article, we looked at the difference between @Controller and @RestController annotations. When writing a RESTful service, using @RestController annotation eliminates the need to use @ResponseBody annotation with each method definition. Therefore, it simply saves us from a few additional keystrokes and makes more sense.

One comment
Pingback: Spring MVC Annotations | Good day Android - Android World

Leave a Comment

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