Spring — FactoryBean | Code Factory

Spring Tutorial Index Page: Link

Create Java Project

<!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>
package com.codeFactory.beans;/**
* @author code.factory
*
*/
public interface Car {
public void drive();
}
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;
}
}
package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class Audi implements Car {
@Override
public void drive() {
System.out.println("Maximum speed is 200");
}
}
package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class JLR implements Car {
@Override
public void drive() {
System.out.println("Maximum speed is 250");
}
}
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();
}
}
Maximum speed is 250

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store