本指南将引导您完成创建使用RESTful Web服务的应用程序的过程。

你会建立什么

您将构建一个使用Spring的应用程序RestTemplatehttps://gturnquist-quoters.cfapps.io/api/random上检索随机的Spring Boot报价。

你需要什么

如何完成本指南

像大多数Spring 入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都可以使用工作代码。

从头开始 ,请继续使用Gradle构建

跳过基础知识 ,请执行以下操作:

完成后 ,您可以根据中的代码检查结果gs-consuming-rest/complete

用Gradle构建

用Gradle构建

首先,您设置一个基本的构建脚本。在使用Spring构建应用程序时,可以使用任何喜欢的构建系统,但是此处包含使用GradleMaven所需的代码。如果您都不熟悉,请参阅使用Gradle 构建Java项目使用Maven构建Java项目

创建目录结构

在您选择的项目目录中,创建以下子目录结构;例如, mkdir -p src/main/java/hello在* nix系统上:

└── src
    └── main
        └── java
            └── hello

创建一个Gradle构建文件

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.4.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    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插件提供了许多方便的功能:

  • 它收集类路径上的所有jar,并构建一个可运行的单个“über-jar”,这使执行和传输服务更加方便。

  • 它搜索public static void main()标记为可运行类的方法。

  • 它提供了一个内置的依赖项解析器,用于设置版本号以匹配Spring Boot依赖项 。您可以覆盖所需的任何版本,但是它将默认为Boot选择的一组版本。

用Maven构建

用Maven构建

首先,您设置一个基本的构建脚本。使用Spring构建应用程序时,可以使用任何喜欢的构建系统,但是此处包含了使用Maven所需的代码。如果您不熟悉Maven,请参阅使用Maven 构建Java项目

创建目录结构

在您选择的项目目录中,创建以下子目录结构;例如, mkdir -p src/main/java/hello在* nix系统上:

└── src
    └── main
        └── java
            └── hello

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>

    <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>2.1.4.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插件提供了许多方便的功能:

  • 它收集类路径上的所有jar,并构建一个可运行的单个“über-jar”,这使执行和传输服务更加方便。

  • 它搜索public static void main()标记为可运行类的方法。

  • 它提供了一个内置的依赖项解析器,用于设置版本号以匹配Spring Boot依赖项 。您可以覆盖所需的任何版本,但是它将默认为Boot选择的一组版本。

使用您的IDE进行构建

使用您的IDE进行构建

取得REST资源

完成项目设置后,您可以创建一个使用RESTful服务的简单应用程序。

RESTful服务已通过https://gturnquist-quoters.cfapps.io/api/random站起来。它随机获取有关Spring Boot的报价,并将其作为JSON文档返回。

如果您通过网络浏览器或curl请求该URL,您将收到一个类似于以下内容的JSON文档:

{
   type: "success",
   value: {
      id: 10,
      quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
   }
}

通过浏览器或curl获取时很容易,但并不是很有用。

使用REST Web服务的一种更有用的方法是以编程方式。为了帮助您完成该任务,Spring提供了一个方便的模板类,称为RestTemplateRestTemplate使与大多数RESTful服务的交互成为一线咒语。而且它甚至可以将该数据绑定到自定义域类型。

首先,创建一个域类以包含所需的数据。

src/main/java/hello/Quote.java

