SpringBoot 官方文档示例(83):自定义RestTemplateBuilder

package cn.edu.tju.config;
import java.time.Duration;
import
        org.springframework.boot.autoconfigure.web.client.RestTemplateBuilderConfigurer;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyRestTemplateBuilderConfiguration {
    @Bean
    public RestTemplateBuilder restTemplateBuilder(RestTemplateBuilderConfigurer
                                                           configurer) {

        return configurer.configure(new
                RestTemplateBuilder()).setConnectTimeout(Duration.ofSeconds(5))
                .setReadTimeout(Duration.ofSeconds(2));
    }
}

package cn.edu.tju.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {
    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    @RequestMapping("/hi")
    public String getInfo(){
        String forObject = restTemplateBuilder.build().getForObject("http://www.baidu.com", String.class);
        return forObject;
    }
}

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)