使用RestTemplate
RestTemplate是Spring Web模块提供的作为客户端按照Rest规范进行Http请求的工具。Spring Boot也提供了对它的自动配置,Spring Boot不是直接的配置好RestTemplate对象,而是由org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
配置类自动配置一个org.springframework.boot.web.client.RestTemplateBuilder
对象,需要使用RestTemplate时可以注入RestTemplateBuilder对象,通过其build方法可以构建一个RestTemplate对象。比如下面的代码中SomeService会被扫描为一个Spring bean,其构造函数需要一个RestTemplateBuilder对象,Spring将自动为其注入该对象,在构造函数中通过注入的RestTemplateBuilder对象创建了一个RestTemplate对象,并把它保存起来,之后就可以在其它地方使用了,比如getSomething()
。
@Component
public class