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,而且工作正常。 我想了解
- 为什么objectmapper在没有bean的情况下工作,而resttemplate没有 在没有bean的情况下工作并希望声明bean李>
- 什么时候创建bean,什么时候不使用 豆我怎么能通过看它来发现呢李>
# 1 楼答案
ObjectMapper
bean是由Spring Boot创建的,因为类路径中存在ObjectMapper
类,这会触发JacksonAutoConfiguration
。这就是为什么您可以自动连接这个bean,而无需显式地创建它RestTemplate
另一方面,这是一个必须自己创建的bean——Spring不会为您这样做,因为没有自动配置类可以触发它的创建# 2 楼答案
正如春季文档中提到的那样https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-resttemplate.html
# 3 楼答案
最有可能的是
ObjectMapper
是通过项目的一个交叉或可传递依赖项进入上下文的,但RestTemplate
不是。所以ObjectMapper
的实例是隐式创建的,而RestTemplate
根本没有创建。所以这就是为什么必须显式地创建RestTemplate
的bean# 4 楼答案
ObjectMapper
之所以有效,是因为还有其他第三方(即Jackson)代码使用该bean(由他们配置)。你只是在利用它,把它自动连接到你自己的bean上另一方面,
RestTemplate
不是由第三方在您的代码库中作为bean提供的(它可能通过依赖关系提供)。所以,如果你想的话,你可以创建一个bean除非你知道,否则你不能假设任何东西都是bean,所以文档是你首先要看的地方
# 5 楼答案
正如其他用户所说,这是正确的,spring没有为RestTemplate定义默认bean。首选的方法是使用org。springframework。靴子网状物客户用于构建rest模板的RestTemplateBuilder
下面给出一个例子
来自restTemplateBuilder的JavaDoc->; “在一个典型的自动配置的Spring Boot应用程序中,这个生成器可以作为bean提供,并且可以在需要RestTemplate时注入。”