Spring 源码解析(六)创建bean实例

回到org.springframework.context.support.AbstractApplicationContext的refresh方法

 //org.springframework.context.support.AbstractApplicationContext
1
@Override 2 public void refresh() throws BeansException, IllegalStateException { 3 synchronized (this.startupShutdownMonitor) { 4 // Prepare this context for refreshing. 5 prepareRefresh(); 6 7 // Tell the subclass to refresh the internal bean factory. 8 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 9 10 // Prepare the bean factory for use in this context. 11 prepareBeanFactory(beanFactory); 12 13 try { 14 // Allows post-processing of the bean factory in context subclasses. 15 postProcessBeanFactory(beanFactory); 16 17 // Invoke factory processors registered as beans in the context. 18 invokeBeanFactoryPostProcessors(beanFactory); 19 20 // Register bean processors that intercept bean creation. 21 registerBeanPostProcessors(beanFactory); 22 23 // Initialize message source for this context. 24 initMessageSource(); 25 26 // Initialize event multicaster for this context. 27 initApplicationEventMulticaster(); 28 29 // Initialize other special beans in specific context subclasses. 30 onRefresh(); 31 32 // Check for listener beans and register them. 33 registerListeners(); 34 35 // Instantiate all remaining (non-lazy-init) singletons. 36 finishBeanFactoryInitialization(beanFactory); 37 38 // Last step: publish corresponding event. 39 finishRefresh(); 40 } 41 42 catch (BeansException ex) { 43 // Destroy already created singletons to avoid dangling resources. 44 destroyBeans(); 45 46 // Reset 'active' flag. 47 cancelRefresh(ex); 48 49 // Propagate exception to caller. 50 throw ex; 51 } 52 } 53 }

第36行,创建bean实例(非延迟加载、单例)。跟踪方法会调用org.springframework.beans.factory.support.AbstractBeanFactory的getBean(String beanName)方法,接着跟踪到AbstractBeanFactory的getBean的doGetBean

  //org.springframework.beans.factory.support.AbstractBeanFactory
1
/** 2 * Return an instance, which may be shared or independent, of the specified bean. 3 * @param name the name of the bean to retrieve 4 * @param requiredType the required type of the bean to retrieve 5 * @param args arguments to use if creating a prototype using explicit arguments to a 6 * static factory method. It is invalid to use a non-null args value in any other case. 7 * @param typeCheckOnly whether the instance is obtained for a type check, 8 * not for actual use 9 * @return an instance of the bean 10 * @throws BeansException if the bean could not be created 11 */ 12 @SuppressWarnings("unchecked") 13 protected <T> T doGetBean( 14 final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) 15 throws BeansException { 16 17 final String beanName = transformedBeanName(name); 18 Object bean; 19 20 // Eagerly check singleton cache for manually registered singletons. 21 Object sharedInstance = getSingleton(beanName); 22 if (sharedInstance != null && args == null) { 23 if (logger.isDebugEnabled()) { 24 if (isSingletonCurrentlyInCreation(beanName)) { 25 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + 26 "' that is not fully initialized yet - a consequence of a circular reference"); 27 } 28 else { 29 logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); 30 } 31 } 32 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); 33 } 34 35 else { 36 // Fail if we're already creating this bean instance: 37 // We're assumably within a circular reference. 38 if (isPrototypeCurrentlyInCreation(beanName)) { 39 throw new BeanCurrentlyInCreationException(beanName); 40 } 41 42 // Check if bean definition exists in this factory. 43 BeanFactory parentBeanFactory = getParentBeanFactory(); 44 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { 45 // Not found -> check parent. 46 String nameToLookup = originalBeanName(name); 47 if (args != null) { 48 // Delegation to parent with explicit args. 49 return (T) parentBeanFactory.getBean(nameToLookup, args); 50 } 51 else { 52 // No args -> delegate to standard getBean method. 53 return parentBeanFactory.getBean(nameToLookup, requiredType); 54 } 55 } 56 57 if (!typeCheckOnly) { 58 markBeanAsCreated(beanName); 59 } 60 61 try { 62 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 63 checkMergedBeanDefinition(mbd, beanName, args); 64 65 // Guarantee initialization of beans that the current bean depends on. 66 String[] dependsOn = mbd.getDependsOn(); 67 if (dependsOn != null) { 68 for (String dependsOnBean : dependsOn) { 69 if (isDependent(beanName, dependsOnBean)) { 70 throw new BeanCreationException("Circular depends-on relationship between '" + 71 beanName + "' and '" + dependsOnBean + "'"); 72 } 73 registerDependentBean(dependsOnBean, beanName); 74 getBean(dependsOnBean); 75 } 76 } 77 78 // Create bean instance. 79 if (mbd.isSingleton()) { 80 sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { 81 @Override 82 public Object getObject() throws BeansException { 83 try { 84 return createBean(beanName, mbd, args);//创建bean,处理bean初始化后aware接口值填充是在AbstractAutowireCapableBeanFactory的invokeAwareMethods里实现,InitializingBean接口也在此类invokeInitMethods调用填充,包括BeanPostProcessor接口等全部都在此类被调 85 } 86 catch (BeansException ex) { 87 // Explicitly remove instance from singleton cache: It might have been put there 88 // eagerly by the creation process, to allow for circular reference resolution. 89 // Also remove any beans that received a temporary reference to the bean. 90 destroySingleton(beanName); 91 throw ex; 92 } 93 } 94 }); 95 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 96 } 97 98 else if (mbd.isPrototype()) { 99 // It's a prototype -> create a new instance. 100 Object prototypeInstance = null; 101 try { 102 beforePrototypeCreation(beanName); 103 prototypeInstance = createBean(beanName, mbd, args); 104 } 105 finally { 106 afterPrototypeCreation(beanName); 107 } 108 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 109 } 110 111 else { 112 String scopeName = mbd.getScope(); 113 final Scope scope = this.scopes.get(scopeName); 114 if (scope == null) { 115 throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); 116 } 117 try { 118 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { 119 @Override 120 public Object getObject() throws BeansException { 121 beforePrototypeCreation(beanName); 122 try { 123 return createBean(beanName, mbd, args); 124 } 125 finally { 126 afterPrototypeCreation(beanName); 127 } 128 } 129 }); 130 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 131 } 132 catch (IllegalStateException ex) { 133 throw new BeanCreationException(beanName, 134 "Scope '" + scopeName + "' is not active for the current thread; " + 135 "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", 136 ex); 137 } 138 } 139 } 140 catch (BeansException ex) { 141 cleanupAfterBeanCreationFailure(beanName); 142 throw ex; 143 } 144 } 145 146 // Check if required type matches the type of the actual bean instance. 147 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { 148 try { 149 return getTypeConverter().convertIfNecessary(bean, requiredType); 150 } 151 catch (TypeMismatchException ex) { 152 if (logger.isDebugEnabled()) { 153 logger.debug("Failed to convert bean '" + name + "' to required type [" + 154 ClassUtils.getQualifiedName(requiredType) + "]", ex); 155 } 156 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); 157 } 158 } 159 return (T) bean; 160 }

关注第79-96行,创建了bean实例(单例的),具体细节不再介绍,请大家有兴趣的可以研究。

下一章介绍Spring解析自定义xsd, 不是命名空间为http://www.springframework.org/schema/beans的节点。


为了大家更直观地查看创建bean过程,列出bean创建的栈信息

posted @ 2018-04-08 17:16  jintian315  阅读(167)  评论(0编辑  收藏  举报