我有以下问题:为什么 GraphQL 控制器在 Spring 中没有注释为 RestController?我遵循了 spring 的官方guide,并且只使用了 Controllers 注释。但是,如果我们查看响应,它是一个 JSON。
我的理解是:
@Controller 注释通常用于基于 UI 的应用程序,其中响应通常是 HTML 页面。
@RestController可以直接在响应体中返回数据,一般为JSON或XML格式。
@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());
}
}
@RestController
注释是 @Controller
和 @ResponseBody
的组合,如果您愿意的话,这是一个快捷方式。 @Controller
将类标记为 @Component
(因此在扫描期间被视为 bean),它对于 Web 应用程序具有特定的作用:Spring 基础结构将查找方法上的映射注释并使用它们来注册处理程序。
Spring for GraphQL 项目选择重用
@Controller
信号来检测 GraphQL API 的处理程序。您可以使用 @Controller
完美注释控制器,并使用 @GetMapping
和 @ResponseBody
注释其某些方法,而仅使用 @QueryMapping
注释其他方法。 @RestController
也可以工作,唯一的区别是控制器中的所有 @RequestMapping
方法都期望使用返回值作为响应主体。
对于 GraphQL,这没有什么区别,因为没有 HTML 视图支持,并且从方法返回的值始终会贡献给 GraphQL 响应。