Sunday, March 20, 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.


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">
<property name="targetBeanName">
<idref local="billPaymentService" />

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

No comments:

Post a Comment