java - org.springframework.web.client.RestTemplate 预计被声明为 @Bean 和普通 @Autowired 抛出错误

标签 java spring rest spring-boot spring-mvc

我的 @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,并且它工作正常。 我想了解

  1. 为什么objectmapper可以在没有bean的情况下工作,而resttemplate却不能 在没有 bean 的情况下工作并期望声明一个 bean?
  2. 何时创建 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/

相关文章:

java - 白标签错误页面此应用程序没有配置错误 View ,因此您将其视为后备

java - Spring boot security oauth2 从 cookie 中获取 access_token

node.js - 在使用 nodejs 和 express 制作的 REST API 中设置响应状态和 JSON 内容的正确方法

java - 缓存 REST 方法

Java 和 .NET : Base64 conversion confusion

java - 事件发生时要显示的JFrame?

java - 从 Java 访问 MS Dynamics CRM Online (2011) 时出现未声明的命名空间前缀 "wsx"错误

java - 使用 hibernate sessionFactory 或 JPA entityManager?

使用 ID token 的 REST API Firestore 身份验证

java - 为什么动画将对象从下到上移动而不是从上到下?