Spring实例化bean的三种方法

1.用构造器来实例化

 

 

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();
	}
}



配置文件



	
		
		
	


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";
	}
}


配置文件

	
	
	

 

测试代码

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

 

 

 

你可能感兴趣的:(spring)