使用javax.inject.Provider代替<lookup-method> </lookup-method>

时间:2013-10-30 09:28:27

标签: java spring spring-annotations

我试图了解如何使用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类型。

1 个答案:

答案 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());
        }
    }