[英]calling method with Rest Template Builder
我使用 rest 模板生成器創建了這個 rest 模板,並設置了連接和讀取超時。 我需要從程序中的其他方法調用此 rest 模板,但不確定如何調用。 請幫助,在此先感謝!
//create rest template with rest template builder and set connection and read timeouts @Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(Duration.ofMillis(connectTimeout))
.setReadTimeout(Duration.ofMillis(readTimeout))
.build();
}
// this is an example method that calls rest template, unsure what goes in the parameter section
@Bean
public example example() {
return new restTemplate(what goes here)
);
}
RestTemplateBuilder
是 Spring boot 提供的一個 bean。 您可以將其注入到任何 Spring bean 類中。
然后,您只想在創建 Spring bean class 時配置您的restTemplate
並將其存儲為一個字段。 您可以執行以下操作(這不是唯一的方法)。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
@Configuration
public class MyExampleRestClientConfiguration {
private final RestTemplateBuilder restTemplateBuilder;
@Autowired
public MyExampleRestClient(RestTemplateBuilder restTemplateBuilder) {
this.restTemplateBuilder = restTemplateBuilder;
}
@Bean
public RestTemplate restTemplate() {
return restTemplateBuilder
.setConnectTimeout(Duration.ofMillis(connectTimeout))
.setReadTimeout(Duration.ofMillis(readTimeout))
.build();
}
}
現在在其他一些 spring bean class 中,您可以簡單地連接restTemplate
bean 並重新使用。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class MyExampleRestClient {
private final RestTemplate restTemplate;
@Autowired
public MyExampleRestClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
//Now You can call restTemplate in any method
}
你可以參考這個了解更多。
如果您已經創建了自定義的 RestTemplate,您可以將它自動連接到您想要調用它的任何 class 並使用它。 如果您有超過 1 個 RestTemplates,您可以在 RestTemplate Bean 上方使用 @Qualifier 並在調用 class 中使用相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.