【发布时间】:2019-09-27 10:46:28
【问题描述】:
我在@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 对象,我像下面这样自动连接它。
@Autowired
private ObjectMapper objectMapper;
我能够使用 objectmapper 而不为它声明任何 bean 并且它工作正常。 我想了解
- 为什么 objectmapper 可以在没有 bean 的情况下工作,而 resttemplate 不能 在没有 bean 的情况下工作并期望声明一个 bean?
- 何时创建 bean 以及何时简单地使用纯
@Autowired而无需 豆?怎么看才知道?
【问题讨论】:
标签: java spring rest spring-boot spring-mvc