Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring lookup method injection with parameters

Tags:

spring

Is there a way to use Spring lookup method inject with parameters? For example, I want to be able to instantiate prototype-scoped beans while passing them arbitrary parameters via constructor.

like image 758
Fixpoint Avatar asked Dec 02 '10 17:12

Fixpoint


People also ask

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.

What problems can be 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 the use of @lookup annotation?

Why @Lookup? 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.

What is the use of lookup method in Java?

lookup(Class<?> cl) method finds the descriptor for a class that can be serialized. Creates an ObjectStreamClass instance if one does not exist yet for class. Null is returned if the specified class does not implement java.


2 Answers

It looks like this vital feature was finally added in Spring 4.1.0.RC2. I have tested it and it seems to work.

It was added as part of JIRA ticket SPR-7431 ("Passing lookup-method arguments to created bean constructor"):

<lookup-method/> should allow specifying any number of parameters. These parameters should be passed directly to the constructor of the newly created bean.

For more info on how the feature was finally added, this blog post was written by the guy who opened the JIRA ticket.

like image 75
Dan Ignat Avatar answered Oct 11 '22 12:10

Dan Ignat


You can inject them via field/setter injection. (Note that constructor injection is frowned upon by spring, although it's supported)

like image 33
Bozho Avatar answered Oct 11 '22 12:10

Bozho