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.
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.
@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.
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.
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.
@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 { }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With