Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Spring Lookup Method Injection with Annotations?

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?

like image 755
Alfredo Osorio Avatar asked Oct 08 '10 15:10

Alfredo Osorio


People also ask

What is lookup annotation in Spring?

A method annotated with @Lookup tells Spring to return an instance of the method's return type when we invoke it. Essentially, Spring will override our annotated method and use our method's return type and parameters as arguments to BeanFactory#getBean.

Which problem is solved using lookup method injection in Spring?

Why @Lookup Annotation in Spring. To put it in simple words, lookup method injection is the process to override a Spring bean at the runtime. The constructor and property are the most common used dependency injection methods. Both the options happen during the initialization of the Bean.

What is lookup method injection in Spring?

Spring lookup method injection is the process of dynamically overriding a registered bean method. The bean method should be annotated with @Lookup. Spring returns the lookup result matched by the method's return type.

Which annotation is used to inject?

Ordering of injection among fields and among methods in the same class is not specified. Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class.


2 Answers

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   }  } 
like image 165
Andrej Herich Avatar answered Oct 14 '22 22:10

Andrej Herich


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.

like image 34
Sami Andoni Avatar answered Oct 14 '22 23:10

Sami Andoni