尝试使用RestTemplateBuilder在Spring Boot 2.1.4中@Autowired RestTemplate。
当我运行junit测试时,尝试自动连接RestTemplate时出现错误。
我在这里看到:How to autowire RestTemplate using annotations
似乎RestTemplateBuilder更好,所以我想使用它。
这是配置文件:
@Configuration
public class Beans {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
这是测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = Beans.class)
public class AppTest extends TestCase {
@Autowired
private RestTemplate restTemplate;
}
错误是:
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method restTemplate in beanDeclerations.Beans required a bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' in your configuration.
我编辑了其他自动连线的工作。
我在这里想念什么?
在网上搜索后,我发现弹簧自动连接RestTemplateBuilder,为什么在这里不这样做?
编辑:
我最终使用了@RestClientTest(),并且现在不得不将RestTemplateBuilder Bean移至主类,稍后再将其移至其他位置。
谢谢您的帮助。
最佳答案
RestTemplateBuilder应该通过自动配置可用(请参阅:https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.java)。我认为此配置由于您的@ContextConfiguration而丢失。您有一些可能性。尝试将RestTemplateBuilder的自动配置添加到您的ContextConfiguration中。第二个是制作一个TestConfiguration并创建自己的RestTemplateBuilder或直接创建一个RestTemplate。第三个是不要注入RestTemplate-在测试中手动构建它。您也可以删除@ ContextConfiguration-Annotation,但这将导致测试加载您在项目中定义的每个配置。
还有一个用于测试的RestTestTemplate(https://www.baeldung.com/spring-boot-testresttemplate)。
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {TestConfig.class, RestTemplateAutoConfiguration.class})
public class SandboxApplicationTests {
@Autowired
RestTemplate restTemplate;
@Test
public void contextLoads() {
}
}
上面的代码段对我有用。如果没有ContextConfiguration中的RestTemplateAutoConfiguration,则由于缺少RestTemplateBuilder-Bean而无法创建RestTemplate