Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Springboot @Controller and @RestController Annotations when to use and what is the underlying concept?

It is more of an observation than a question because I spent more than 2-3 hrs just figuring out which annotation should be used according to our needs.

According to me, @Controller is used when we are making a proper MVC application that will do internal routing for the app and give a response along with a View(HTML PAGE) instead of exposing raw details.@RestController is used when we are making a RestFul App whose purpose is only to get the data fetched from the DB and perform a query. The Data which we get while using the @RestController is in JSON format.

I want to know why spring behaves in this particular manner and is there some internal working that a SpringBoot learner should know for making restful APIs.

like image 367
Aditya Sadaphule Avatar asked Sep 03 '25 03:09

Aditya Sadaphule


1 Answers

@RestController is itself annotated with two Spring annotations: @Controller and @ResponseBody.

That means that the only difference between @RestController and @Controller is in the handling of return values.

With @RestController, the return value is used as the response body. That's exactly what you want when writing REST services.

With @Controller you don't get this so you get the default handling. That means that a string return value is seen as the view to render, not a string to return as-is.

like image 200
Rob Spoor Avatar answered Sep 05 '25 02:09

Rob Spoor