有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java组织。springframework。网状物客户RestTemplate应声明为@Bean,而plain@Autowired抛出错误

在我的@RestController类“personController”中需要一个RestTemplate对象,所以我像下面那样声明它

@Autowired
 private RestTemplate restTemplate;

当我尝试使用它时,我得到了下面的错误 com中的字段restTemplate。实例演示。应用程序编程接口。PersonController需要找不到类型为org.springframework.web.client.RestTemplate的bean。 考虑在配置中定义一个类型为{{CD2}}的bean。

为了克服这个错误,我在一个配置中声明了一个@Bean用于重新模板,如下所示。java文件及其工作正常,不会抛出任何错误

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    return restTemplate;
}

我在@Service类“personService”中使用了一个com.fasterxml.jackson.databind.ObjectMapper对象,我如下所示自动连接了它

@Autowired
private ObjectMapper objectMapper;

我可以使用objectmapper,而无需为它声明任何bean,而且工作正常。 我想了解

  1. 为什么objectmapper在没有bean的情况下工作,而resttemplate没有 在没有bean的情况下工作并希望声明bean
  2. 什么时候创建bean,什么时候不使用 豆我怎么能通过看它来发现呢

共 (5) 个答案

  1. # 1 楼答案

    ObjectMapperbean是由Spring Boot创建的,因为类路径中存在ObjectMapper类,这会触发JacksonAutoConfiguration。这就是为什么您可以自动连接这个bean,而无需显式地创建它

    RestTemplate另一方面,这是一个必须自己创建的bean——Spring不会为您这样做,因为没有自动配置类可以触发它的创建

  2. # 2 楼答案

    正如春季文档中提到的那样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.

  3. # 3 楼答案

    最有可能的是ObjectMapper是通过项目的一个交叉或可传递依赖项进入上下文的,但RestTemplate不是。所以ObjectMapper的实例是隐式创建的,而RestTemplate根本没有创建。所以这就是为什么必须显式地创建RestTemplate的bean

  4. # 4 楼答案

    ObjectMapper之所以有效,是因为还有其他第三方(即Jackson)代码使用该bean(由他们配置)。你只是在利用它,把它自动连接到你自己的bean上

    另一方面,RestTemplate不是由第三方在您的代码库中作为bean提供的(它可能通过依赖关系提供)。所以,如果你想的话,你可以创建一个bean

    除非你知道,否则你不能假设任何东西都是bean,所以文档是你首先要看的地方

  5. # 5 楼答案

    正如其他用户所说,这是正确的,spring没有为RestTemplate定义默认bean。首选的方法是使用org。springframework。靴子网状物客户用于构建rest模板的RestTemplateBuilder

    下面给出一个例子

    @Service
    public class RestServiceCaller {
    
      private RestTemplate restTemplate;
    
      @Autowired
      RestServiceCaller(RestTemplateBuilder builder) {
         restTemplate = builder.build();
      }
    
     ........
     .....//here you will have other methods which make use of this restTemplate
    }
    

    来自restTemplateBuilder的JavaDoc->; “在一个典型的自动配置的Spring Boot应用程序中,这个生成器可以作为bean提供,并且可以在需要RestTemplate时注入。”