How to do Spring Lookup Method Injection with Annotations?

Alfredo Osorio picture Alfredo Osorio · Oct 8, 2010 · Viewed 17.8k times · Source

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?

Answer

Andrej Herich picture Andrej Herich · May 23, 2013

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
  }

}