How to do Spring Lookup Method Injection with Annotations?
Asked Answered
L

4

30

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?

Lancinate answered 8/10, 2010 at 15:25 Comment(0)
P
29

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
  }

}
Polyhydroxy answered 23/5, 2013 at 13:15 Comment(1)
Please also note the answer about @Lookup below - it's possible with Spring 4.1 ot later to use the annotation. Even though I think the Provider is much cleaner and less confusing while reading the code.Socinus
M
17

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.

Matthaus answered 4/9, 2013 at 0:6 Comment(0)
T
13

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

Tecu answered 5/1, 2011 at 15:28 Comment(2)
In Spring Framework 4.1 it is available as the \@Lookup annotation. See @Danny-Dan's answer.Preterit
Thanks, udpated my answer accordinglyTecu
G
10

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

Grantinaid answered 18/11, 2014 at 10:9 Comment(1)
The @Lookup annotation requires Spring 4.1 or laterPreterit

© 2022 - 2024 — McMap. All rights reserved.