我试图了解如何使用javax.inject.Provider
代替Spring <lookup-method>
。这是我的代码
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();
}
}
但是当我运行此代码时,我遇到了异常
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
我知道,我对Provider
的理解不对,但我的问题是,我是否需要提供
@Autowired
private Provider<Target> targetBean;
在每个实施课程中,还是我做错了什么? 我假设因为我将对象类型传递给Abstract类,Provider将能够找到所请求的bean类型。
答案 0 :(得分:1)
@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());
}
}