以API“https://gturnquist-quoters.cfapps.io/api/random”为例,spring官网给的例子!
一、编写与其返回数据对应的类(pojo类)
package com.example.demo.pojo;
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.demo.pojo;
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 + '\'' +
'}';
}
}
这里的注解@JsonIgnoreProperties(ignoreUnknown = true)其存在的就是为了忽略类中不存在的字段。
二、启动类中编写实现方法
package com.example.demo;
import com.example.demo.pojo.Quote;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}//getLogget是一个静态方法,.class将这个类反射,便可知道其中的属性个方法
private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}//RestTemplate使用这个方法创建,但是它的范围仅限制于我们创建的类中。
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {//java一种编写方式
Quote quote = restTemplate.getForObject(//get请求方法
"https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());//使用日志和使用主控台打印感觉没差别
};
}
}
在这里,有几点说明:
1.我们是用日志进行api调用返回数据的打印(和System.out.println差别不大,效果一样)
2.使用注解@Bean,Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。
3.使用RestTemplate,RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
4.实现CommandLineRunner接口,CommandLineRunner是在容器启动成功后的最后一步回调.