Springの公式サイト、Getting Started での記述に倣って、RESTful Web Service を使用する機能を作成します。
https://spring.io/guides/gs/rest-service/
公式サイトにあるように、今回は以下のサービスにアクセスしてJSON形式のパラメータを取得します。
https://gturnquist-quoters.cfapps.io/api/random
アクセスすればわかるように、下記の様に入れ子構造になっているJSONメッセージを取得できます。
{
"type": "success",
"value": {
"id": 11,
"quote": "I have two hours today to build an app from scratch. @springboot to the rescue!"
}
}
パッケージのダウンロード
Spring Initializrにアクセスし、”Artifact” 欄を “consuming-rest” とし、”Dependencies” に “Spring Web”を追加したうえで、Generateボタンでダウンロードします。
(Artifactはデフォルトの”demo”のままでも、各クラスのパッケージを適切に変更すれば動きます)

落としたzipは解凍して、Cドライブ直下に配置。

ドメインクラスの作成
JSONパラメータを格納するためのドメインクラスを作成します。
今回使用するJSONはこのように入れ子構造になっているので、2階層に分けてクラスを作成します。
{
"type": "success",
"value": {
"id": 11,
"quote": "I have two hours today to build an app from scratch. @springboot to the rescue!"
}
}
“type”, “value” を格納するQuoteクラスと、”value”の下にある “id”, “quote”を格納するValueクラスです。
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 + '\'' +
'}';
}
}
両方とも、@JsonIgnorePropertiesというアノテーションが使われています。
これは「JSON側に存在するが、それを扱うクラスには存在しない」パラメータがある場合、そのパラメータを無視する働きをします。
SpringBootApplicationクラスの編集
Spring Initializrに既に存在する ConsumingRestApplication クラスを、次のように編集します。
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());
};
}
}
RestTemplate はJSONを処理するライブラリであるjacksonを使用し、データを読み込みます。
CommanLineRunner は RestTemplate によって対象URLからJSONパラメータを取得し、スタートアップ画面に結果を表示します。
実行結果
コマンドプロンプトで実行してみます。
mvnw spring-boot:run
すると、スタートアップ画面に、JSONの取得結果が確認できました。
c:\consuming-rest>mvnw spring-boot:run
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< com.example:consuming-rest >---------------------
[INFO] Building consuming-rest 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.2.4.RELEASE:run (default-cli) > test-compile @ consuming-rest >>>
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ consuming-rest ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ consuming-rest ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ consuming-rest ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory c:\consuming-rest\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ consuming-rest ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:2.2.4.RELEASE:run (default-cli) < test-compile @ consuming-rest <<<
[INFO]
[INFO]
[INFO] --- spring-boot-maven-plugin:2.2.4.RELEASE:run (default-cli) @ consuming-rest ---
[INFO] Attaching agents: []
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.4.RELEASE)
2020-02-15 05:10:18.194 INFO 11504 --- [ main] c.e.c.ConsumingRestApplication : Starting ConsumingRestApplication on MyComputer with PID 11504 (C:\consuming-rest\target\classes started by in c:\consuming-rest)
2020-02-15 05:10:18.197 INFO 11504 --- [ main] c.e.c.ConsumingRestApplication : No active profile set, falling back to default profiles: default
2020-02-15 05:10:20.017 INFO 11504 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-02-15 05:10:20.067 INFO 11504 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-02-15 05:10:20.069 INFO 11504 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-02-15 05:10:20.722 INFO 11504 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-02-15 05:10:20.723 INFO 11504 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2489 ms
2020-02-15 05:10:21.193 INFO 11504 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-02-15 05:10:21.451 INFO 11504 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-02-15 05:12:15.269 INFO 11504 --- [ main] c.e.c.ConsumingRestApplication : Started ConsumingRestApplication in 117.609 seconds (JVM running for 118.886)
2020-02-15 05:12:17.254 INFO 11504 --- [ 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.'}}
