I have this following configuration class where I generate all of my beans, everything worked perfectly until I needed a second instance of a same bean:
@Configuration
@EnableScheduling
@EnableConfigurationProperties({
ConfigA.class,
ConfigB.class,
ConfigC.class
})
public class ApplicationConfiguration {
@Bean("externalApiClient")
WebClient externalApiClient(ConfigA configA) {
WebClient webClient =
WebClient.builder()
.baseUrl(configA.getApiBaseUrl())
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
return webClient;
}
@Bean("selfApiClient")
WebClient selfApiClient(ConfigA configA) {
WebClient webClient =
WebClient.builder()
.baseUrl(configA.getBaseUrl())
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
return webClient;
}
}
And the following is my service which makes use of the two beans through constructor injection:
@Service
public class MyService {
private final WebClient selfApiClient;
private final WebClient externalApiClient;
public MyService(
@Qualifier("selfApiClient") WebClient selfApiClient,
@Qualifier("externalApiClient") WebClient externalApiClient) {
this.selfApiClient = selfApiClient;
this.externalApiClient = externalApiClient;
}
}
Which results in the following error, while everything worked before I needed the second instance:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘org.springframework.web.reactive.function.client.WebClient’ available: expected single matching bean but found 2: selfApiClient,externalApiClient
I also added this to my build.gradle after reading some posts about enabling the parameters flag of the java compiler:
compileJava {
options.compilerArgs += [
'-parameters'
]
}
I found out that there is another service I forgot about completely, MyService2
which also injected a WebClient webClient
in its constructor and didn’t specify a qualifier, which caused the error. For people who get confused about the same problem, be sure that there is no other class in your project which injects beans without qualifiers.