package hello;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {

    private String type;
    private Value value;

    public Quote() {
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Value getValue() {
        return value;
    }

    public void setValue(Value value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Quote{" +
                "type='" + type + '\'' +
                ", value=" + value +
                '}';
    }
}

如您所见,这是一个简单的Java类,具有一些属性和匹配的getter方法。带有注释@JsonIgnoreProperties从Jackson JSON处理库中获取,以指示应忽略此类型中未绑定的任何属性。

为了将数据直接绑定到自定义类型,您需要指定与API返回的JSON文档中的键完全相同的变量名。如果您的JSON文档中的变量名和键不匹配,则需要使用@JsonProperty注释以指定JSON文档的确切密钥。

需要一个附加的类来嵌入内部引号本身。

src/main/java/hello/Value.java

package hello;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {

    private Long id;
    private String quote;

    public Value() {
    }

    public Long getId() {
        return this.id;
    }

    public String getQuote() {
        return this.quote;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    @Override
    public String toString() {
        return "Value{" +
                "id=" + id +
                ", quote='" + quote + '\'' +
                '}';
    }
}

这使用相同的批注,但仅映射到其他数据字段。

使应用程序可执行

尽管可以将该服务打包为传统的WAR文件以部署到外部应用程序服务器,但是下面演示的更简单的方法创建了一个独立的应用程序。您将所有内容打包在一个可运行的JAR文件中,由一个好的旧Java驱动main()方法。在此过程中,您使用Spring的支持将Tomcat servlet容器作为HTTP运行时嵌入,而不是部署到外部实例。

现在您可以编写Application使用的类RestTemplate从我们的Spring Boot报价服务中获取数据。

src/main/java/hello/Application.java

package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;

public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
        RestTemplate restTemplate = new RestTemplate();
        Quote quote = restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
        log.info(quote.toString());
    }

}

由于Jackson JSON处理库位于类路径中, RestTemplate将使用它(通过消息转换器 )将传入的JSON数据转换为Quote宾语。从那里开始, Quote对象将被记录到控制台。

在这里你只用了RestTemplate制作一个HTTP GET请求。但RestTemplate还支持其他HTTP动词,例如POSTPUTDELETE

使用Spring Boot管理应用程序生命周期

到目前为止,我们还没有在应用程序中使用Spring Boot,但是这样做有一些好处,这并不难。优势之一是,我们可能希望让Spring Boot在服务器中管理消息转换器。 RestTemplate ,这样很容易以声明方式添加自定义项。为此,我们使用@SpringBootApplication像在任何Spring Boot应用程序中一样,在main类上转换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 class Application {

	private static final Logger log = LoggerFactory.getLogger(Application.class);

	public static void main(String args[]) {
		SpringApplication.run(Application.class);
	}

	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}

	@Bean
	public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
		return args -> {
			Quote quote = restTemplate.getForObject(
					"https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
			log.info(quote.toString());
		};
	}
}

RestTemplateBuilder是由Spring注入的,如果您使用它创建一个RestTemplate那么您将受益于Spring Boot中所有带有消息转换器和请求工厂的自动配置。我们还提取RestTemplate变成一个@Bean以使其更易于测试(可以更轻松地进行模拟)。

构建可执行的JAR

您可以使用Gradle或Maven从命令行运行该应用程序。或者,您可以构建一个包含所有必需的依赖项,类和资源的可执行JAR文件,然后运行该文件。这使得在整个开发生命周期中,跨不同环境等等的情况下,可以轻松地将服务作为应用程序进行发布,版本控制和部署。

如果您使用的是Gradle,则可以使用./gradlew bootRun 。或者您可以使用以下命令构建JAR文件./gradlew build 。然后,您可以运行JAR文件:

java -jar build/libs/gs-consuming-rest-0.1.0.jar

如果您使用的是Maven,则可以使用./mvnw spring-boot:run 。或者您可以使用以下命令构建JAR文件: ./mvnw clean package 。然后,您可以运行JAR文件:

java -jar target/gs-consuming-rest-0.1.0.jar
上面的过程将创建一个可运行的JAR。您也可以选择构建经典的WAR文件

您应该看到如下输出,并带有随机引号:

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]您可能处于无法连接到后端服务(如果可以访问JSON的情况下会发送JSON)的环境中。也许您在公司代理后面?尝试设置标准系统属性http.proxyHosthttp.proxyPort值适合您的环境。

摘要

恭喜你!您刚刚使用Spring开发了一个简单的REST客户端。