Reputation: 53916
I'm trying to inject a property everytime a bean (myBean) is called using a lookup method and Spring dependency injection :
<bean id="myBean" class="com.myclass"
<property name="default" ref="myDefault" >
<lookup-method name="getUri" bean="defaultUri" />
</property>
</bean>
<bean id="defaultUri" scope="prototype" class="DefaultUri" >
</bean>
class myclass {
public String getUri(){
return "test"
}
}
Above XML returns this error on startup :
"XML document from PortletContext resource is invalied"
The error seems to be because <lookup-method name="getUri" bean="defaultUri" />
is configured incorrectly.
How can I configure a Spring lookup method within a String 'property' as I'm trying to implement in above XML ?
Upvotes: 6
Views: 23292
Reputation: 196
Suppose singleton bean A needs to use non-singleton (prototype) bean B, perhaps on each method invocation on A(getBeanB()), we expect to get new instance of bean B for every request. But The container only creates the singleton bean A once, and thus only gets one opportunity to set the properties. The container cannot provide bean A with a new instance of bean B every time one is needed. To get new new instance of bean B for every request we need to use lookup-method injection
Please refer to http://www.javapointer.com/spring/spring-core/spring-lookup-method-injection/
Upvotes: 2
Reputation: 10632
Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container.
Now, suppose you want to get a new instance of DefaultUri
(which is a prototype bean) every time you call a method (let it be createDefaultUri
) in myclass
(which is a singleton bean). Then you can define MyClass
as this:
class abstract Myclass {
public String getUri(){
// create a new instance of DefaultUri
DefaultUri defaultUri = createDefaultUri();
return "test"
}
protected abstract DefaultUri createDefaultUri();
}
The Spring Framework will generate a dynamic subclass of Myclass
that will override the createDefaultUri
method to provide a new instance of DefaultUri
every time it is requested for.
You can now define the name of lookup-method
name in the Myclass
bean definition as this:
<bean id="defaultUri" scope="prototype" class="DefaultUri">
</bean>
<bean id="myBean" class="com.myclass"
<lookup-method name="createDefaultUri" bean="defaultUri" />
</bean>
Upvotes: 11