Saturday 19 March 2011

Spring : Creating custom factory-bean

Because of the complexity involved, we tend to write our own factory classes to initialize complex beans. There are couple of ways :

  • Traditional way of writing factory classes
  • Using FactoryBean Api for writing a factory class

example :

Suppose we have a bean called MyService. Likewise there can be many other beans, and there is a factory class to which contain multiple methods to return these different type of beans. So based on the parameter of the function, it generates a bean of different type.

Consider the bean class:

package ex3;

public class MyService {

//some bean components
}


Consider the factory class :


import javax.sql.DataSource;

public class MyServiceLocator {

public MyService createMyService() {
//we assume there is some complex code to initialize MyService bean
return new MyService();
}

public MyService createMyService(DataSource dataSource) {
//some database specific code to fetch values required for instantiating the bean
return new MyService();
}
}


Describing the factory class:


<!-- define the bean of type factory-class -->
<bean id="serviceLocator" class="ex3.MyServiceLocator" />
<!-- Now get the bean created by factory class by factory-bean -->
<bean id="myService" factory-bean="serviceLocator" factory-method="createMyService" />


Creating the beans from factory class:


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyServiceLocatorTest {

public void testMyServiceLocator() {
ApplicationContext container = new ClassPathXmlApplicationContext("/sompath/config.xml");
//getbean of type myservice from factory class inside containter
MyService myService = container.getBean("myService", MyService.class);
}


Now this will call factory-method of type with no arguments, but when factory-method has argument then we can do this by these 2 methods. See here.

No comments:

Post a Comment