简体   繁体   中英

calling method with Rest Template Builder

I created this rest template with the rest template builder and set connection and read timeouts. I need to call this rest template from other methods in the program, but am unsure how to do so. please help, thanks in advance!

//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 is a bean provided by Spring boot. You can inject that into any of your Spring bean classes.

Then you just want to configure your restTemplate at the creation of your Spring bean class and store it as a field. You can do something like below (This is not the one and only way).

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

Now in Some other spring bean class, you can simply wire the restTemplate bean and re-use.

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
}

You may refer this for more.

if you have created your customised RestTemplate, you may autowire it any class where you want to call it and use the one. if you more than 1 RestTemplates you can use @Qualifier above RestTemplate Bean and use the same in the calling class.

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