Pages

July 03, 2018

Difference Between @RestController and @Controller

What is the difference between @RestController and @Controller Annotation in Spring MVC and REST?
@RestController was added into Spring 4.0 to make the development of RESTful Web Services in Spring framework easier. But @Controller was added on Spring 2.5 version.

A web application is generally returns a view (HTML + CSS + JavaScript) because they are intended for human viewers. Where as REST API just returns data in form of JSON or XML.


@Controller creates a Map of the model object and find a view, but @RestController just returns the object and object data is directly written into HTTP response as JSON or an XML.

In short the @RestController annotation in Spring MVC is nothing but a combination of @Controller and @ResponseBody annotation.

FYI, @ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header. @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

The @Controller is a specialization of @Component annotation while @RestController is a specialization of @Controller annotation.

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

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

-K Himaanshu Shuklaa..

No comments:

Post a Comment