1,编写bean
package com.songyan.factory2; public class Bean3 { }
2,编写工厂
package com.songyan.factory2; public class MyBean3Factory { public MyBean3Factory() { System.out.println("bean3 实例化ing``````"); } public Bean3 createBean() { return new Bean3(); } }
3, 编写xml
<?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="fac3" class="com.songyan.factory2.MyBean3Factory" ></bean> <bean id="bean3" class="com.songyan.factory2.Bean3" factory-bean="fac3" factory-method="createBean"></bean> </beans>
4, 测试类
package com.songyan.factory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestFactory { public static void main(String[] args) { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("com/songyan/factory/beans2.xml"); Bean2 bean=(Bean2)applicationContext.getBean("factory"); System.out.println(bean); } }
5, 输出结果