RESTful web services를 사용하는 서비스 만들기.
RESTful한 서비에스에서 응답받은 json형태를 곧바로 사용하기에는 불편함이 있음. 때문에 스프링의 RestTemplate 라이브러리를 이용해서 사용하기 편한 구조화된 객체 형태로 변환함.
build.gradle
plugins {
id 'org.springframework.boot' version '2.1.7.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-sta-brter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
응답을 받은 데이터를 저장할 객체
- @JsonIgnoreProperties(ignoreUnknown = true) 은 해당 타입에 없는 정보는 무시하기 위해 사용
- @JsonProperty 은 json데이터 중에서 객체 필드에 직접 맵핑하고 싶은 것이 있을 때 사용 (현 예제는 넘어오는 json 키이름이 필드와 일치해서 미사용)
Quote.java
@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 +
'}';
}
}
Value.java
@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 + '\'' +
'}';
}
}
SpringBoot 서비스를 구동
-
logger : 결과를 로그 창에 나타내기 위해 사용
-
RestTemplate : 호출한 데이터를 Jackson JSON 프로세스 라이브러리로 가공
-
CommandLineRunner : 어플리케이션 시작시 메소드를 구동
@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());
};
}
}
'공식메뉴얼 > spring.io' 카테고리의 다른 글
Building Java Projects with Maven (0) | 2020.11.15 |
---|---|
Building Java Projects with Gradle (0) | 2020.10.31 |
Scheduling Tasks (0) | 2020.09.06 |
Building a RESTful Web Service (0) | 2020.09.06 |