bearcat是网易的一个ioc容器,下面是学习的示例代码:
代码文件构成:
context.json:
{
"name": "zjw-lib",
"scan": "lib"
}
scan:表示扫描lib文件夹中的所有文件
lib1.js:
/**
* Created by Administrator on 2016/5/3.
*/
var BearCat = require('bearcat');
var EventEmitter = require('events').EventEmitter;
var Util = require('util');
var person = function (name, age) {
EventEmitter.call(this);
this.human = null;
this.name = name;
this.age = age;
this.lastName = null;
this.a = null;
};
Util.inherits(person, EventEmitter);
person.prototype.init = function () {
this.lastName = "zheng";
};
person.prototype.toString = function () {
return this.name + " " + this.age + " " + this.lastName + " " + this.a+" "+this.human.getName();
};
module.exports = {
id: "person",
func: person,
init: "init",
scope: "prototype",
"args": [
{name: "name", type: "String"},
{name: "age", type: "Number"}
],
"props": [
{name: "a", value: 1222},
{name: "human", ref: "human"}
]
};
id:bearcat内部识别的唯一key
func:对象
init:自动执行函数,bearcat调用getBean会自动执行该函数
scope:用于生成对象,默认是singleton(单例模式),每次调用返回old对象
多例(prototype)意味着每次对名叫id的bean的请求, 容器都会创建一个新的bean实例. 作为经验, prototype scope 的bean适用于有状态的beans, 而 singleton scope适用于无状态的beans.
args:生成对象构造函数参数
props:注入内容,注入的内容可以在对象内部调用
lib2.js:
/**
* Created by Administrator on 2016/5/3.
*/
var Bearcat = require('bearcat');
var EventEmitter = require('events').EventEmitter;
var Util = require('util');
var human = function () {
this.name = "human1111";
this.index = 0;
};
Util.inherits(human, EventEmitter);
human.prototype.start = function () {
this.emit("addIndex", this.index);
this.index++;
console.log("emit index start");
};
human.prototype.getName = function () {
this.on("addIndex", function (index) {
console.log("index ", index);
});
return this.name;
};
module.exports = {
id: "human",
func: human
};
app.js:
/**
* Created by Administrator on 2016/5/3.
*/
var BearCat = require("bearcat");
var Path = require("path");
var contextArray = [];
var context1 = require.resolve(Path.join(__dirname, "./context.json"));
contextArray.push(context1);
BearCat.createApp(contextArray);
BearCat.start(function () {
var p= BearCat.getBean("person","zjw",25);
console.log(p.toString());
var h = BearCat.getBean("human");
h.start();
console.log(h.getName());
});
参考资料:https://github.com/bearcatjs/bearcat
https://github.com/bearcatjs/bearcat/wiki