1

我想看看我如何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;

在每个实现类中还是我做错了什么?我假设由于我将对象类型传递给抽象类,提供者将能够找到正在请求的 bean 类型。

4

1 回答 1

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());
        }
    }
于 2013-11-12T10:12:12.167 回答