手写Spring scope模拟
bean工厂实现singleton、 prototype bean的创建方式
1、实体类
public class Teacher {
private String tname;
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
}
2、Bean定义
public class BeanDefined {
private String beanId;
private String classPath;
private String scope ="singleton";
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getBeanId() {
return beanId;
}
public void setBeanId(String beanId) {
this.beanId = beanId;
}
public String getClassPath() {
return classPath;
}
public void setClassPath(String classPath) {
this.classPath = classPath;
}
}
3、bean工厂
singleton、 prototype分别创建
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BeanFactory {
private List<BeanDefined> beanDefinedList;
private Map<String ,Object> SpringIoc;//已经创建好实例对象
public List<BeanDefined> getBeanDefinedList() {
return beanDefinedList;
}
public BeanFactory(List<BeanDefined> beanDefinedList) throws Exception {
this.beanDefinedList = beanDefinedList;
SpringIoc = new HashMap(); //所有scope="singleton" 采用单类模式管理bean对象
for(BeanDefined beanObj:this.beanDefinedList){
if("singleton".equals(beanObj.getScope())){
Class classFile= Class.forName(beanObj.getClassPath());
Object instance= classFile.newInstance();
SpringIoc.put(beanObj.getBeanId(), instance);
}
}
}
public void setBeanDefinedList(List<BeanDefined> beanDefinedList) {
this.beanDefinedList = beanDefinedList;
}
public Object getBean(String beanId) throws Exception{
Object instance = null;
for(BeanDefined beanObj:beanDefinedList){
if(beanId.equals(beanObj.getBeanId())){
String classPath = beanObj.getClassPath();
Class classFile= Class.forName(classPath);
String scope=beanObj.getScope();
if("prototype".equals(scope)){//.getBean每次都要返回一个全新实例对象
instance= classFile.newInstance();
}else{
instance=SpringIoc.get(beanId);
}
return instance;
}
}
return null;
}
}
4、测试程序
import java.util.ArrayList;
import java.util.List;
import com.kaikeba.beans.Teacher;
import com.kaikeba.util.BeanDefined;
import com.kaikeba.util.BeanFactory;
public class TestMain {
public static void main(String[] args) throws Exception {
//1.声明注册bean
BeanDefined beanObj = new BeanDefined();
beanObj.setBeanId("teacher");
beanObj.setClassPath("com.myspring.beans.Teacher");
//beanObj.setScope("prototype");
List beanList = new ArrayList();
beanList.add(beanObj);//spring核心配置
//2.声明一个Spring提供BeanFacotory
BeanFactory factory = new BeanFactory(beanList);
//3.开发人员向BeanFactory索要实例对象.
Teacher t= (Teacher) factory.getBean("teacher");
System.out.println("t="+t);
Teacher t2= (Teacher) factory.getBean("teacher");
System.out.println("t2="+t2);
}
}