0

I am new to learning Spring and I created a simple RestApi. Now in some tutorials I see that the controller class is sometimes annotated with @Controller and others are annotated with @RestController.

Can anyone clarify the differences for me? Thanks

codeax13
  • 11
  • 1
  • Another major difference is If you annotate RestController your method response automatically converted into Json format. Controller you have to define the response type. – Thirumaran May 12 '22 at 08:08

1 Answers1

1

It only took one quick google search for me to get a lot of answers. Also, this question has already been answered in another SO thread, found here.

But quickly summarized:

@Controller is used to annotate your controller class. When using @Controller you typically use it in combination with @ResponseBody. So you annotate your endpoint methods with @ResponseBody to let Spring know what return type to expect from that particular endpoint.

@Controller
public ControllerClass {

   @GetMapping("/greetings")
   @ResponseBody
   private String someEndpoint(){
       return "hey";
   }

}

@RestController simply combines @Controller and @ResponseBody. So you don't need to annotate your endpoint methods with @ResponseBody. A single anntoation of your controller class will do the magic. The return type of the endpoint methods are used as response body.

@RestController
public ControllerClass {

   @GetMapping("/greetings")
   private String someEndpoint(){
       return "hey";
   }

}
Domiii
  • 66
  • 4