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
CodePudding user response:
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";
}
}