没有org.springframework.web.client.RestOperations类型的限定bean可用

时间:2017-07-30 16:39:53

标签: java spring spring-boot

@Configuration课程中,RestTemplate的定义如下:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

@Autowired
private RestTemplate restTemplate;

在测试类中,使用注释声明如下RestOperations定义为:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {Application.class})
@ActiveProfiles("test")

@MockBean
private RestOperations restOperations;

这是错误陈述,

Unsatisfied dependency expressed through constructor parameter 0; nested exception is 
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying 
bean of type 'org.springframework.web.client.RestOperations' available: 
expected single matching bean but found 2: restTemplate,createRestTemplate

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

看起来你为RestTemplate定义了两个不同的bean,一个是" restTemplate"另一个是" createRestTemplate"。因此使用@Qualifier并提供相应的bean id。请参阅下文,

@Autowired @Qualifier("{bean_id}") private RestTemplate restTemplate;