Saturday 19 March 2011

Spring : Lookup Method injection

In a Spring application, when a singleton bean uses another singleton bean, or a non-singleton bean uses another non-singleton bean, setting one bean as a property of the other is quite adequate. But when the two beans are not of the same Scope i.e. When a singleton bean has to use a non-singleton (prototype) bean, the container will create the singleton bean just once, and the prototype bean that it depends on will also be set only once. The container cannot provide the Singleton bean with a new instance of the prototype bean each time it is needed.
Example: There are 2 beans BeanA and BeanB. Now BeanA depends on BeanB. BeanA requires a new fresh instance of BeanB whenever any method of BeanA is called.
Suppose BeanA is NewsFeedManager and BeanB is NewsFeed.
//This is a singleton bean depending upon a non singleton bean
public abstract class NewsFeedManager {

public abstract NewsFeed getNewsFeed();

public void printNews() {
NewsFeed newsFeed = getNewsFeed();
System.out.println(newsFeed.getNews());
}
}


//We are assuming this bean cannot be singleton in nature
public class NewsFeed {

public String getNews() {
return "Java with Spring has broken all the box office records!";
}
}


Now in this case look-up method injection will work like this:

<bean id="newsFeed" class="com.spring.lookup.NewsFeed" scope="prototype" />

<!-- use lookup method to refer non-singleton bean-->
<bean id="newsFeedManager" class="com.spring.lookup.NewsFeedManager" scope="singleton">
<lookup-method name="getNewsFeed" bean="newsFeed" />
</bean>

No comments:

Post a Comment