1. 程式人生 > 其它 >Spring中Bean的例項化——例項工廠例項化

Spring中Bean的例項化——例項工廠例項化

技術標籤:springbeanjava

1、在eclipse中建立chapter02專案,在src下建立一個com.itheima.instance.factory包,在 該包中建立一個Bean3類,類中不需要新增任何方法**

public class Bean3 {

}

2、在com.itheima.instance.factory包中,建立一個MyBean3Factory類,並在類中重寫無參構造方法,並使用createBean()方法來建立Bean3物件。**

public class MyBean3Factory {
	//重寫無參構造方法
	public MyBean3Factory
() { System.out.println("bean3工廠例項化中。。。。。。"); } //建立Bean3的例項方法 public Bean3 createBean(){ return new Bean3(); } }

3、在src目錄下建立Spring配置檔案beans3.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-4.3.xsd" > <bean id="My" class="com.itheima.instance.factory.MyBean3Factory">
</bean> <bean id="bean3" factory-bean="My" factory-method="createBean"></bean> </beans>

在上述配置檔案中,首先配置了一個工廠Bean,然後配置了需要例項化的Bean。在id為bean3的Bean中,使用factory-bean屬性指向配置的例項工廠,該屬性值就是工廠Bean的id。使用factory-method屬性來確定使用工廠中的createBean()方法。

**4、在在com.itheima.instance.factory包中,建立測試類InstanceTest3。

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InstanceTest3 {
	public static void main(String[] args) {
	//載入配置檔案
	ApplicationContext app=new ClassPathXmlApplicationContext ("beans3.xml");
	//例項化
	Bean3 b=(Bean3) app.getBean("bean3");
	System.out.println(b);
	//也可以這樣例項化,
	System.out.println(app.getBean("bean3"));//注意構造方法只輸出一次

}
}

5、執行程式後,控制檯輸出結果如下圖
在這裡插入圖片描述