Spring實例化bean的三種方法

1.用構造器來實例化

 

<bean id="hello2" class="com.hsit.hello.impl.ENhello" />

 

2.使用靜態工廠方法實例化

 

要寫一個bean,bean中定義一個靜態方法,生成bean,配置factory-method指定靜態方法,運行時容器就會自動調用靜態方法生成實例


bean

package com.hsit.hello.impl;

import com.hsit.hello.IHello;

public class CHhello implements IHello {

	private String msg;

	public void sayHello() {
		System.out.println("中文" + msg);
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Chinese";
	}

	public static CHhello createInstance() {
		System.out.println("jingtai");
		return new CHhello();
	}
}



配置文件


<bean id="hello1" class="com.hsit.hello.impl.CHhello" factory-method="createInstance" lazy-init="true">
	<!-- setter注入 -->
		<property name="msg" value="哈哈">
		</property>
	</bean>


3.使用實例工廠方法實例化

 

要寫兩個bean,一個是要實例化的bean,另一個是工廠bean。容器先實例化工廠bean,然後調用工廠bean配置項factory-method中指定的方法,在方法中實例化bean

 

package com.hsit.hello.impl;

public class ENhelloFactory {
	
	public ENhello createInstance() {
		System.out.println("ENhello工廠");
		return new ENhello();
	}
	
	public ENhelloFactory() {
		System.out.println("chuanjian");
	}

}


 

package com.hsit.hello.impl;

import com.hsit.hello.IHello;

public class ENhello implements IHello {

	@Override
	public void sayHello() {
		// TODO Auto-generated method stub
		System.out.println("hello");
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "我是ENhello";
	}
}


配置文件

	<bean id="eHelloFactory" class="com.hsit.hello.impl.ENhelloFactory" />
	<!-- factory-bean填上工廠bean的id,指定工廠bean的工廠方法生成實例,class屬性不填 -->
	<bean id="example" factory-bean="eHelloFactory" factory-method="createInstance"/>

 

測試代碼

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		ENhello eNhello = (ENhello) factory.getBean("example");
		System.out.println(eNhello.toString());
		
		 factory.getBean("hello1");

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章