Factory Method
Spring Inversion of Control (IoC ) also known as
Dependency Injection (DI ) is a process by which
objects define their dependencies with collaborating objects.
This example shows getting a DriverManager instance by invoking a static factory method
package com.bethecoder.tutorials.spring3.basic;
public class DriverManager {
private static DriverManager clientService = new DriverManager () ;
private DriverManager () {
}
public static DriverManager getInstance () {
return clientService;
}
}
package com.bethecoder.tutorials.spring3.tests.factory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.bethecoder.tutorials.spring3.basic.DriverManager;
public class FactoryMethod {
/**
* @param args
*/
public static void main ( String [] args ) {
XmlBeanFactory factory = new XmlBeanFactory (
new ClassPathResource ( "factory_method.xml" )) ;
DriverManager driverMgr1 = ( DriverManager ) factory.getBean ( "driverMgr1" ) ;
System.out.println ( driverMgr1 ) ;
DriverManager driverMgr2 = ( DriverManager ) factory.getBean ( "driverMgr2" ) ;
System.out.println ( driverMgr2 ) ;
}
}
It gives the following output,
com.bethecoder.tutorials.spring3.basic.DriverManager@c39a20
com.bethecoder.tutorials.spring3.basic.DriverManager@c39a20