如何使用注释执行Spring Lookup方法注入?

时间:2010-10-08 15:25:32

标签: spring dependency-injection spring-annotations

有没有办法使用注释使用查找方法注入?

鉴于以下课程:

@Service
public abstract class A {


    protected abstract createB();

}

为了让它工作,我必须在spring applicationContext.xml中声明以下内容:

<bean id="b" class="com.xyz.B">
</bean>

<bean id="a" class="com.xyz.A">
    <lookup-method name="createB" bean="b"/>
</bean>

即使我使用<context:component-scan base>,我也必须在XML中声明它。我认为这不是一个好方法。

如何使用注释进行操作?

4 个答案:

答案 0 :(得分:28)

可以使用javax.inject.Provider。感谢Phil Webb

public class MySingleton {

  @Autowired
  private Provider<MyPrototype> myPrototype;

  public void operation() {
    MyPrototype instance = myPrototype.get();
    // do something with the instance
  }

}

答案 1 :(得分:17)

如果您想了解Spring API

,也可以使用org.springframework.beans.factory.ObjectFactory
public class MySingleton {

  @Autowired
  private ObjectFactory<MyPrototype> myPrototypeFactory;

  public void operation() {
    MyPrototype instance = myPrototypeFactory.getObject();
    // do something with the instance
  }
}

您可以在documentation中阅读更多内容。

答案 2 :(得分:13)

仅使用Spring&gt; = 4.1实现。请参阅ticket

答案 3 :(得分:10)

最后作为@Lookup注释引入。以下是关于如何使用它的discussion