7

我在 Spring Boot 应用程序中使用带有 @ContextConfiguration 的 RestTemplateBuilder 时遇到了问题(我尝试添加 @SpringBootTest、@RunWith(SpringRunner.class) 注释但没有任何运气)。

任何帮助表示赞赏。这是背景:

我对我的班级进行了如下注释:

@ContextConfiguration(classes = {
    JsonNodeList.class,
    JsonNodeUtils.class,
    MyService.class,
    RestClient.class,
    RestTemplateBuilder.class}, loader = SpringBootContextLoader.class)
 public class StepsDefinition {

RestClient 类将 RestTemplateBuilder 自动装配为:

 @Autowired
  public RestClient(final RestTemplateBuilder restTemplateBuilder) {
    this.restTemplate = configureRestTemplate(restTemplateBuilder);
  }

MyService 类自动装配 RestClient。当我尝试使用@ContextConfigurationwith加载应用程序SpringBootContextLoader时,出现以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplateBuilder': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.client.RestTemplateBuilder]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.boot.web.client.RestTemplateBuilder.<init>()
4

2 回答 2

6

我通过使用@SpringBootTest并添加RestTemplateAutoConfiguration.class到 classes 数组解决了这个问题:

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { RestTemplateAutoConfiguration.class })
public class MyTest {
   // test methods
}
于 2019-11-13T14:25:56.487 回答
0

尝试运行单元测试时,我遇到了同样的问题。以下是对我有用的注释:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { RestTemplate.class })
@DataJpaTest
@AutoConfigurationPackage
public class MyTest {
   // test methods
}

当我在注释中RestTemplateBuilder.class指定时:@SpringBootTest

@SpringBootTest(classes = { RestTemplate.class, RestTemplateBuilder.class })

我得到了同样的例外:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplateBuilder': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.client.RestTemplateBuilder]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.boot.web.client.RestTemplateBuilder.<init>()
于 2018-11-07T16:57:22.343 回答