简体   繁体   English

在 spring 启动 java 应用程序中调用自定义 Rest 模板

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

I have a spring boot application that is running on version 2.1.7.我有一个在 2.1.7 版上运行的 spring 引导应用程序。 I am trying to implement a custom rest template using Rest Template Builder in order to set connection and read timeouts.我正在尝试使用 Rest 模板生成器来实现自定义 rest 模板,以设置连接和读取超时。 I've learned I need to use Rest Template Builder since I am running on 2.1.7.我知道我需要使用 Rest 模板生成器,因为我在 2.1.7 上运行。 The code for my custom rest template is shown below.我的自定义 rest 模板的代码如下所示。 I need assistance with calling this rest template in other areas of my code since this rest template is going to be utilized by various components of my application but I need help doing so.我需要帮助在我的代码的其他区域调用这个 rest 模板,因为这个 rest 模板将被我的应用程序的各个组件使用,但我需要帮助这样做。 Any advice on this would be greatly appreciated.对此的任何建议将不胜感激。 Thanks!谢谢!

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);
    }
}

You don't need to extend the customizer, that's an overkill.您不需要扩展定制器,那是矫枉过正。 The simplest and cleanest way to do it is to create a bean of RestTemplate and inject it as a dependency.最简单和最干净的方法是创建一个RestTemplate bean 并将其作为依赖项注入。

For example, you can have a config and declare the bean there:例如,您可以有一个配置并在那里声明 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();
    }
}

Now just inject the bean in the class, like so:现在只需将 bean 注入 class 中,如下所示:

@Service
public class FooService {

    private RestTemplate restTemplate;

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

    // custom code here....
}

Hope that helps希望有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM