UNPKG

node-web-mvc

Version:
354 lines (353 loc) 14.5 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isIocRemovedSymbol = void 0; const BeanCreationException_1 = __importDefault(require("../../errors/BeanCreationException")); const BeanPropertyCreationException_1 = __importDefault(require("../../errors/BeanPropertyCreationException")); const Exception_1 = __importDefault(require("../../errors/Exception")); const LoopDependenciesException_1 = __importDefault(require("../../errors/LoopDependenciesException")); const Javascript_1 = __importDefault(require("../../interface/Javascript")); const ElementType_1 = __importDefault(require("../../servlets/annotations/annotation/ElementType")); const RuntimeAnnotation_1 = __importDefault(require("../../servlets/annotations/annotation/RuntimeAnnotation")); const Autowired_1 = __importDefault(require("../annotations/Autowired")); const Qualifier_1 = __importDefault(require("../annotations/Qualifier")); const InstantiationAwareBeanPostProcessor_1 = __importDefault(require("../processor/InstantiationAwareBeanPostProcessor")); const Aware_1 = __importDefault(require("./Aware")); const BeanDefinition_1 = __importDefault(require("./BeanDefinition")); const BeanFactoryAware_1 = __importDefault(require("./BeanFactoryAware")); const BeanNameAware_1 = __importDefault(require("./BeanNameAware")); const OrderedHelper_1 = __importDefault(require("./OrderedHelper")); const ProxyHelper_1 = __importDefault(require("./ProxyHelper")); exports.isIocRemovedSymbol = Symbol('isIocRemoved'); class AbstractBeanFactory { constructor() { // bean处理器 this.beanPostProcessors = []; // bean实例缓存 this.beanInstancesCache = new Map(); this.id = performance.now(); this.createChains = []; } /** * 判断传入名称的bean是否为单例 * @param key */ isSingleton(key) { var _a; return ((_a = this.getBeanDefinition(key)) === null || _a === void 0 ? void 0 : _a.scope) === 'singleton'; } /** * 判断传入名称的bean是否为原型 * @param key */ isPrototype(key) { var _a; return ((_a = this.getBeanDefinition(key)) === null || _a === void 0 ? void 0 : _a.scope) === 'prototype'; } /** * 指定指定名称的bean构造函数或者类 * @param name */ getType(name) { const definition = this.getBeanDefinition(name); const clazz = definition === null || definition === void 0 ? void 0 : definition.clazz; if (definition && !definition.clazz) { // 如果是函数来构造bean,在不显示设置返回类型时 无法获取returnType 则需要获取实例后,再获取类型 const bean = this.doGetBean(definition, name, true); bean && definition.fallbackBeanType(bean.constructor); } return clazz; } /** * 是否包含指定名称的bean * @param key * @returns */ containsBean(key) { return this.containsBeanDefinition(key); } /** * 判定指定名称Bean是为beanType参数指定的类型 * @param beanName bean定义名 * @param espectBeanType 预期的bean类型 */ isTypeMatch(beanName, beanType) { const clazz = this.getType(beanName); return Javascript_1.default.createTyper(clazz).isType(beanType); } /** * 获取指定bean实例 */ getBean(name) { const beanName = BeanDefinition_1.default.toBeanName(name); const definition = this.getBeanDefinition(beanName); let instance = null; if (definition) { instance = this.doGetBean(definition, beanName); // throw new BeanDefinitionNotfoundException(name); } this.debug('GetBean ', beanName, instance ? 'ok' : 'fail'); return instance; } getBeansOfType(beanType) { const result = []; for (const beanInstance of this.beanInstancesCache.values()) { if (Javascript_1.default.createTyper(beanInstance.constructor).isType(beanType)) { result.push(beanInstance); } } return OrderedHelper_1.default.sort(result); } /** * 根据Bean定义创建Bean实例 * @param definition Bean定义 * @returns Bean的实例对象 */ doGetBean(definition, beanName, saveInstance = false) { const isSingleton = this.isSingleton(beanName); const needSaveInstance = isSingleton || saveInstance === true; let beanInstance = this.beanInstancesCache.get(definition); if (!isSingleton) { // 为了补充getType分支,这里为了不浪费实例会设置saveInstance=true,在获取后会需要移除掉,在非单例模式下 this.beanInstancesCache.delete(definition); } if (beanInstance) { // 返回缓存对象 return beanInstance; } beanInstance = this.createBean(definition, beanName); if (beanInstance && needSaveInstance) { this.beanInstancesCache.set(definition, beanInstance); } return beanInstance; } createBean(definition, beanName) { try { // 1. 执行预创建实例化事件,如果有返回对象,则直接结束创建 const beanInstance = this.resolveBeforeInstantiation(definition, beanName); if (beanInstance) { return beanInstance; } } catch (ex) { throw new BeanCreationException_1.default(definition, beanName, `BeanPostProcessor before instantiation of bean failed`, ex); } return this.doCreateBean(definition, beanName); } checkLoopDependencies(definition, beanName) { if (!!this.createChains.find((m) => m.definition == definition)) { const chains = this.createChains; throw new LoopDependenciesException_1.default(chains); } this.createChains.push({ beanName: beanName, definition }); } doCreateBean(definition, beanName) { try { // 检测循环依赖 this.checkLoopDependencies(definition, beanName); // 2. 根据定义创建实例 const beanInstance = this.createInstance(definition); this.populateBean(beanInstance, beanName, definition); const instance = this.initializeBean(beanInstance, beanName); return instance; } catch (ex) { if (ex instanceof Exception_1.default) { throw ex; } throw new BeanCreationException_1.default(definition, beanName, `Unexpected exception during bean creation`, ex); } finally { // 创建实例成功后,重置检测变量 this.createChains.pop(); } } createInstance(definition) { if (definition.method) { return this.createInstanceByMethod(definition); } const Bean = definition.clazz; return new Bean(); } createInstanceByMethod(definition) { let instance = {}; const ownerClazz = definition.methodClazz; const clazzBeanName = BeanDefinition_1.default.toBeanName(ownerClazz); if (this.getBeanDefinition(clazzBeanName) !== definition) { // 需要先创建类实例 instance = this.getBean(clazzBeanName); } // 创建函数bean const handler = definition.method; const annotations = RuntimeAnnotation_1.default.getAnnotations([Qualifier_1.default, Autowired_1.default], ownerClazz); const parameters = annotations.filter((m) => m.elementType == ElementType_1.default.PARAMETER && m.method == handler); const values = parameters.map((parameter) => { const x = parameter.nativeAnnotation; return this.getBean(x.value || parameter.paramType.clazz); }); // 这里获取原始的实例 为了保证在类内部调用函数不使用代理对象 const originInstance = ProxyHelper_1.default.getProxyOriginInstance(instance); return handler.apply(originInstance, values); } getProcessors(processorType) { const processors = this.beanPostProcessors.filter((m) => m instanceof processorType); return processors; } resolveBeforeInstantiation(definition, beanName) { const targetType = definition.clazz; // 1.1 实例化bean let beanInstance = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (beanInstance) { // 1.2 执行初始化结束事件 beanInstance = this.applyBeanPostProcessorsAfterInitialization(beanInstance, beanName); } return beanInstance; } /** * 执行实例化before事件 * @param targetType 当前bean类 * @param beanName 当前bean名称 * @returns 返回预创建创建的实例如果有的话 */ applyBeanPostProcessorsBeforeInstantiation(targetType, beanName) { const processors = this.getProcessors(InstantiationAwareBeanPostProcessor_1.default); for (const processor of processors) { const instance = processor.postProcessBeforeInstantiation(targetType, beanName); if (instance != null) { return instance; } } } /** * 执行实例化after事件 * @param instance 当前bean实例 * @param beanName 当前bean名称 * @returns */ applyBeanPostProcessorsAfterInstantiation(instance, beanName) { const processors = this.getProcessors(InstantiationAwareBeanPostProcessor_1.default); for (const processor of processors) { const isSkip = !processor.postProcessAfterInstantiation(instance, beanName); if (isSkip) { return isSkip; } } } /** * 执行初始化before事件 * @param instance 当前bean实例 * @param beanName 当前bean名称 * @returns 要导出的bean实例 */ applyBeanPostProcessorsBeforeInitialization(instance, beanName) { const processors = this.getProcessors(InstantiationAwareBeanPostProcessor_1.default); let beanInstance = instance; for (const processor of processors) { const current = processor.postProcessBeforeInitialization(beanInstance, beanName); if (current) { beanInstance = current; } } return beanInstance; } /** * 执行初始化结束事件 * @param instance 当前bean实例 * @param beanName 当前bean名称 * @returns 要导出的bean实例 */ applyBeanPostProcessorsAfterInitialization(instance, beanName) { const processors = this.getProcessors(InstantiationAwareBeanPostProcessor_1.default); let beanInstance = instance; for (const processor of processors) { const current = processor.postProcessAfterInitialization(beanInstance, beanName); if (current) { beanInstance = current; } } return beanInstance; } applyBeanPostProperties(pvs, beanInstance, beanName, definition) { const processors = this.getProcessors(InstantiationAwareBeanPostProcessor_1.default); for (const processor of processors) { pvs = processor.postProcessProperties(pvs, beanInstance, beanName, definition); } return pvs; } populateBean(beanInstance, beanName, definition) { // 2.1 执行实例化after事件 const isSkip = this.applyBeanPostProcessorsAfterInstantiation(beanInstance, beanName); if (isSkip) { // 如果忽略属性设置 return; } // 2.2 执行处理实例属性事件 const properties = this.applyBeanPostProperties([], beanInstance, beanName, definition); properties.forEach((p) => { const value = p.value; if (p.optional === false && (value === null || value === undefined)) { throw new BeanPropertyCreationException_1.default(definition, beanName, p.name, 'get bean null'); } if (typeof value === 'function') { // 如果是一个函数,则表示用作getter 可用于解决循环依赖 Object.defineProperty(beanInstance, p.name, { get() { return value(); }, }); } else { beanInstance[p.name] = value; } }); } invokeAwareMethods(beanInstance, beanName) { if (!(beanInstance instanceof Aware_1.default)) return; if (beanInstance instanceof BeanNameAware_1.default) { beanInstance.setBeanName(beanName); } else if (beanInstance instanceof BeanFactoryAware_1.default) { beanInstance.setBeanFactory(this); } } invokeInitMethods(beanInstance, beanName) { var _a, _b; (_b = (_a = beanInstance).afterPropertiesSet) === null || _b === void 0 ? void 0 : _b.call(_a); } initializeBean(beanInstance, beanName) { // 2.3 处理初始化前事件 this.applyBeanPostProcessorsBeforeInitialization(beanInstance, beanName); // 2.4 执行不同类型的实例属性注入 this.invokeAwareMethods(beanInstance, beanName); // 2.5 执行实例初始化函数 this.invokeInitMethods(beanInstance, beanName); // 2.6 执行初始化after事件 return this.applyBeanPostProcessorsAfterInitialization(beanInstance, beanName); } /** * 添加一个或多个bean处理器 */ addBeanPostProcessor(...processors) { this.beanPostProcessors.push(...processors); } removeBeanInstance(definition) { const instance = this.beanInstancesCache.get(definition); this.beanInstancesCache.delete(definition); if (instance) { instance[exports.isIocRemovedSymbol] = true; } } debug(...args) { // console.debug(`BeanFactory[${this.id}]:`, ...args); } /** * 销毁工厂 */ destory() { this.beanInstancesCache.clear(); } } exports.default = AbstractBeanFactory;