程序结构
└── 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将会你做如下的事:
- 将 classpath 里面所有用到的jar包构建成一个可执行的 JAR 文件,方便执行和传输你的服务
- 搜索public static void main()方法并且将它当作可执行类
- 根据springboot版本,去查找相应的依赖类版本,当然你可以定义其它版本。
获取一个REST资源
完成项目设置后,您可以创建一个使用RESTful服务的简单应用程序。
https://gturnquist-quoters.cfapps.io/api/random
是一个RESTful服务。它随机获取关于SpringBoot的称赞名言,并将其作为JSON文档返回。
如果您通过Web浏览器或curl请求该URL,您将收到一个类似以下内容的JSON文档:
{"type":"success","value":{"id":7,"quote":"The real benefit of Boot, however, is that it's just Spring. That means any direction the code takes, regardless of complexity, I know it's a safe bet."}}
使用RESTWeb服务的一个更有用的方法是通过编程。为了帮助您完成这项任务,Spring提供了一个称为 RestTemplate的方便模板类。
首先,创建一个包含所需数据的域类:
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 +
'}';
}
}
上面使用Jackson JSON处理库中的@JsonIgnoreProperties进行了注解,以表明任何未绑定在此类型中的属性都应被忽略。
为了直接将数据绑定到自定义类型,需要指定与从API返回的JSON文档中的键完全相同的变量名。如果JSON文档中的变量名和键不匹配,则需要使用@JsonIgnoreProperties 注解来指定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文件,放到外部的WEB容器中;另一种是生成可执行jar文件,这需要有一个类中有main()方法:
写一个使用RestTemplate的Application类,并从这个类运行程序:
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动作,如 POST, PUT和DELETE。
管理应用程序生命周期
到目前为止,我们的应用程序中还没有使用Springboot。使用Springboot的一个优点是,让Springboot管理RestTemplate中的消息转换,我们可以在主类上使用@SpringBootApplication,并在转换主方法来启动它,
就像在任何SpringBoot应用程序中一样。最后,我们将RestTemplate移动到CommandLineRunner回调,以便在启动时由Springboot执行:
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,那么您将受益于Springboot中自动配置的消息转换器和请求工厂。我们还将RestTemplate提取到@Bean中,以便于测试(这样更容易模拟)。
运行你的程序(STS下,Maven可参考前面文章):右键-选择Run as-Spring Boot App ,输出如下:
2019-06-26 23:03:23.241 INFO 10288 --- [ main] c.example.demo.RestTemplateApplication : Quote{type='success', value=Value{id=2, quote='With Boot you deploy everywhere you can find a JVM basically.'}}
如果你看到如下的错:
no suitable HttpMessageConverter found for response type [class hello.Quote]
有可能您所处的环境无法连接到后端服务(如果可以连接到该服务,则发送JSON)。也许你的公司是在代理服务器后,请尝试设置正确http.proxyhost和http.proxyport系统属性。
更多的例子在这里
http://www.itmanclub.com/blog/article/647