Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between spring @Controller and @RestController annotation

Difference between spring @Controller and @RestController annotation.

Can @Controller annotation be used for both Web MVC and REST applications?
If yes, how can we differentiate if it is Web MVC or REST application.

like image 548
Srikanth Avatar asked Aug 11 '14 11:08

Srikanth


People also ask

What is difference between REST controller and controller?

The main difference between the @restcontroller and the @controller is that the @restcontroller combination of the @controller and @ResponseBody annotation. RestController: RestController is used for making restful web services with the help of the @RestController annotation.

What is the difference between @controller and @component in Spring?

@Component : It is a basic auto component scan annotation, it indicates annotated class is an auto scan component. @Controller : Annotated class indicates that it is a controller component, and mainly used at the presentation layer. @Service : It indicates annotated class is a Service component in the business layer.

Can we replace @controller with @RestController?

In simple words, @RestController is @Controller + @ResponseBody. So if you are using latest spring version you can directly replace @Controller with @RestController without any issue.

What is are the uses of the @RestController annotation?

Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.


2 Answers

  • @Controller is used to mark classes as Spring MVC Controller.
  • @RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations (see: Javadoc)

So the following two controller definitions should do the same

@Controller @ResponseBody public class MyController { }  @RestController public class MyRestController { } 
like image 98
micha Avatar answered Sep 30 '22 00:09

micha


In the code below I'll show you the difference between @controller

@Controller public class RestClassName{    @RequestMapping(value={"/uri"})   @ResponseBody   public ObjectResponse functionRestName(){       //...       return instance    } } 

and @RestController

@RestController public class RestClassName{    @RequestMapping(value={"/uri"})   public ObjectResponse functionRestName(){       //...       return instance    } } 

the @ResponseBody is activated by default. You don't need to add it above the function signature.

like image 27
BERGUIGA Mohamed Amine Avatar answered Sep 29 '22 23:09

BERGUIGA Mohamed Amine