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

Alf*_*rio 30 spring dependency-injection spring-annotations

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

鉴于以下课程:

@Service
public abstract class A {


    protected abstract createB();

}
Run Code Online (Sandbox Code Playgroud)

为了使它工作,我必须在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>
Run Code Online (Sandbox Code Playgroud)

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

如何用注释做到这一点?

And*_*ich 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
  }

}
Run Code Online (Sandbox Code Playgroud)


小智 17

org.springframework.beans.factory.ObjectFactory如果您想跟上Spring API,也可以使用它

public class MySingleton {

  @Autowired
  private ObjectFactory<MyPrototype> myPrototypeFactory;

  public void operation() {
    MyPrototype instance = myPrototypeFactory.getObject();
    // do something with the instance
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以在文档中阅读更多内容.


Ben*_*lah 13

它仅在Spring> = 4.1时实现.查看票证.


Dan*_*Dan 10

最后介绍为 @Lookup注释.这是关于如何使用它的讨论.