我在Spring启动应用程序中使用带有@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。当我尝试使用@ContextConfiguration
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>()
答案 0 :(得分:1)
我通过使用@SpringBootTest
并将RestTemplateAutoConfiguration.class
添加到类数组来解决了这个问题:
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { RestTemplateAutoConfiguration.class })
public class MyTest {
// test methods
}
答案 1 :(得分: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>()