spring bean加载模式
作者:bin1.mbd.isSingleton()单例
2.mbd.isPrototype()原型,即多例
3.ohter,Request、Session等
我们可以通过打断点查看你的bean是如何加载的:
beanName.indexOf("factoryBeanService") > 0 ? true : false
类:org.springframework.beans.factory.support.AbstractBeanFactory;
// 单例模式创建 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { //从单例缓存中显式删除实例:它可能已经放在那里迫切需要创建过程,以允许循环引用解析。还要删除所有收到对该bean的临时引用的bean。 destroySingleton(beanName); throw ex; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //原型模式创建 else if (mbd.isPrototype()) { //这是一个原型->创建一个新实例。 Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } //其他Request等 else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } }