繁体   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