Saturday 19 March 2011

Spring : ServiceLocatorFactoryBean Interface

This interface is used for lazy initialization of beans:

The problem with ApplicationContextAware and ObjectFactory is the component is coupled with the spring API.

Steps required

Step 1

Now to achieve 100% abstraction, we need some way by which Spring can dynamically create the instance of another bean and return it to us. So this is what we do as our first step:

//the interface implemented by various impl classes
public interface BillPaymentService {

}
//step 1
public interface BillPaymentServiceFactory {

public BillPaymentService getService();
}


Step 2


public interface CustomerService{ 
void payBill(double amt)
}
public class CustomerServiceImpl3 implements CustomerService {

private BillPaymentServiceFactory billPaymentServiceFactory;

public void setBillPaymentServiceFactory(
BillPaymentServiceFactory billPaymentServiceFactory) {
this.billPaymentServiceFactory = billPaymentServiceFactory;
}

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


Step 3 :  Xml config

<!-- We are using the ServiceLocatorFactoryBean here -->
<!-- In the bean just refer to serviceLocator -->
bean id="customerService3" class="com.xxxxx.CustomerServiceImpl3">
<property name="billPaymentServiceFactory" ref="serviceLocator"/>
/bean>

<bean id="serviceLocator"
class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
<property name="serviceLocatorInterface" value="com.xxxxx.BillPaymentServiceFactory"/>
/bean>

We are injecting the ServiceLocator in CustomerService bean which implement factory interface for us and provide an instance of the target bean transparently.

No comments:

Post a Comment