What is the difference between Controller and RestController?

When working on controllers in Spring, you would have seen there are two annotations which can be used to configure the controllers @Controller and @RestController.

@Controller is the traditional annotation used widely in Spring MVC, in which the controller is used to create the Model Object which contains data and the return the View object.

@RestController is a Restful webservice controller, which simply return an object and transmits the object data in HTTP Response in JSON or XML format.

So, the main difference is the way the HTTP response body is created. When you annotate @RestController for the controller, all the methods are written as objects instead of views. Moreover @RestController is same as @Controller + @ResponseBody.

Even though if you use @Controller, you can still return data. If you use @ResponseBody annotation.


@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
@AliasFor(
annotation = Component.class
)
String value() default "";
}


@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(
annotation = Controller.class
)
String value() default "";
}


Happy Programming...!!!

Comments

Popular posts from this blog

Method Reference in Java Streams

PHP LARAVEL Directory Structure

PHP LARAVEL - Hello World Laravel