---
title: "js模拟java的spring"
author: "devil13th"
date: "2010-12-02T11:47:15Z"
tags: []
categories: ["Web前端"]
slug: "js-java-spring"
draft: false
lastmod: "2010-12-02T11:47:15Z"
id: 831328
url: "https://devil13th.iteye.com/blog/831328"
---

```
<script type="text/javascript">



//模拟 map 
var Map = function(){
	this.m = {};
}
Map.prototype = {
	put : function(k,v){
		this.m[k] = v;
	},
	get : function(k){
		return this.m[k];
	}
}

//模拟beanFactory 
var Spring = {
	objs : new Map(),
	init : function(config){
		for(var i = 0 , j = config.length ; i < j ; i++){
			var cfg = config[i];
			var ret = this.create(cfg);
			this.objs.put(ret[0],ret[1]);
		}
	},
	get : function(k){
		return this.objs.get(k);
	},
	create : function(cfg){
		var f = new Function();
		f.prototype = window[cfg.fn].prototype;
		var _instance = new f();
		
		var args = [];
		if(cfg.pro){
			for(var pro in cfg.pro){
				if(cfg.pro[pro].v){
					args.push(cfg.pro[pro].v)
				}
				if(cfg.pro[pro].c){
					args.push(this.get(cfg.pro[pro].c))
				}
			}
		}
		window[cfg.fn].apply(_instance,args);
		return [cfg.id,_instance]
	}
}


//模拟applicationContext.xml
var cfg = [
	//模拟bean
	{
		id : "c2", // bean的id
		fn : "C2"  // bean的class
	},
	{
		id : "c1",
		fn : "C1",
		pro : {//构造函数的参数
			arg1 : {v:"vvv"}, //v :代表直接赋值 (spring 配置文件中的 value="...")
			arg2 : {v:"bbb"}, 
			arg3 : {c:"c2"} //c : 配置中其他bean的id(spring 配置文件中的 ref bean = "...")
		}
	}
]


//客户端

var C1 = function(x,y,z){
	this.a = x;
	this.b = y;
	this.c = z;
	this.s = this.c.add(this.a,this.b);
	var _this = this;
	this.z = function(){alert(_this.a + "|||||" +  _this.b)}
}

var C2 = function(){
	this.add = function(a,b){return a + b};
	this.toString = function(){return "C2"}
}


Spring.init(cfg); //加载配置
var  c1 = Spring.get("c1"); //从beanfactory中获取bean

alert(c1.s);
c1.z();




</script>
```