【发布时间】:2019-10-18 13:49:49
【问题描述】:
我在 Java 和 Spring Boot 领域还很陌生,所以一些显而易见的事情对我来说可能并不那么明显。我希望这个问题适合stackoverflow...
我有一个 Spring Boot 服务,它有一些开放的 REST API 控制器和一些与这些控制器交互的服务类。一些服务类调用外部 REST API。
我使用 RestTemplate 调用外部 REST api。
我的问题是:
为什么我必须创建一个 bean
//resttemplate so that we can autowire it inside services
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
// Do any additional configuration here
return builder.build();
}
然后在我的服务中
@Autowired
private RestTemplate restTemplate = new RestTemplate();
我也可以将它与自动装配一起使用,然后我就不必创建一个 bean...
没有创建 bean @autowired 对我来说失败了。
【问题讨论】:
-
答案就在问题中:为了能够自动装配 bean,必须定义 bean。所以,如果你不创建bean,由于Spring Boot没有提供默认的RestTemplate bean,你需要自己创建。如果你想知道为什么 Boot 不提供默认的 RestTemplate bean:docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…
-
包含
restTemplate()方法的类必须注解@Configuration
标签: java spring spring-boot