Donate : Link

WordPress Blog : Link

Applications… : Link

Spring Tutorial Index Page: Link

  • If we implement FactoryBean then we have to implement 3 methods of FactoryBean interface.
    - getObject()
    - getObjectType()
    - isSingleton()

Create Java Project

  • Open Eclipse
  • Go to File -> New -> Others… -> Java Project
  • Create FactoryClasseFactoryBean project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs
    - commons-logging-X.X.jar
    - spring-beans-X.X.X.jar
    - spring-context-X.X.X.jar
    - spring-core-X.X.X.jar
  • * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)

spring.java

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="cf" class="com.codeFactory.beans.CarFactory" >
<property name="companyName" value="com.codeFactory.beans.JLR" />
</bean>
</beans>

Car.java

package com.codeFactory.beans;/**
* @author code.factory
*
*/
public interface Car {
public void drive();
}

CarFactory.java

package com.codeFactory.beans;import org.springframework.beans.factory.FactoryBean;/**
* @author code.factory
*
*/
public class CarFactory implements FactoryBean {
private String companyName; public void setCompanyName(String companyName) {
this.companyName = companyName;
}
@Override
public Object getObject() throws Exception {
return Class.forName(companyName).newInstance();
}
@Override
public Class getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
/* true - for Singleton
* false - for Prototype */
return true;
}
}

Audi.java

package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class Audi implements Car {
@Override
public void drive() {
System.out.println("Maximum speed is 200");
}
}

JLR.java

package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class JLR implements Car {
@Override
public void drive() {
System.out.println("Maximum speed is 250");
}
}

Client.java

package com.codeFactory.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.Car;/**
* @author code.factory
*
*/
public class Client {
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");

Car c = (Car) context.getBean("cf");
c.drive();
}
}

Output:

Maximum speed is 250