简体   繁体   中英

Calling Custom Rest Template in spring boot java application

I have a spring boot application that is running on version 2.1.7. I am trying to implement a custom rest template using Rest Template Builder in order to set connection and read timeouts. I've learned I need to use Rest Template Builder since I am running on 2.1.7. The code for my custom rest template is shown below. 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. 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.

For example, you can have a config and declare the bean there:

@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:

@Service
public class FooService {

    private RestTemplate restTemplate;

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

    // custom code here....
}

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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