https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-http-interface に書いてある通り。
ソースコードなど
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.2'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
以下は RestTemplate
の場合。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.support.RestTemplateAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import org.springframework.web.util.DefaultUriBuilderFactory;
@Configuration
public class Config {
@Bean
public BookApiClientService bookApiClientService(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory("http://localhost:8080/"));
RestTemplateAdapter adapter = RestTemplateAdapter.create(restTemplate);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
BookApiClientService service = factory.createClient(BookApiClientService.class);
return service;
}
}
6.1から新規追加された RestClient
を使用する場合。
@Bean
public BookApiClientService bookApiClientService(){
RestClient restClient = RestClient.builder().baseUrl("http://localhost:8080/").build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
BookApiClientService service = factory.createClient(BookApiClientService.class);
return service;
}
WebClient
もデフォルトで用意されているがここでは省略。
もしspringに対応するproxyクラスが無い場合、HttpExchangeAdapter
の実装クラスを自前で用意するのだと思われる。以下はJDK標準の HttpClient
を使用する場合のイメージ。とはいえ、探せば何かしらライブラリが公開されているとは思うがそこまでは調べていない。
public class Asadf implements HttpExchangeAdapter {
HttpClient client = ...