本指南将指导您完成创建使用REST式Web服务的应用程序的过程。
你将构建一个使用Spring的 RestTemplate
来检索随机Spring Boot引用的应用程序 http://gturnquist-quoters.cfapps.io/api/random
.
与大多数Spring 入门指南 一样,您可以从头开始并完成每个步骤,也可以绕过已经熟悉的基本设置步骤。 无论如何,你最终得到工作代码。
要从头开始, 请转到 使用Gradle构建 .
要跳过基本操作,请执行以下操作:
git clone https://github.com/spring-guides/gs-consuming-rest.git
gs-consuming-rest/initial
完成, 你可以根据 gs-consuming-rest/complete
中的代码检查结果.
首先你设置一个基本的构建脚本。 你可以使用任何你喜欢的一个来构建项目,当使用Spring构建应用程序时,但是需要使用 Gradle 和 Maven 来写你的代码。 如果你不熟悉任何一个,请参考 使用Gradle构建Java项目 或 使用Maven构建Java项目 。
在您选择的项目目录中,创建以下子目录结构; 例如,在 nix 系统上使用`mkdir -p src / main / java / hello’:
└── src
└── main
└── java
└── hello
下面是 initial Gradle build file .
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-consuming-rest'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter")
compile("org.springframework:spring-web")
compile("com.fasterxml.jackson.core:jackson-databind")
testCompile("junit:junit")
}
Spring Boot gradle插件 提供了许多方便的功能:
public static void main()
方法来标记为可运行类。 首先你设置一个基本的构建脚本。 你可以使用任何你喜欢的一个来构建项目,当使用Spring构建应用程序,但是需要使用 Maven 来构建你的代码。 如果你不熟悉Maven,请参考 使用Maven构建Java项目 .
在您选择的项目目录中,创建以下子目录结构; 例如,在 nix 系统上使用`mkdir -p src / main / java / hello’:
└── src
└── main
└── java
└── hello
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<projectxmlns="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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-consuming-rest</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Spring Boot Maven插件 提供了许多方便的功能:
public static void main()
方法来标记为可运行类。 完成项目设置后,您可以创建一个使用RESTful服务的简单应用程序。
一个RESTful服务已经在 http://gturnquist-quoters.cfapps.io/api/random 上建立了起来。 它随机获取关于Spring Boot的引用,并将它们作为JSON字符串返回。
如果您通过Web浏览器或curl请求该网址,您会收到一个JSON字符串,如下所示:
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}
足够简单吧,不过通过浏览器或通过curl去获取,终究不是长久之事。
一种更有用的方式来测试REST Web服务是以编程方式。 为了帮助你完成这个任务,Spring提供了一个方便的模板类
RestTemplate
。 RestTemplate
使得与大多数RESTful服务进行交互是一种享受。 它甚至可以将该数据绑定到自定义域类型。
首先,创建一个domain类以包含所需的数据。
src/main/java/hello/Quote.java
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public classQuote{
private String type;
private Value value;
publicQuote(){
}
publicStringgetType(){
return type;
}
publicvoidsetType(String type){
this.type = type;
}
publicValuegetValue(){
return value;
}
publicvoidsetValue(Value value){
this.value = value;
}
@Override
publicStringtoString(){
return "Quote{" +
"type='" + type + '/'' +
", value=" + value +
'}';
}
}
正如你所看到的,这是一个简单的Java类,有几个属性和相应的getter方法。 当使用来自Jackson JSON处理库的 @ JsonIgnoreProperties
进行注释,代表在此类中未绑定的任何属性都应该被忽略。
需要一个额外的类来嵌入内部引用本身。
src/main/java/hello/Value.java
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public classValue{
private Long id;
private String quote;
publicValue(){
}
publicLonggetId(){
return this.id;
}
publicStringgetQuote(){
return this.quote;
}
publicvoidsetId(Long id){
this.id = id;
}
publicvoidsetQuote(String quote){
this.quote = quote;
}
@Override
publicStringtoString(){
return "Value{" +
"id=" + id +
", quote='" + quote + '/'' +
'}';
}
}
这里通过使用相同的注解,但可以很轻松地映射到其他数据字段。
虽然可以将此服务打包为用于部署到外部应用程序服务器的传统 WAR
文件,但下面演示的创建一个独立应用程序的方法更简单。 你把一切都包装在一个可执行的JAR文件中,由一个大家初学Java时的Java main()
方法驱动。 整个过程,你使用Spring支持嵌入的 Tomcat
servlet容器作为HTTP运行时的容器,而不是部署到外部实例中去。
现在你可以写使用 RestTemplate
的 Application
类来从我们的Spring Boot引用服务并且获取数据。
src/main/java/hello/Application.java
public classApplication{
private static final Logger log = LoggerFactory.getLogger(Application.class);
publicstaticvoidmain(String args[]){
RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
}
}
因为Jackson JSON处理库在类路径中, RestTemplate
将使用它(通过 message converter
)将传入的JSON数据转换为一个“Quote”对象。 从那里, Quote
对象的内容将被记录到控制台。
这里你只使用 RestTemplate
来做一个HTTP GET
请求。 但是RestTemplate也支持其他HTTP动词,例如 POST
, PUT
和 DELETE
。
到目前为止,我们没有在我们的应用程序中使用Spring Boot,Spring Bootd 一些优点,使用起来并不难。 其中的一个优点是我们可能想让Spring Boot管理 RestTemplate
中的消息转换器,以便定制很容易声明性地添加。 为此,就像在任何Spring Boot应用程序中一样,我们在主类上使用 @ SpringBootApplication
,并转换main方法来启动它。 最后,我们将 RestTemplate
移动到 CommandLineRunner
回调,所以它在启动时由Spring Boot执行:
src/main/java/hello/Application.java
package hello;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public classApplication{
private static final Logger log = LoggerFactory.getLogger(Application.class);
publicstaticvoidmain(String args[]){
SpringApplication.run(Application.class);
}
@Bean
publicRestTemplaterestTemplate(RestTemplateBuilder builder){
return builder.build();
}
@Bean
publicCommandLineRunnerrun(RestTemplate restTemplate)throwsException{
return args -> {
Quote quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}
RestTemplateBuilder
是由Spring注入的,如果你使用它来创建一个 RestTemplate
,那么你将受益于在Spring Boot中使用消息转换器和请求工厂发生的所有自动配置。 我们还将 RestTemplate
注解为 @ Bean
,以便更容易测试(它可以更容易地被测试)。
您可以使用Gradle或Maven从命令行运行应用程序。 或者,您可以构建单个可执行文件,其中包含所有必需的依赖关系,类和资源,并运行它。 这使得在整个开发生命周期中,易于跨不同环境将服务作为应用程序进行发布,维护版本和部署等等。
如果您使用Gradle,可以使用 ./gradlew bootRun
运行应用程序。 或者你可以使用 ./gradlew build
来构建JAR文件。 然后可以运行JAR文件:
java -jar build/libs/gs-consuming-rest-0.1.0.jar
如果您使用Maven,可以使用 ./maven spring-boot:run
运行应用程序。 或者你可以用 ./mvn clean package
构建JAR文件。 然后可以运行JAR文件:
java -jar target/gs-consuming-rest-0.1.0.jar
| ** | 上面的过程将创建一个可运行的JAR。 您也可以选择 build a classic WAR file |
|---|
您应该看到类似下面的输出,带有随机引用:
2015-09-23 14:22:26.415 INFO 23613 --- [main] hello.Application : Quote{type='success', value=Value{id=12, quote='@springboot with @springframework is pure productivity! Who said in #java one has to write double the code than in other langs? #newFavLib'}}
| ** |
如果您看到错误 Could not extract response: no suitable HttpMessageConverter found for response type [class hello.Quote]
“无法提取响应:没有找到适合响应类型[类hello.Quote]的HttpMessageConverter”,可能是在一个环境中无法连接到后端服务(如果可以到达它发送JSON)。 也许你是在使用其他网络代理? 尝试将标准系统属性 http.proxyHost
和 http.proxyPort
设置为适合您的环境的值。 |
|---|
恭喜! 你刚刚使用Spring开发了一个简单的REST客户端。
想要写一个新的指南或贡献现有的? 查看我们的 贡献指南 .
翻译自: https://spring.io/guides/gs/consuming-rest/