Reputation: 23587
I am trying to see how i can use javax.inject.Provider
in place of Spring <lookup-method>
. here is my code
public abstract class MyAbstractClass<Source,Target>{
@Autowired
private Provider<Target> targetBean;
protected abstract Target createTarget();
public Provider<Target> getTargetBean() {
return this.targetBean;
}
}
public class MyClass extends MyAbstractClass<ObjectA, ObjectB>{
@Override
protected ObjectB createTarget()
{
return this.targetBean.get();
}
}
But when i am running this code, i am getting following exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [java.lang.Object] is defined: expected single matching bean but found // list of all beans
I know, my understanding of Provider
is not right, but my question is, do i need to provide
@Autowired
private Provider<Target> targetBean;
In each implementation class or is there something i am doing totally wrong? I was assuming that since i am passing type of object to Abstract class, Provider will able to find type of bean which is being requested.
Upvotes: 1
Views: 1031
Reputation: 3667
@Component
@Scope("prototype")
public class Prototype
{
}
@Component
public class Singleton
{
@Autowired
Provider<Prototype> prototype;
public Prototype createPrototype()
{
return this.prototype.get();
}
}
@Configuration
@ComponentScan
public class Factory
{
// The ComponentScan does the job
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { Factory.class })
public class SingletonPrototypeTest
{
@Autowired
Singleton singleton;
@Test
public void testFoo()
{
Assert.assertTrue(this.singleton.createPrototype() != this.singleton.createPrototype());
}
}
Upvotes: 1