How to do Spring Lookup Method Injection with Anno

2019-01-21 19:09发布

Is there any way to use Lookup Method Injection using annotations?

Given the following class:

@Service
public abstract class A {


    protected abstract createB();

}

In order to get it to work I have to declare in spring applicationContext.xml the following:

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

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

Even though I am using <context:component-scan base> I have to declare it also in the XML. Not a good approach I think.

How to do it with annotations?

4条回答
女痞
2楼-- · 2019-01-21 19:45

It is possible to use javax.inject.Provider. All thanks go to Phil Webb.

public class MySingleton {

  @Autowired
  private Provider<MyPrototype> myPrototype;

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

}
查看更多
干净又极端
3楼-- · 2019-01-21 19:50

It is also possible with org.springframework.beans.factory.ObjectFactory if you want to keep up with Spring API

public class MySingleton {

  @Autowired
  private ObjectFactory<MyPrototype> myPrototypeFactory;

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

you can read more in the documentation.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-21 19:55

Finally introduced as @Lookup annotation. Here is discussion on how to use it.

查看更多
仙女界的扛把子
5楼-- · 2019-01-21 20:05

It is implemented only with Spring >= 4.1 See the ticket.

查看更多
登录 后发表回答