Spring Boot has built-in support for REST services, so it is common for one Spring Boot application to call another through REST endpoints. A typical way to do this is with RestTemplate. The basic workflow is simple: create a customized RestTemplate bean, inject it where needed, and use its request methods to call the target API.
Below is a practical example of how to configure and use RestTemplate, along with a brief look at the related Spring Boot auto-configuration.
Creating a RestTemplate instance
In most projects, a RestTemplate instance is usually customized before use. Spring Boot does not simply create a ready-to-use RestTemplate bean for every application by default, but it does provide an auto-configured RestTemplateBuilder, which can be used to build one.
The relevant auto-configuration code is in RestTemplateAutoConfiguration under spring-boot-autoconfigure. A simplified excerpt looks like this:
@Configuration(
proxyBeanMethods = false
)
@AutoConfigureAfter({HttpMessageConvertersAutoConfiguration.class})
@ConditionalOnClass({RestTemplate.class})
@Conditional({RestTemplateAutoConfiguration.NotReactiveWebApplicationCondition.class})
public class RestTemplateAutoConfiguration {
@Bean
@Lazy
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder(RestTemplateBuilderConfigurer restTemplateBuilderConfigurer) {
RestTemplateBuilder builder = new RestTemplateBuilder(new RestTemplateCustomizer[0]);
return restTemplateBuilderConfigurer.configure(builder);
}
// 省略其他代码
}
From this code, you can see that Spring Boot automatically creates a RestTemplateBuilder bean by default, and the bean name is restTemplateBuilder. Once it exists in the Spring container, it can be injected directly and used to construct a RestTemplate.
There are two common ways to configure this bean.
The first approach is to inject RestTemplateBuilder into a configuration class and call it when creating the RestTemplate bean:
@Configuration
public class RestTemplateConfig {
@Autowired
private RestTemplateBuilder restTemplateBuilder;
@Bean
public RestTemplate restTemplate() {
restTemplateBuilder.setConnectTimeout(Duration.ofSeconds(5));
restTemplateBuilder.setReadTimeout(Duration.ofSeconds(5));
return restTemplateBuilder.build();
}
}
This style is straightforward: inject the builder, set the required options, and call build() to obtain the final RestTemplate instance.
The second approach is a little more concise. Instead of defining a field, pass RestTemplateBuilder directly as a parameter of the bean method. When Spring Boot creates the RestTemplate bean, it will automatically resolve and inject the matching builder:
@Component
public class RestConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
builder.setConnectTimeout(Duration.ofSeconds(5));
builder.setReadTimeout(Duration.ofSeconds(5));
return builder.build();
}
}
Both examples set the connection timeout and read timeout to five seconds. In real projects, you can call other methods provided by RestTemplateBuilder depending on your needs, customizing the RestTemplate before finally invoking build().
After this initialization step, the RestTemplate bean can be injected and used anywhere else in the application.
Calling an endpoint with RestTemplate
The following example defines a REST endpoint in the same project and then calls it through RestTemplate. The full sample code is as follows:
@RestController
public class TestController {
@Resource
private RestTemplate restTemplate;
@GetMapping("/hello")
public String hello() {
return "Hello world!";
}
@GetMapping("/testHello")
public void testHello() {
String url = "http://127.0.0.1:8080/hello";
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
System.out.println(result.getBody());
}
}
Here, /hello is the service being called, while /testHello performs the actual call. After starting the project, visit /testHello; the console will print Hello world!, which means the request was successful.
RestTemplate also provides many other request methods, such as getForObject, execute, exchange, and patchForObject. These methods usually include multiple overloads, so you can choose the most suitable one based on the specific request scenario.
Notes on dependencies and usage
Using RestTemplate in a Spring Boot project does not require introducing additional dependencies beyond the basic web starter. In most cases, adding spring-boot-starter-web is enough.
The key is to configure the RestTemplate instance according to the actual business requirements, especially options such as timeout settings, and then choose the appropriate request method for each API call.