

REST(Representational State Transfer)和GraphQL都是用于构建Web服务的API设计和交互方式,它们有不同的特点和优劣势。
REST(Representational State Transfer):
/users/1表示用户1的信息。资源的操作通常使用HTTP动词来执行,如GET(获取资源)、POST(创建资源)、PUT(更新资源)和DELETE(删除资源)等。
GraphQL:
/graphql),客户端可以在单个请求中获取多个资源的数据。
选择REST还是GraphQL取决于您的项目需求和偏好。REST通常更简单,适用于简单的API,而GraphQL提供了更大的灵活性和效率,特别适用于复杂的数据查询和实时应用程序。根据项目的具体情况,您可以选择其中之一或将它们结合使用。

在Spring Boot中整合REST,您可以使用Spring Web模块,它提供了用于构建RESTful Web服务的支持。下面是一个简单的示例工程:
pom.xml文件中包含以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, REST!";
}
}http://localhost:8080/api/hello将返回"Hello, REST!"。这就是一个简单的Spring Boot整合REST的示例工程。
在Spring Boot中整合GraphQL,您可以使用第三方库(例如graphql-java和spring-graphql)。下面是一个简单的示例工程:
pom.xml文件中包含以下依赖:
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>11.1.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>11.1.0</version>
<scope>runtime</scope>
</dependency># src/main/resources/graphql/schema.graphqls
type Query {
hello: String
}import graphql.schema.DataFetcher;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GraphQLConfig {
@Bean
public GraphQLSchema schema() {
return GraphQLSchema.newSchema()
.query(queryType())
.build();
}
@Bean
public GraphQLQueryResolver queryType() {
return new GraphQLQueryResolver() {
public String hello() {
return "Hello, GraphQL!";
}
};
}
}http://localhost:8080/graphiql可以使用图形化界面测试GraphQL查询,或者通过POST请求http://localhost:8080/graphql发送查询。这就是一个简单的Spring Boot整合GraphQL的示例工程,它允许您定义自己的GraphQL模式和查询,并通过HTTP端点进行查询。