Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When to use @Controller and when @RestController annotation in RESTApi based on Spring

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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";
   }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading