I have the following question: why are the GraphQL Controllers not annotated as a RestController in the spring? I followed the official guide from spring and only the Controllers annotation is used. However, if we look at the Response it's a JSON.
My understanding is that:
@Controller annotation is typically used in UI-based applications where the response is generally an HTML page.
@RestController can return data directly in the response body, typically in JSON or XML format.
@Controller
public class BookController {
@QueryMapping
public Book bookById(@Argument String id) {
return Book.getById(id);
}
@SchemaMapping
public Author author(Book book) {
return Author.getById(book.authorId());
}
}
The
@RestControllerannotation is a combination of@Controllerand@ResponseBody, a shortcut if you will.@Controllermarks a class as a@Component(so considered as a bean during scanning) that has a specific role for web applications: the Spring infrastructure will look for mapping annotations on methods and use those to register handlers.Spring for GraphQL project chose to reuse the
@Controllersignal for detecting handlers for GraphQL APIs. You can perfectly annotate a controller with@Controllerand some of its methods with@GetMappingand@ResponseBody, others with@QueryMappingonly.@RestControllerwill also work, the only difference is that all@RequestMappingmethods in the controller will expect to use the return value as the response body.In the case of GraphQL, this makes no difference as there is no HTML view support and the values returned from methods are always expected to be contributed to the GraphQL response.