Tuesday, March 21, 2023

Difference between @RestController and @Controller Annotation in Spring MVC and REST

The @RestController annotation in Spring MVC is nothing but a combination of @Controller and @ResponseBody annotation. It was added into Spring 4.0 to make the development of RESTful Web Services in Spring framework easier. If you are familiar with the REST web services you know that the fundamental difference between a web application and a REST API is that the response from a web application is generally view (HTML + CSS + JavaScript)  because they are intended for human viewers while REST API just returns data in form of JSON or XML because most of the REST clients are programs. This difference is also obvious in the @Controller and @RestController annotation.

The job of @Controller is to create a Map of the model object and find a view but @RestController simply returns the object and object data is directly written into HTTP response as JSON or XML.

This can also be done with traditional @Controller and use @ResponseBody annotation but since this is the default behavior of RESTful Web services, Spring introduced @RestController which combined the behavior of @Controller and @ResponseBody together.

In short, the following two code snippet are equal in Spring MVC:

@Controller
@ResponseBody
public class MVCController { 
   .. your logic
}

@RestController
public class RestFulController { 
  .... your logic
}

Obviously, everybody would like to declare just one annotation instead of two. Also, the @RestController is more obvious and telling than the previous two. Btw, if you are not familiar with Spring Core and Spring MVC, I suggest you first take a look at the Spring Framework: Beginner to Guru course on Udemy. One of the up-to-date and comprehensive courses to learn Spring.





What are @Controller and @RestController in Spring?

In the Spring framework, A Controller is a class that is responsible for preparing a model Map with data to be displayed by the view as well as choosing the right view itself. It can also directly write into the response stream by using @ResponseBody annotation and complete the request.

The behavior of writing directly into response stream is very useful for responding calls to RESTful web services because their we just return data instead of returning a view as explained in my earlier post about how Spring MVC works internally.

If you have developed RESTful Web services before Spring 4 like in Spring 3 or Spring 3.1, you would have been familiar with using a combination of @Controller and @ResponseBody to create a RESTful response. Spring guys take cognizant of these issues and created @RestController.

Now, you don't need to use @Controller and @RestponseBody annotation, instead you can use @RestController to provide the same functionality. In short, it is a convenience controller that combines the behavior of @Controler and @Response body into one.

If you are interested in developing RESTful web services with Spring then you can further join Eugen Paraschiv's REST with Spring Master class if you are more curious about learning the advanced techniques to develop RESTFul Web Service in Spring. One of the guided and code-focused way to learn Spring MVC.

Difference between @RestController and @Controller in Spring



Difference between @RestController and @Controller in Spring

Now that, you are familiar with both of these annotations, it's a good time to analyze some factual differences between @RestController and @Controler. This is a very important concept, not just from the Interview point of view but also from Spring Core  Developer Certification.

 If you are preparing for Spring certifications, you should familiar with such subtle differences. Additionally, you can also take a look at free Spring tests to get an idea about the exam format and level of questions.

Anyway, let's get back to the point, here are some important differences between these two annotations.

1. The @Controller is a common annotation that is used to mark a class as Spring MVC Controller while @RestController is a special controller used in RESTFul web services and the equivalent of @Controller + @ResponseBody.

2. The @RestController is relatively new, added only on Spring 4.0 but @Controller is an old annotation, exists since Spring started supporting annotation, officially it was added on Spring 2.5 version. You can learn more about @RestController and other Spring 4 annotations on Master RESTful Web Services with Spring Boot course on Udemy. Spring boot really makes it easy to develop REST APIs with spring.

3. The @Controller annotation indicates that the class is a "Controller" like a web controller while @RestController annotation indicates that the class is a controller where @RequestMapping methods assume @ResponseBody semantics by default i.e. servicing REST API.


4. The @Controller is a specialization of @Component annotation while @RestController is a specialization of @Controller annotation. It is actually a convenience controller annotated with @Controller and @ResponseBody as shown below.

@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController

and here is how the declaration of @Controller looks like:

@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Controller


5. One of the key differences between @Controler and @RestCotroller in Spring MVC is that once you mark a class @RestController then every method is written a domain object instead of a view. You can see Bryan Hassen's Introduction to Spring MVC 4 to learn more about how to use the @RestController annotation in your Spring-based application.

@RestController vs @Controller Annotation in Spring MVC and REST



6. Another key difference between @RestController and @Controller is that you don't need to use @ResponseBody on every handler method once you annotate the class with @RestController as shown below:

with @RestControler

@RestController
public class Book{

@RequestMapping(value={"/book"})
public Book getBook(){
//...
return book;
}
}

without @RestController

@Controller
public class Book{

@RequestMapping(value={"/book"})
@ResponseBody
public Book getBook(){
//...
return book;
}
}

You can see that if you use Spring MVC @Controller annotation to create a RESTful response you need to annotate each method with the @ResponseBody annotation, which is not required when you use @RestController. It not only makes your code more readable but also saves a couple of keystrokes for you.


Here is a simple HelloWorld example using @RestController and Spring Boot framework:

Difference between @RestController and @Controller Annotation in Spring MVC and REST


That's all about the difference between @Controller and @RestController annotation in Spring MVC and REST. @RestController is nothing but the shortcut to use both @Controller and @ResponseBody annotation together. In other words, @Controller is used to controller which can accept and return HTML while @RestController annotation can be used to return JSON response. 

Spring purposefully added this annotation in Spring 4 to make the development of RESTful web services easier using the Spring framework. It can directly convert the response to JSON or XML depending upon the MIME type of request.

So, if you are creating a RESTful Web Services it's better to use @RestController than combining @Controller to @ResponseBody.


Other Spring related articles you may like to explore this blog
  • 5 Free Spring and Spring Boot Courses to learn online (courses)
  • 23 Spring MVC Interview questions for 2 to 3 years experienced (list)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • 20+ Spring and REST Interview Questions (questions)
  • 3 ways to learn Spring Framework better (article
  • 25 Spring Security Interview Questions (spring security questions)
  • How to enable Spring security in Java application? (answer)
  • 13 Spring Actuator interview questions (spring actuator questions)
  • Does Spring certification help in Job and Career? (article)
  • Top 5 Spring Certification Mock Exams (list)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Spring and Hibernate online courses for Java developers (list)
  • 20 Spring Boot Testing Interview questions (Spring boot questions)
  • 10 Spring Annotation Java Developers Should Know (annotations)
  • Top 5 Spring Boot Features for Java Developers (features)

Thanks for reading this article. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment and I'll try to answer it as soon as possible.

P. S. - If you want to learn more about developing RESTful Web Services using Spring and Spring Security framework, I suggest you join Eugen Paraschiv's REST with Spring certification class. Eugen has some good real-world experience in developing and securing RESTful web services in Java and this class is a good opportunity to benefit from his immense experience.

9 comments :

Anonymous said...

Good

Anonymous said...

Awesome

saavedra29 said...

Thanks, very good explaination

Unknown said...

Thanks ,nice explaination

Brocho said...

Easy explained! Thanks!

manav said...

One correction @RestponseBody should be @ResponseBody

javin paul said...

ah yes, thx for correcting it.

Bruce Quesenberry said...

Just found this nugget of wisdom, I like how you dug down into the guts of the annotation. RestController is a Controller which is a Component and all are interfaces. Bit confused about the public @interface Controller. Wondering what @interface is doing as far as the "@"?

Anonymous said...

Good explanation

Post a Comment