我的 @RestController
类“personController”中需要一个 RestTemplate 对象,所以我如下声明它。
@Autowired
private RestTemplate restTemplate;
当我尝试使用它时,出现以下错误
com.example.demo.api.PersonController 中的字段restTemplate 需要一个org.springframework.web.client.RestTemplate
类型的bean,但无法找到。
考虑在配置中定义 org.springframework.web.client.RestTemplate
类型的 bean。
为了克服这个错误,我在 config.java 文件中为 restemplate 声明了一个 @Bean
,如下所示,它工作正常并且不会抛出任何错误。
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
我在 @Service
类“personService”中使用 com.fasterxml.jackson.databind.ObjectMapper
对象,并像下面一样 Autowiring 它。
@Autowired
private ObjectMapper objectMapper;
我能够使用对象映射器,而无需为其声明任何 bean,并且它工作正常。 我想了解
- 为什么objectmapper可以在没有bean的情况下工作,而resttemplate却不能 在没有 bean 的情况下工作并期望声明一个 bean?
- 何时创建 bean 以及何时简单地使用普通的
@Autowired
而无需 bean 角,扁 bean ?我怎样才能通过查看找到答案?
最佳答案
正如 Spring 文档中提到的那样。 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-resttemplate.html
If you need to call remote REST services from your application, you can use the Spring Framework’s RestTemplate class. Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder, which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder ensures that sensible HttpMessageConverters are applied to RestTemplate instances.
关于java - org.springframework.web.client.RestTemplate 预计被声明为 @Bean 和普通 @Autowired 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58132983/