import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FactoryBeanTest {
public static void main(String[] args){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Object object= applicationContext.getBean("factoryBeanPojo");
FactoryBeanPojo factoryBeanPojo= (FactoryBeanPojo) applicationContext.getBean("&factoryBeanPojo");
System.out.println(object.getClass().getName());
System.out.println(factoryBeanPojo.getClass().getName());
}
}
import org.springframework.beans.factory.FactoryBean;
public class FactoryBeanPojo implements FactoryBean {
private String type;
@Override
public Object getObject() throws Exception {
if("dog".equals(type)){
return new Dog();
}else{
return new Cat();
}
}
@Override
public Class getObjectType() {
return Cat.class;
}
@Override
public boolean isSingleton() {
return true;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class Dog {
private String dogName;
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
}
public class Cat {
private String catName;
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.supremepole.springfactorybean.Dog">
<property name="dogName" value="little-yellow" />
</bean>
<bean id="school" class="com.supremepole.springfactorybean.Cat">
</bean>
<bean id="factoryBeanPojo" class="com.supremepole.springfactorybean.FactoryBeanPojo">
<property name="type" value="dog" />
</bean>
</beans>