Now you need to add a few other things to the ConsumingRestApplication class to get it to show quotations from our RESTful source. You need to add:
A logger, to send output to the log (the console, in this example).
A RestTemplate, which uses the Jackson JSON processing library to process the incoming data.
A CommandLineRunner that runs the RestTemplate (and, consequently, fetches our quotation) on startup.
现在您需要向ConsumingRestApplication类添加一些其他东西,以使它显示来自RESTful源代码的引用。您需要添加:
一个记录器,将输出发送到日志(本例中为控制台)。
一个restemplate,它使用Jackson JSON处理库来处理传入的数据。
一个CommandLineRunner,在启动时运行restemplate(从而获取我们的报价)。
Fetching a REST Resource
With project setup complete, you can create a simple application that consumes a RESTful service.
A RESTful service has been stood up at https://gturnquist-quoters.cfapps.io/api/random. It randomly fetches quotations about Spring Boot and returns them as JSON documents.
If you request that URL through a web browser or curl, you receive a JSON document that looks something like this:
{
type: “success”,
value: {
id: 10,
quote: “Really loving Spring Boot, makes stand alone Spring apps easy.”
}
}
That is easy enough but not terribly useful when fetched through a browser or through curl.
A more useful way to consume a REST web service is programmatically. To help you with that task, Spring provides a convenient template class called RestTemplate. RestTemplate makes interacting with most RESTful services a one-line incantation. And it can even bind that data to custom domain types.
获取REST资源
项目设置完成后,您可以创建一个使用RESTful服务的简单应用程序。
已在https://gturnquist-quoters.cfapps.io/api/random。它随机获取关于springboot的引用并将它们作为JSON文档返回。
如果您通过web浏览器或curl请求该URL,则会收到一个JSON文档,该文档如下所示:
{
type:“成功”,
价值观:{
编号:10,
引语:“非常喜欢SpringBoot,让独立的Spring应用变得简单。”
}
}
这很简单,但当通过浏览器或curl获取时,并不是非常有用。
使用restweb服务的一种更有用的方法是以编程方式。为了帮助您完成这项任务,Spring提供了一个方便的模板类restemplate。restemplate使与大多数RESTful服务的交互成为一种简单的咒语。它甚至可以将这些数据绑定到自定义域类型。
package com.example.consumingrest;
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 ConsumingRestApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
@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());
};
}
}
package com.example.consumingrest;
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 +
'}';
}
}
package com.example.consumingrest;
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 + '\'' +
'}';
}
}
<?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>demo-RESTfulWebService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-RESTfulWebService</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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-04 17:23:36.980 INFO 1348 --- [ main] c.e.c.ConsumingRestApplication : Starting ConsumingRestApplication on PC-202008012041 with PID 1348 (G:\eclipse-workspace-Jee\demo-RESTfulWebService\target\classes started by Administrator in G:\eclipse-workspace-Jee\demo-RESTfulWebService)
2020-08-04 17:23:36.982 INFO 1348 --- [ main] c.e.c.ConsumingRestApplication : No active profile set, falling back to default profiles: default
2020-08-04 17:23:37.639 INFO 1348 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-04 17:23:37.647 INFO 1348 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-04 17:23:37.647 INFO 1348 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-04 17:23:37.648 INFO 1348 --- [ main] o.a.catalina.core.AprLifecycleListener : Loaded Apache Tomcat Native library [1.2.24] using APR version [1.7.0].
2020-08-04 17:23:37.648 INFO 1348 --- [ main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2020-08-04 17:23:37.649 INFO 1348 --- [ main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2020-08-04 17:23:37.653 INFO 1348 --- [ main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1g 21 Apr 2020]
2020-08-04 17:23:37.729 INFO 1348 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-04 17:23:37.730 INFO 1348 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 712 ms
2020-08-04 17:23:37.891 INFO 1348 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-04 17:23:38.020 INFO 1348 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-04 17:23:38.028 INFO 1348 --- [ main] c.e.c.ConsumingRestApplication : Started ConsumingRestApplication in 1.321 seconds (JVM running for 2.893)
2020-08-04 17:23:40.325 INFO 1348 --- [ main] c.e.c.ConsumingRestApplication : Quote{type='success', value=Value{id=3, quote='Spring has come quite a ways in addressing developer enjoyment and ease of use since the last time I built an application using it.'}}