DoAsVue地址:DoAsVue
【@Bean与@Autowired注解源码】
【@Bean与@Autowired注解源码】
JavaScript:
// BeanAnnotation.DAVue.js
var plugin = {
data(){
return{
enum:{
singleton : "singleton",
factory : "factory"
},
beanContainer:{
}
}
},
extends:"BaseAnnotationOperator",
methods:{
setBeanDefinition(key,value,type,method,plugin){
this.beanContainer[key] = {
value:value,
type:type,
method:method,
plugin:plugin
};
},
getBean(name,force){
if(this.beanContainer[name] == null){
if(force!=null && force==true){
throw Error("Cannot get beam named \""+name+"\"");
} else {
return null;
}
}else{
let currentBeanDefinition = this.beanContainer[name];
if(currentBeanDefinition.type == this.enum.singleton){
if(currentBeanDefinition.value == null){
currentBeanDefinition.value = currentBeanDefinition.method.call(currentBeanDefinition.plugin);
}
return currentBeanDefinition.value; //单例模式
}else{
return currentBeanDefinition.method.call(currentBeanDefinition.plugin) //工厂模式
}
}
},
//Bean 注解,将一个method的返回值定义为 bean
/**
* @param {*} name bean名称
* @param {*} type 创建类型:[singleton:单例模式、factory:工厂模式]
*/
Bean(method,methodName,annotationInfo,module,name,type){
/**
* @annotation
*/
if(typeof(name) == "string"){
if(type == this.enum.factory){
this.print("加载bean: "+name+" type: "+this.enum.factory)
this.setBeanDefinition(name,null,this.enum.factory,method,module);
}else{
this.print("加载bean: "+name+" type: "+this.enum.singleton)
this.setBeanDefinition(name,null,this.enum.singleton,method,module);
}
}else{
throw Error("name of bean must be string")
}
return method;
},
/**
* @param {*} beanNameArray bean名称列表,会按照method的参数列表进行依次注入
* @param {*} forceInject 是否强制注入,是:如果注入失败会报错,否:注入失败会给默认值null而不会报错
*/
Autowired(method,methodName,annotationInfo,module,beanNameArray,forceInject){
/**
* @annotation
*/
if(beanNameArray == null || !Array.isArray(beanNameArray)){
throw Error("beanNameArray must be an array")
}
let beanArray = [];
for(let i in beanNameArray){
beanArray.push(this.getBean(beanNameArray[i],forceInject))
}
method(...beanArray);
return method;
}
}
}
//导出规范
module.exports={
name:"BeanAnnotation", //表示这个插件的名字,用于被其他插件引用时的名字
plugin:plugin//当前导出的创建对象
}