Saturday 19 March 2011

Spring : ObjectFactory Interface

This approach helps us to deal with "lazy initialization" of bean. The problem with ApplicationContextAware approach was that we need to know the id of the bean. No doubt we can inject the id of the bean somehow, but that still means more code.

This interface is even used manually by Spring framework to create bean objects.

Example:

public interface CustomerService {

public void payBill(double amt);
}
public class CustomerServiceImpl2 implements CustomerService {

private ObjectFactory<BillPaymentService> factory;

public void setFactory(ObjectFactory<BillPaymentService> factory) {
this.factory = factory;
}

public void payBill(double amt) {
BillPaymentService billService = factory.getObject();
//we need to call some method of BillPaymentService here. Right now not required.
}
}

Now in the bean descriptor file we have to use idref tag :

<!--  We are using ObjectFactory interface here -->    
<bean id="customerService2" class="com.xxxxx.CustomerServiceImpl2">
<property name="factory">
<bean
class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
<property name="targetBeanName">
<idref local="billPaymentService" />
</property>
</bean>
</property>
</bean>

<!-- idref is referring to the local bean billPaymetService defined here -->
<bean id="billPaymentService" class="ex6.BillPaymentServiceImpl" scope="prototype" />



No comments:

Post a Comment