返回

最简单的模拟spring ioc中的scope

发布时间:2022-12-26 11:11:41 321
# java# spring# java# 容器

在spring mvc中,scope主要是prototype和singleton两个状态了,下面用代码简单模拟下:

实体类:
 

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



}

BeanDefined.java,这个类中,存放的是要加入的每个类的名字和全路径,方便容器反射的时候找到:
 

public class BeanDefined {

private String beanId;
private String classPath;
private String scope ="singleton";
。。。。。。。。。

}

模拟的Beanfactory类:
 

public class BeanFactory {

private List beanDefinedList;
private Map SpringIoc;//已经创建好实例对象

public List getBeanDefinedList() {
return beanDefinedList;
}




public BeanFactory(List 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 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;
}


}

  可以看到,这里通过HASHMAP存放每次要实例化的对象了,使用方法比较简单:
 

public static void main(String[] args) throws Exception {

//1.声明注册bean
BeanDefined beanObj = new BeanDefined();
beanObj.setBeanId("teacher");
beanObj.setClassPath("com.kaikeba.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);

}

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
常用方法论总结 2022-12-26 10:30:25