Difference Between Spring @Controller and @Restcontroller Annotation

Difference between spring @Controller and @RestController annotation

  • @Controller is used to mark classes as Spring MVC Controller.
  • @RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations (see: Javadoc)

So the following two controller definitions should do the same

@Controller
@ResponseBody
public class MyController { }

@RestController
public class MyRestController { }

Springboot @Controller and @RestController Annotations when to use and what is the underlying concept?

@RestController is itself annotated with two Spring annotations: @Controller and @ResponseBody.

That means that the only difference between @RestController and @Controller is in the handling of return values.

With @RestController, the return value is used as the response body. That's exactly what you want when writing REST services.

With @Controller you don't get this so you get the default handling. That means that a string return value is seen as the view to render, not a string to return as-is.

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

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

}

Controller or RestController

The job of @Controller is to create a Map of model object and find a view but @RestController simply return the object and object data is directly written into HTTP response as JSON or XML.

The @Controller is a common annotation which is used to mark a class as Spring MVC Controller while @RestController is a special controller used in RESTFul web services and the equivalent of @Controller + @ResponseBody.

If you want the same functionality of @RestController without using it you can use @Controller and @ResponseBody.

@Controller
public class HelloController{

@RequestMapping("/")
@ResponseBody
public String index() {
return "index";
}
}


Related Topics



Leave a reply



Submit