Spring Boot 错误 @Autowired RestTemplateBuilder 与 junit

Ace*_*e66 5 java spring autowired spring-boot

尝试使用 RestTemplateBuilder 在 Spring Boot 2.1.4 中 @Autowired RestTemplate。当我运行 junit 测试时,尝试自动连接 RestTemplate 时出现错误。

我在这里看到:如何使用注释自动装配 RestTemplate 似乎 RestTemplateBuilder 更好,所以我想使用它。

这是配置文件:

@Configuration
public class Beans {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = Beans.class)
public class AppTest extends TestCase {
    @Autowired
    private RestTemplate restTemplate;
}
Run Code Online (Sandbox Code Playgroud)

错误是:

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.
Run Code Online (Sandbox Code Playgroud)

我编辑了其他有效的自动连线。我在这里缺少什么?在网上搜索后,我发现 spring 自动连接 RestTemplateBuilder,为什么在这里不这样做呢?

编辑:我最终使用了 @RestClientTest() 并且必须暂时将 RestTemplateBuilder Bean 移动到主类,稍后我会将其移动到不同的位置。谢谢您的帮助。

Chr*_*3is 4

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。第三个是不要注入 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() {
    }

}
Run Code Online (Sandbox Code Playgroud)

上面的片段对我有用。如果 ContextConfiguration 中没有 RestTemplateAutoConfiguration,则无法创建 RestTemplate,因为缺少 RestTemplateBuilder-Bean


归档时间:

查看次数:

10168 次

最近记录:

4 年,2 月 前