这篇教程帮你体验用Spring创建一个“Hello, World” RESTful Web服务的过程。
你会创建什么
你将会创建一个在http://localhost:8080/greeting
接收HTTP GET请求的服务。
它将会返回一个JSON格式的问候,就像下面一样:
{"id":1,"content":"Hello, World!"}
你可以通过在query string中提供一个可选的name
参数来自定义问候语,就像下面一样:
http://localhost:8080/greeting?name=User
name
参数值会覆盖默认的值World
并且体现在响应中,就像下面一样:
{"id":1,"content":"Hello, User!"}
你需要什么
- 大约15分钟
- 一个你喜欢的文本编辑器或者IDE
- JDK1.8或更高版本
- Gradle 4+ 或 Maven 3.2+
- 你也可以将代码直接导入IDE
如何完成这篇指南
和大多数的Spring Getting Started guides非常像,你可以从头开始并完成每一步或者跳过你已经熟悉的基础步骤。无论哪一种,你最终都可以获得可以运行的代码。
如果想从头开始, 请移步Starting with Spring Initializr.
如果想跳过基础步骤,做以下步骤:
- 下载并解压对应这份指南的源仓库,或者使用Git克隆它:
git clone https://github.com/spring-guides/gs-rest-service.git
- 进入
gs-rest-service/initial
- 跳转至Create a Resource Representation Class
当你完成时,你可以在gs-rest-service/complete
中查看对应你源代码的结果
从Spring Initializr开始
对于所有的Spring应用,你应该从Spring Initializr开始。这个Initializr提供了加入你项目所需的所有依赖的快速方法并且为你做了很多步骤。这个例子只需要Spring Web依赖。下方的图片展示了Initializr如何建立示例项目。
上面的图片展示了在Initializr中Maven被选作构建工具。你也可以使用Gradle。它还显示了com.example
和rest-service
各自作为Group和Artifact的值。你将会在剩余的示例中使用所选择的值。
下面的清单展示了你选择Maven时创建的pom.xml
文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>rest-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rest-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
下面的清单展示了你选择Gradle时创建的build.gradle
文件:
plugins {
id 'org.springframework.boot' version '2.3.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
建立一个Resource Representation类
鉴于你已经建立的项目且构建了系统,你可以创建你的Web服务了。
通过思考服务交互来开始这个过程。
这个服务将会处理发送至/greeting
的GET
请求。其中在query string中的参数name
是可选的。这个GET
请求应该返回一个在响应体中有JSON格式问候与的200 OK
响应。它应该看起来像下方的输出:
{
"id": 1,
"content": "Hello, World!"
}
id
字段是一个欢迎的唯一标识符,content
是代表欢迎的文字。
创建一个resource representation类来完成问候信息。为id
和content
数据提供一个带有字段、构造器、访问器的POJO(Plain Old Java Object)。就像下面(文件src/main/java/com/example/restservice/Greeting.java
)所展示的:
package com.example.restservice;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
本应用使用Jackson JSON库来自动地把Greeting
类型的实例转化为JSON。Jackson默认被包含在web starter中。
创建一个资源控制器
在Spring的创建RESTful web服务的方法中,HTTP请求在控制器中被处理。这些部件被@RestController
注解所标记,并且如下所示的GreetingController
(文件src/main/java/com/example/restservice/GreetingController.java
)通过返回一个Greeting
类的新实例来处理发送到/greeting
的GET
请求。
package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
这个控制器是非常简明的,但是其背后也有许多值得学习的内容。我们一步步来讲解它。
@GetMapping
注解确保发送到/greeting
的HTTP GET请求被映射到greeting()
方法。
还有一些关于其他HTTP请求方法的注解(例如用于POST方法的@PostMapping
)。这些注解都派生于@RequestMapping
注解,并且该注解可以作为他们的同义词提供服务(例如@RequestMapping(method=GET)
)。
@RequestParam
将query string中name
参数的值绑定到greeting()
方法的name
参数中。如果name参数在请求中缺失,则defaultValue
的值World
将被使用。
函数体的实现创建并且返回了一个新的带有id
和content
属性的Greeting
对象。其中id
基于变量counter
的下一个值,content
则是基于格式化后的给定name
值的问候 template
。
传统MVC控制器与和刚才介绍的RESTful web服务的一个关键区别就是HTTP响应体的创建方式不同。RESTful web服务控制器产生并返回一个Greeting
对象,而不是依赖于视图技术执行服务端渲染来将问候数据渲染到HTML。对象数据将以JSON格式直接写入HTTP响应。
这段代码使用Spring@RestController
注解,它将类标记为控制器,在控制器中每个方法返回一个域对象而不是视图。它是联合使用@Controller
和@ResponseBody
的简便写法。
这个Greeting
对象必须被转换为JSON。得益于Spring的HTTP消息转换器的支持,你无需手动进行转换。由于Jackson 2在classpath中,Spring的MappingJackson2HttpMessageConverter
被自动选中来将Greeting
实例转换为JSON。
@SpringBootApplication
是一个便捷的注解写法来添加下方所列的东西:
@Configuration
:为应用上下文中标记这个类为bean定义的源。@EnableAutoConfiguration
:告诉Spring Boot开始键入基于classpath设置、其他beans和各种各样的属性设置。例如,如果spring-webmvc
在classpath中,这个注解标记应用为一个Web应用并且激活关键行为,例如建立一个DispatcherServlet
。@ComponentScan
:告诉Spring在com/example
包中寻找其他组件、配置和服务,让他找到控制器。
main()
函数使用Spring Boot的SpringApplication.run()
方法来启动应用。你注意到教程中一行XML也没有了吗?也没有web.xml
文件。这个Web应用是百分百纯Java的,你不用处理高级或基础的配置。
构建可执行的JAR
你可以使用Gradle或者Maven从命令行运行应用。你也可以构建一个包含所有必需依赖、类和资源的单独的可执行JAR文件然后运行它。构建一个可执行的JAR文件使得项目在整个开发生命周期中,都可以将服务作为应用程序,在跨不同环境等等情况下轻松发布、版本化和部署。
如果你使用Gradle,你可以通过./gradlew bootRun
运行应用。或者,你可以通过./gradlew build
构建JAR文件然后运行它,如下所示:
java -jar build/libs/gs-rest-service-0.1.0.jar
如果你使用Maven,你可以通过./mvnw spring-boot:run
运行应用.。或者,你可以通过./mvnw clean package
构建JAR文件然后运行它,如下所示:
java -jar target/gs-rest-service-0.1.0.jar
这些步骤描述了创建可执行JAR的过程。你也可以构建一个传统的WAR文件。
测试服务
鉴于服务可用,访问http://localhost:8080/greeting,在那里你应当看到:
{"id":1,"content":"Hello, World!"}
通过访问http://localhost:8080/greeting?name=User在query string中提供name
参数。注意content
的值从Hello, World!
变成了Hello, User!
,如下所示:
{"id":2,"content":"Hello, User!"}
这个变化证明在GreetingController
中@RequestParam
注解的工作符合预期。name
参数被给予一个默认值World
但是可以可以通过query string显式覆盖。
也要注意id
属性是如何从1
变到2
的。这证明您的多个请求针对同一个GreetingController
进行操作。并且GreetingController
的counter
字段正在按照预期地每次请求加一。
总结
恭喜!你刚刚通过Spring开发了一个RESTful web服务。
还可以看
The following guides may also be helpful:
- Accessing GemFire Data with REST
- Accessing MongoDB Data with REST
- Accessing data with MySQL
- Accessing JPA Data with REST
- Accessing Neo4j Data with REST
- Consuming a RESTful Web Service
- Consuming a RESTful Web Service with AngularJS
- Consuming a RESTful Web Service with jQuery
- Consuming a RESTful Web Service with rest.js
- Securing a Web Application
- Building REST services with Spring
- React.js and Spring Data REST
- Building an Application with Spring Boot
- Creating API Documentation with Restdocs
- Enabling Cross Origin Requests for a RESTful Web Service
- Building a Hypermedia-Driven RESTful Web Service
- Circuit Breaker
Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.
All guides are released with an ASLv2 license for the code, and an Attribution, NoDerivatives creative commons license for the writing.