【Spring MVC】RestTemplateの導入

概要

RESTfulなAPIを呼ぶクライアントライブラリである、RestTemplateの概要についてまとめた。
RestTemplateを使用するための準備と、どんなメソッドがあるのかを紹介している。

 

前提

今後動作確認を行う際には、以前の記事で作成したREST APIアプリにリクエストを行ってレスポンスを取得する。

あわせて読みたい

概要 これから数回にかけてREST APIについて学んだことを載せていく。 今回はREST APIの仕組みとプロジェクト作成方法について紹介する。 尚、RESTとは何かということについては取り扱わない。   仕組み[…]

 

RestTemplate

RestTemplateはHTTPリクエストを送信できる。
また、メッセージコンバーターを内包しているため、JSONやXMLなどのレスポンスを適切なオブジェクトにマッピングできる。

 

主なメソッド

RestTemplateには、HTTP メソッドごとに様々な API が用意されている。

 

メソッド 説明
getForObject GET リクエストを送信し、レスポンスをオブジェクトとして取得
getForEntity GET リクエストを送信し、ResponseEntity を取得
postForObject POST リクエストを送信し、レスポンスをオブジェクトとして取得
postForEntity POST リクエストを送信し、ResponseEntity を取得
put PUT リクエストを送信
delete DELETE リクエストを送信
exchange 任意の HTTP メソッドでリクエストを送信し、ResponseEntity を取得

 

 

事前準備

今後数回にわたって、RestTemplateのメソッドの基本的な使用方法について紹介する。
RestTemplateを使用するための事前準備を行う。

 

必要ライブラリ

RestTemplateを使用するためには、spring-webライブラリをpom.xmlに追加する必要がある。
※spring-webmvcにspring-webも含まれるため、以下でも可能

 

pom.xml


<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.1.20.RELEASE</version>
</dependency>

 

Bean定義

RestTemplateをDIするためには、Bean定義が必要となる。

 

applicationContext.xml


<!-- RestTemplate の Bean 定義 -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

 

APIアクセスクラス

RestTemplateのDIを行い、APIにアクセスするメソッドを今後追加していく。

 

RestClient.java


package com.example.client_prototype.biz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RestClient {

	@Autowired
	private RestTemplate restTemplate;
	
}

 

リソースクラス

REST APIアプリから返却されるレスポンスを、リソースクラスにマッピングするため用意する。

 

Resource.java


package com.example.rest_client_prototype.resources;

import java.time.LocalDate;

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Resource {
	/** ID */
	private String id;
	/** 名前 */
	private String name;
	/** とある日付 */
	@JsonFormat(pattern = "yyyy-MM-dd")
	private LocalDate hogeDate;
}

 

動作確認用クラス

RestTemplateの動作を簡易的に確認するため、エントリーポイントとなるクラスを用意する。

 

Main.java


package com.example.client_prototype.executor;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.client_prototype.biz.RestClient;

public class Main {

	public static void main(String[] args) {
		try (var context = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml")) {
			// DIコンテナから取得
			var restClient = context.getBean(RestClient.class);
			
		}
	}
}

 

var restClient = context.getBean(RestClient.class);

上記はDIコンテナからRestClientのインスタンスを取得している。
このエントリーポイントからRestClientで定義したメソッドを呼び出す。

 

まとめ

 

☑ RestTemplateを利用することで、HTTPリクエストを送信可能

☑ RestTemplateを使用するには、spring-webライブラリを導入する

☑ メッセージコンバーターを内包しており、JSONやXMLなどのレスポンスを適切なオブジェクトにマッピングできる

スポンサーリンク