I'm using constructor-based dependency injection to inject a javax.inject.Provider<T>
to a service. With Spring Framework (4.2.5), NoSuchBeanDefinitionException
will be thrown saying "No qualifying bean of type [T] found for dependency. Why is T
expected by Spring while injecting javax.inject.Provider<T>
?
Here's the sample code:
Provider:
import javax.inject.Provider;
public class MessageProvider implements Provider<String> {
@Override
public String get() {
return "Hello!";
}
}
Service:
import javax.inject.Inject;
import javax.inject.Provider;
public class GreetingService {
private final String message;
@Inject
GreetingService(Provider<String> provider) {
// GreetingService(MessageProvider provider) { // this works!
this.message = provider.get();
}
public String greeting() {
return message;
}
}
Test:
import org.junit.Test;
import static org.junit.Assert.*;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class GreetingServiceTest {
@Test
public void testSomeMethod() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MessageProvider.class);
ctx.register(GreetingService.class);
ctx.refresh();
GreetingService bean = ctx.getBean(GreetingService.class);
String message = bean.greeting();
assertNotNull(message);
}
}
And here's the error message:
Error creating bean with name 'greetingService': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [GreetingService]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}