簡體   English   中英

在 spring 啟動 java 應用程序中調用自定義 Rest 模板

[英]Calling Custom Rest Template in spring boot java application

我有一個在 2.1.7 版上運行的 spring 引導應用程序。 我正在嘗試使用 Rest 模板生成器來實現自定義 rest 模板,以設置連接和讀取超時。 我知道我需要使用 Rest 模板生成器,因為我在 2.1.7 上運行。 我的自定義 rest 模板的代碼如下所示。 我需要幫助在我的代碼的其他區域調用這個 rest 模板,因為這個 rest 模板將被我的應用程序的各個組件使用,但我需要幫助這樣做。 對此的任何建議將不勝感激。 謝謝!

public abstract class CustomRestTemplate implements RestTemplateCustomizer {

    public void customize(RestTemplate restTemplate, Integer connectTimeout, Integer readTimeout) {
        restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
        SimpleClientHttpRequestFactory template = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
        template.setConnectTimeout(connectTimeout);
        template.setReadTimeout(readTimeout);
    }
}

您不需要擴展定制器,那是矯枉過正。 最簡單和最干凈的方法是創建一個RestTemplate bean 並將其作為依賴項注入。

例如,您可以有一個配置並在那里聲明 bean:

@Configuration
public class WebConfig {

    private int fooConnectTimeout = 4000;
    private int fooReadTimeout = 4000;

    @Bean
    public RestTemplate restTemplate(final RestTemplateBuilder builder) {
        return builder.setConnectTimeout(fooConnectTimeout)
                .setReadTimeout(fooReadTimeout)
                .build();
    }
}

現在只需將 bean 注入 class 中,如下所示:

@Service
public class FooService {

    private RestTemplate restTemplate;

    public FooService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    // custom code here....
}

希望有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM