gpt4 book ai didi

java - Spring Boot 错误 @Autowired RestTemplateBuilder 与 junit

转载 作者:行者123 更新时间:2023-11-30 05:34:19 26 4
gpt4 key购买 nike

尝试使用 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.

我编辑了其他有效的自动连线。我在这里缺少什么?在网上搜索后,我发现 spring 自动连接 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 的 AutoConfig 添加到您的 ContextConfiguration 中。第二种是创建一个 TestConfiguration 并创建您自己的 RestTemplateBuilder 或直接创建一个 RestTemplate。第三个是不要注入(inject) 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,则无法创建 RestTemplate,因为缺少 RestTemplateBuilder-Bean

关于java - Spring Boot 错误 @Autowired RestTemplateBuilder 与 junit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com