Spring配置文件
<?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-3.0.xsd">
<bean id="productBean1" class="factory.StaticFactory" factory-method="create" scope="prototype">
</bean>
<bean id="productBean2" factory-bean="myfactory" factory-method="create" scope="prototype">
</bean>
<bean id="myfactory" class="factory.NonStaticFactory"/>
</beans>
StaticFactory.java
public class StaticFactory {
public static ProductBean create(){
return new ProductBean("FromStaticFactory");
}
}
NonStaticFactory.java
public class NonStaticFactory {
public ProductBean create(){
return new ProductBean("FromNonStaticFactory");
}
}
ProductBean.java
public class ProductBean {
public String name;
public ProductBean(){}
public ProductBean(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
测试类
public class FactoryTest {
private static ApplicationContext ctx = new ClassPathXmlApplicationContext("factory/factory-context.xml");
/**
* @param args
*/
public static void main(String[] args) {
StaticFactoryTest();
NonStaticFactoryTest();
}
public static void StaticFactoryTest(){
ProductBean pb = (ProductBean)ctx.getBean("productBean1");
out.println(pb);
}
public static void NonStaticFactoryTest(){
ProductBean pb = (ProductBean)ctx.getBean("productBean2");
out.println(pb);
}
}