系列文章目录
文章目录
前言
提示:在上一章的学习中,我们对BeanFactory的创建过程有了一个熟悉,其实实际的操作不止创建BeanFactory,调用的过程也实现了将xml解析为Document对象,再转换成BeanDefinition(很重要,Spring的Bean),并注册到BeanFactory,接着本文带着疑问学习一下Spring中的Bean(BeanDefinition)是怎么创建实例出来的?
提示:以下是本篇文章正文内容,下面案例可供参考
一、BeanDefinition实例过程简介
上一章学习了obtainFreshBeanFactory这个方法,经过这个方法,xml配置信息已经转换成一个BeanDefinition,但是BeanDefinition还没实例,属性也没配置,只是配置信息被提取出来,而且注册到BeanFactory

在之前文章学习,我们知道了,Bean的实例完成是在finishBeanFactoryInitialization这一步,当然是针对非懒加载的单例bean,多例的情况,后面有时间再来学习

二、finishBeanFactoryInitialization实现
ok,有了前面的简单了解,可以开始学习finishBeanFactoryInitialization的创建过程:通过代码,一步步跟,看看BeanDefinition是怎么初始化的?bean属性是怎么填充的?
1/** 2 * Finish the initialization of this context's bean factory, 3 * initializing all remaining singleton beans. 4 */ 5protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { 6 7 8 9 // Initialize conversion service for this context. 10 // 初始化ConversionService,这个bean用于将前端传过来的参数和后端的 controller 方法上的参数进行绑定 11 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && 12 beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { 13 14 15 16 beanFactory.setConversionService( 17 beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); 18 } 19 20 // Register a default embedded value resolver if no bean post-processor 21 // (such as a PropertyPlaceholderConfigurer bean) registered any before: 22 // at this point, primarily for resolution in annotation attribute values. 23 if (!beanFactory.hasEmbeddedValueResolver()) { 24 25 26 27 beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); 28 } 29 30 // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. 31 // 先初始化LoadTimeWeaverAware 类型的Bean 32 // AspectJ 的内容,IoC的源码学习,先跳过 33 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); 34 for (String weaverAwareName : weaverAwareNames) { 35 36 37 38 getBean(weaverAwareName); 39 } 40 41 // Stop using the temporary ClassLoader for type matching. 42 beanFactory.setTempClassLoader(null); 43 44 // Allow for caching all bean definition metadata, not expecting further changes. 45 // 冻结配置,不让bean 定义解析、加载、注册 46 beanFactory.freezeConfiguration(); 47 48 // Instantiate all remaining (non-lazy-init) singletons. 49 // 实例所有非懒加载的单例Bean 50 beanFactory.preInstantiateSingletons(); 51}
{@link org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons}
1@Override 2public void preInstantiateSingletons() throws BeansException { 3 4 5 6 if (logger.isDebugEnabled()) { 7 8 9 10 logger.debug("Pre-instantiating singletons in " + this); 11 } 12 13 // Iterate over a copy to allow for init methods which in turn register new bean definitions. 14 // While this may not be part of the regular factory bootstrap, it does otherwise work fine. 15 // 获取beanName列表,this.beanDefinitionNames 保存了所有的 beanNames 16 List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); 17 18 // Trigger initialization of all non-lazy singleton beans... 19 // 触发所有非懒加载的单例bean初始化操作(lazy-init=false) 20 for (String beanName : beanNames) { 21 22 23 24 // 合并rootBean中的配置, <bean id="a" class="a" parent="p" /> 25 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); 26 // 非抽象(abstract = false)、非懒加载(lazy-init=false)的单例Bean(scope=singleton) 27 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { 28 29 30 31 // 处理FactoryBean,注意对比BeanFactory和FactoryBean 32 if (isFactoryBean(beanName)) { 33 34 35 36 // factoryBean调用在beanName加载前缀符号‘&’ 37 // 为什么要加‘&’,应该是做下标记,不过在bean创建过程要进行转换,详情请看下文 38 Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); 39 if (bean instanceof FactoryBean) { 40 41 42 43 FactoryBean<?> factory = (FactoryBean<?>) bean; 44 boolean isEagerInit; 45 // FactoryBean是SmartFactoryBean 的基类 46 if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { 47 48 49 50 isEagerInit = AccessController.doPrivileged( 51 (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, 52 getAccessControlContext()); 53 } 54 else { 55 56 57 58 isEagerInit = (factory instanceof SmartFactoryBean && 59 ((SmartFactoryBean<?>) factory).isEagerInit()); 60 } 61 if (isEagerInit) { 62 63 64 65 getBean(beanName); 66 } 67 } 68 } 69 else { 70 71 72 73 // 普通的Bean,调这个方法进行实例,往下跟 74 getBean(beanName); 75 } 76 } 77 } 78 79 // Trigger post-initialization callback for all applicable beans... 80 // SmartInitializingSingleton 的基类在这里回调 81 for (String beanName : beanNames) { 82 83 84 85 Object singletonInstance = getSingleton(beanName); 86 if (singletonInstance instanceof SmartInitializingSingleton) { 87 88 89 90 SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; 91 if (System.getSecurityManager() != null) { 92 93 94 95 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { 96 97 98 99 smartSingleton.afterSingletonsInstantiated(); 100 return null; 101 }, getAccessControlContext()); 102 } 103 else { 104 105 106 107 smartSingleton.afterSingletonsInstantiated(); 108 } 109 } 110 } 111}
AbstractBeanFactory.java:
{@link org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean}
1@Override 2public Object getBean(String name) throws BeansException { 3 4 5 6 // 往下跟 7 return doGetBean(name, null, null, false); 8}
{@link org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean}
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 when creating a bean instance using explicit arguments 6 * (only applied when creating a new instance as opposed to retrieving an existing one) 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") 13protected <T> T doGetBean( 14 String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) 15 throws BeansException { 16 17 18 19 // 处理BeanName,前面说的FactoryBean带‘&’符号,要在这里进行转换 20 String beanName = transformedBeanName(name); 21 Object bean; 22 23 // Eagerly check singleton cache for manually registered singletons. 24 // 从map(singletonObjects)里获取单例bean,确定是否已经存在对应实例 25 Object sharedInstance = getSingleton(beanName); 26 if (sharedInstance != null && args == null) { 27 28 29 30 if (logger.isDebugEnabled()) { 31 32 33 34 if (isSingletonCurrentlyInCreation(beanName)) { 35 36 37 38 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + 39 "' that is not fully initialized yet - a consequence of a circular reference"); 40 } 41 else { 42 43 44 45 logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); 46 } 47 } 48 // 两种情况:普通的bean,直接从singletonObjects返回sharedInstance 49 //如果是FactoryBean,返回其创建的对象实例 50 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); 51 } 52 53 else { 54 55 56 57 // Fail if we're already creating this bean instance: 58 // We're assumably within a circular reference. 59 // 为了避免循环引用,遇到这种情况,直接抛出异常 60 if (isPrototypeCurrentlyInCreation(beanName)) { 61 62 63 64 throw new BeanCurrentlyInCreationException(beanName); 65 } 66 67 // Check if bean definition exists in this factory. 68 // 检查BeanFactory是否存在这个BeanDefinition 69 BeanFactory parentBeanFactory = getParentBeanFactory(); 70 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { 71 72 73 74 // Not found -> check parent. 75 // 当前容器找不到BeanDefinition,去parent容器查询 76 String nameToLookup = originalBeanName(name); 77 if (parentBeanFactory instanceof AbstractBeanFactory) { 78 79 80 81 return ((AbstractBeanFactory) parentBeanFactory).doGetBean( 82 nameToLookup, requiredType, args, typeCheckOnly); 83 } 84 else if (args != null) { 85 86 87 88 // Delegation to parent with explicit args. 89 // 返回parent容器的查询结果 90 return (T) parentBeanFactory.getBean(nameToLookup, args); 91 } 92 else { 93 94 95 96 // No args -> delegate to standard getBean method. 97 return parentBeanFactory.getBean(nameToLookup, requiredType); 98 } 99 } 100 101 if (!typeCheckOnly) { 102 103 104 105 //typeCheckOnly为false的情况,将beanName放在一个alreadyCreated的集合 106 markBeanAsCreated(beanName); 107 } 108 109 try { 110 111 112 113 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 114 checkMergedBeanDefinition(mbd, beanName, args); 115 116 // Guarantee initialization of beans that the current bean depends on. 117 // 校验是否配置了 depends-on 118 String[] dependsOn = mbd.getDependsOn(); 119 if (dependsOn != null) { 120 121 122 123 for (String dep : dependsOn) { 124 125 126 127 // 存在循环引用的情况,要抛出异常 128 if (isDependent(beanName, dep)) { 129 130 131 132 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 133 "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); 134 } 135 // 正常情况,注册依赖关系 136 registerDependentBean(dep, beanName); 137 try { 138 139 140 141 // 初始化被依赖项 142 getBean(dep); 143 } 144 catch (NoSuchBeanDefinitionException ex) { 145 146 147 148 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 149 "'" + beanName + "' depends on missing bean '" + dep + "'", ex); 150 } 151 } 152 } 153 154 // Create bean instance. 155 // 单例的Bean 156 if (mbd.isSingleton()) { 157 158 159 160 sharedInstance = getSingleton(beanName, () -> { 161 162 163 164 try { 165 166 167 168 // 创建单例bean 169 return createBean(beanName, mbd, args); 170 } 171 catch (BeansException ex) { 172 173 174 175 // Explicitly remove instance from singleton cache: It might have been put there 176 // eagerly by the creation process, to allow for circular reference resolution. 177 // Also remove any beans that received a temporary reference to the bean. 178 destroySingleton(beanName); 179 throw ex; 180 } 181 }); 182 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 183 } 184 // 多例的Bean,scope = protoType 185 else if (mbd.isPrototype()) { 186 187 188 189 // It's a prototype -> create a new instance. 190 Object prototypeInstance = null; 191 try { 192 193 194 195 beforePrototypeCreation(beanName); 196 // 执行多例Bean创建 197 prototypeInstance = createBean(beanName, mbd, args); 198 } 199 finally { 200 201 202 203 afterPrototypeCreation(beanName); 204 } 205 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 206 } 207 // 如果不是单例bean也不是多例的bean,委托给对应的实现类 208 else { 209 210 211 212 String scopeName = mbd.getScope(); 213 if (!StringUtils.hasLength(scopeName)) { 214 215 216 217 throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'"); 218 } 219 Scope scope = this.scopes.get(scopeName); 220 if (scope == null) { 221 222 223 224 throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); 225 } 226 try { 227 228 229 230 Object scopedInstance = scope.get(beanName, () -> { 231 232 233 234 beforePrototypeCreation(beanName); 235 try { 236 237 238 239 // 执行bean创建 240 return createBean(beanName, mbd, args); 241 } 242 finally { 243 244 245 246 afterPrototypeCreation(beanName); 247 } 248 }); 249 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 250 } 251 catch (IllegalStateException ex) { 252 253 254 255 throw new BeanCreationException(beanName, 256 "Scope '" + scopeName + "' is not active for the current thread; consider " + 257 "defining a scoped proxy for this bean if you intend to refer to it from a singleton", 258 ex); 259 } 260 } 261 } 262 catch (BeansException ex) { 263 264 265 266 cleanupAfterBeanCreationFailure(beanName); 267 throw ex; 268 } 269 } 270 271 // Check if required type matches the type of the actual bean instance. 272 // 检查一下类型是否正确,不正确抛出异常,正确返回实例 273 if (requiredType != null && !requiredType.isInstance(bean)) { 274 275 276 277 try { 278 279 280 281 T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); 282 if (convertedBean == null) { 283 284 285 286 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); 287 } 288 return convertedBean; 289 } 290 catch (TypeMismatchException ex) { 291 292 293 294 if (logger.isDebugEnabled()) { 295 296 297 298 logger.debug("Failed to convert bean '" + name + "' to required type '" + 299 ClassUtils.getQualifiedName(requiredType) + "'", ex); 300 } 301 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); 302 } 303 } 304 return (T) bean; 305}
补充前面说的FactoryBean带‘&’符号问题可以在transformedBeanName看到原因
{@link org.springframework.beans.factory.support.AbstractBeanFactory#transformedBeanName}
1/** 2 * Return the bean name, stripping out the factory dereference prefix if necessary, 3 * and resolving aliases to canonical names. 4 * @param name the user-specified name 5 * @return the transformed bean name 6 */ 7protected String transformedBeanName(String name) { 8 9 10 11 // 往下跟 12 return canonicalName(BeanFactoryUtils.transformedBeanName(name)); 13} 14 15 16/** 17 * Return the actual bean name, stripping out the factory dereference 18 * prefix (if any, also stripping repeated factory prefixes if found). 19 * @param name the name of the bean 20 * @return the transformed name 21 * @see BeanFactory#FACTORY_BEAN_PREFIX 22 */ 23public static String transformedBeanName(String name) { 24 25 26 27 Assert.notNull(name, "'name' must not be null"); 28 String beanName = name; 29 // FactoryBean的beanName是带‘&’的 30 while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { 31 32 33 34 beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length()); 35 } 36 return beanName; 37}
{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean}
1/** 2 * Central method of this class: creates a bean instance, 3 * populates the bean instance, applies post-processors, etc. 4 * @see #doCreateBean 5 */ 6@Override 7protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 8 throws BeanCreationException { 9 10 11 12 13 if (logger.isDebugEnabled()) { 14 15 16 17 logger.debug("Creating instance of bean '" + beanName + "'"); 18 } 19 RootBeanDefinition mbdToUse = mbd; 20 21 // Make sure bean class is actually resolved at this point, and 22 // clone the bean definition in case of a dynamically resolved Class 23 // which cannot be stored in the shared merged bean definition. 24 // ClassLoader加载BeanDefinition 25 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); 26 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { 27 28 29 30 mbdToUse = new RootBeanDefinition(mbd); 31 mbdToUse.setBeanClass(resolvedClass); 32 } 33 34 // Prepare method overrides. 35 // 处理方法覆盖 36 // todo 涉及bean 定义中的 <lookup-method /> 和 <replaced-method />,先放过 37 try { 38 39 40 41 mbdToUse.prepareMethodOverrides(); 42 } 43 catch (BeanDefinitionValidationException ex) { 44 45 46 47 throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), 48 beanName, "Validation of method overrides failed", ex); 49 } 50 51 try { 52 53 54 55 // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. 56 // todo 让InstantiationAwareBeanPostProcessor这个后置处理器有机会返回一个代理的实例,这个ioc源码学习先放过 57 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); 58 if (bean != null) { 59 60 61 62 return bean; 63 } 64 } 65 catch (Throwable ex) { 66 67 68 69 throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, 70 "BeanPostProcessor before instantiation of bean failed", ex); 71 } 72 73 try { 74 75 76 77 // 重头戏,doCreateBean是实践执行bean创建的 78 Object beanInstance = doCreateBean(beanName, mbdToUse, args); 79 if (logger.isDebugEnabled()) { 80 81 82 83 logger.debug("Finished creating instance of bean '" + beanName + "'"); 84 } 85 return beanInstance; 86 } 87 catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { 88 89 90 91 // A previously detected exception with proper bean creation context already, 92 // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. 93 throw ex; 94 } 95 catch (Throwable ex) { 96 97 98 99 throw new BeanCreationException( 100 mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); 101 } 102}
继续跟doCreateBean
1/** 2 * Actually create the specified bean. Pre-creation processing has already happened 3 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks. 4 * <p>Differentiates between default bean instantiation, use of a 5 * factory method, and autowiring a constructor. 6 * @param beanName the name of the bean 7 * @param mbd the merged bean definition for the bean 8 * @param args explicit arguments to use for constructor or factory method invocation 9 * @return a new instance of the bean 10 * @throws BeanCreationException if the bean could not be created 11 * @see #instantiateBean 12 * @see #instantiateUsingFactoryMethod 13 * @see #autowireConstructor 14 */ 15protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 16 throws BeanCreationException { 17 18 19 20 21 // Instantiate the bean. 22 BeanWrapper instanceWrapper = null; 23 if (mbd.isSingleton()) { 24 25 26 27 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); 28 } 29 // 不是FactoryBean的情况 30 if (instanceWrapper == null) { 31 32 33 34 // 创建Bean实例,但是还没设置属性 35 instanceWrapper = createBeanInstance(beanName, mbd, args); 36 } 37 Object bean = instanceWrapper.getWrappedInstance(); 38 Class<?> beanType = instanceWrapper.getWrappedClass(); 39 if (beanType != NullBean.class) { 40 41 42 43 mbd.resolvedTargetType = beanType; 44 } 45 46 // Allow post-processors to modify the merged bean definition. 47 // 涉及到MergedBeanDefinitionPostProcessor,先跳过 todo 48 synchronized (mbd.postProcessingLock) { 49 50 51 52 if (!mbd.postProcessed) { 53 54 55 56 try { 57 58 59 60 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 61 } 62 catch (Throwable ex) { 63 64 65 66 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 67 "Post-processing of merged bean definition failed", ex); 68 } 69 mbd.postProcessed = true; 70 } 71 } 72 73 // Eagerly cache singletons to be able to resolve circular references 74 // even when triggered by lifecycle interfaces like BeanFactoryAware. 75 // 循环依赖的问题,先跳过 todo 76 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && 77 isSingletonCurrentlyInCreation(beanName)); 78 if (earlySingletonExposure) { 79 80 81 82 if (logger.isDebugEnabled()) { 83 84 85 86 logger.debug("Eagerly caching bean '" + beanName + 87 "' to allow for resolving potential circular references"); 88 } 89 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); 90 } 91 92 // Initialize the bean instance. 93 Object exposedObject = bean; 94 try { 95 96 97 98 // 关键一步,Bean属性填充 99 populateBean(beanName, mbd, instanceWrapper); 100 // 调用初始化方法,应用BeanPostProcess后置处理器 101 exposedObject = initializeBean(beanName, exposedObject, mbd); 102 } 103 catch (Throwable ex) { 104 105 106 107 if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { 108 109 110 111 throw (BeanCreationException) ex; 112 } 113 else { 114 115 116 117 throw new BeanCreationException( 118 mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); 119 } 120 } 121 122 if (earlySingletonExposure) { 123 124 125 126 Object earlySingletonReference = getSingleton(beanName, false); 127 if (earlySingletonReference != null) { 128 129 130 131 if (exposedObject == bean) { 132 133 134 135 exposedObject = earlySingletonReference; 136 } 137 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { 138 139 140 141 String[] dependentBeans = getDependentBeans(beanName); 142 Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); 143 for (String dependentBean : dependentBeans) { 144 145 146 147 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { 148 149 150 151 actualDependentBeans.add(dependentBean); 152 } 153 } 154 if (!actualDependentBeans.isEmpty()) { 155 156 157 158 throw new BeanCurrentlyInCreationException(beanName, 159 "Bean with name '" + beanName + "' has been injected into other beans [" + 160 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + 161 "] in its raw version as part of a circular reference, but has eventually been " + 162 "wrapped. This means that said other beans do not use the final version of the " + 163 "bean. This is often the result of over-eager type matching - consider using " + 164 "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); 165 } 166 } 167 } 168 } 169 170 // Register bean as disposable. 171 try { 172 173 174 175 registerDisposableBeanIfNecessary(beanName, bean, mbd); 176 } 177 catch (BeanDefinitionValidationException ex) { 178 179 180 181 throw new BeanCreationException( 182 mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); 183 } 184 185 return exposedObject; 186}
看一下关键的createBeanInstance方法,这是创建bean实例的方法:
1/** 2 * Create a new instance for the specified bean, using an appropriate instantiation strategy: 3 * factory method, constructor autowiring, or simple instantiation. 4 * @param beanName the name of the bean 5 * @param mbd the bean definition for the bean 6 * @param args explicit arguments to use for constructor or factory method invocation 7 * @return a BeanWrapper for the new instance 8 * @see #obtainFromSupplier 9 * @see #instantiateUsingFactoryMethod 10 * @see #autowireConstructor 11 * @see #instantiateBean 12 */ 13protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { 14 15 16 17 // Make sure bean class is actually resolved at this point. 18 // 确保classloader加载了此bean class 19 Class<?> beanClass = resolveBeanClass(mbd, beanName); 20 // 校验这个bean权限是否是public的 21 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { 22 23 24 25 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 26 "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); 27 } 28 29 Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); 30 if (instanceSupplier != null) { 31 32 33 34 return obtainFromSupplier(instanceSupplier, beanName); 35 } 36 37 if (mbd.getFactoryMethodName() != null) { 38 39 40 41 // 采用工厂方法实例化 42 return instantiateUsingFactoryMethod(beanName, mbd, args); 43 } 44 45 // Shortcut when re-creating the same bean... 46 // 判断是否第一次构建,第一次构建采用无参构造函数,还是构造函数依赖注入 47 boolean resolved = false; 48 boolean autowireNecessary = false; 49 if (args == null) { 50 51 52 53 synchronized (mbd.constructorArgumentLock) { 54 55 56 57 if (mbd.resolvedConstructorOrFactoryMethod != null) { 58 59 60 61 resolved = true; 62 autowireNecessary = mbd.constructorArgumentsResolved; 63 } 64 } 65 } 66 if (resolved) { 67 68 69 70 if (autowireNecessary) { 71 72 73 74 // 构造函数注入 75 return autowireConstructor(beanName, mbd, null, null); 76 } 77 else { 78 79 80 81 // 无参构造函数 82 return instantiateBean(beanName, mbd); 83 } 84 } 85 86 // Candidate constructors for autowiring? 87 // 判断是否采用有参构造函数 88 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); 89 if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || 90 mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { 91 92 93 94 // 有参构造函数依赖注入 95 return autowireConstructor(beanName, mbd, ctors, args); 96 } 97 98 // No special handling: simply use no-arg constructor. 99 // 调用无参构造函数 100 return instantiateBean(beanName, mbd); 101}
跳最简单的无参构造函数注入方法instantiateBean:
1/** 2 * Instantiate the given bean using its default constructor. 3 * @param beanName the name of the bean 4 * @param mbd the bean definition for the bean 5 * @return a BeanWrapper for the new instance 6 */ 7protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) { 8 9 10 11 try { 12 13 14 15 Object beanInstance; 16 if (System.getSecurityManager() != null) { 17 18 19 20 beanInstance = AccessController.doPrivileged( 21 (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this), 22 getAccessControlContext()); 23 } 24 else { 25 26 27 28 // 重点,实例过程 29 beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this); 30 } 31 // BeanWrapper封装一下,返回 32 BeanWrapper bw = new BeanWrapperImpl(beanInstance); 33 initBeanWrapper(bw); 34 return bw; 35 } 36 catch (Throwable ex) { 37 38 39 40 throw new BeanCreationException( 41 mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); 42 } 43}
{@link org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate}
1@Override 2public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) { 3 4 5 6 // Don't override the class with CGLIB if no overrides. 7 // 不存在方法覆写的情况,利用java的反射(JDK API)就能实现实例,方法覆写详情参考lookup-method 和 replaced-method 8 if (!bd.hasMethodOverrides()) { 9 10 11 12 Constructor<?> constructorToUse; 13 synchronized (bd.constructorArgumentLock) { 14 15 16 17 constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod; 18 if (constructorToUse == null) { 19 20 21 22 final Class<?> clazz = bd.getBeanClass(); 23 if (clazz.isInterface()) { 24 25 26 27 throw new BeanInstantiationException(clazz, "Specified class is an interface"); 28 } 29 try { 30 31 32 33 if (System.getSecurityManager() != null) { 34 35 36 37 constructorToUse = AccessController.doPrivileged( 38 (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor); 39 } 40 else { 41 42 43 44 constructorToUse = clazz.getDeclaredConstructor(); 45 } 46 bd.resolvedConstructorOrFactoryMethod = constructorToUse; 47 } 48 catch (Throwable ex) { 49 50 51 52 throw new BeanInstantiationException(clazz, "No default constructor found", ex); 53 } 54 } 55 } 56 // 调用BeanUtils对构造方法进行实例 57 return BeanUtils.instantiateClass(constructorToUse); 58 } 59 else { 60 61 62 63 // Must generate CGLIB subclass. 64 // 存在方法覆写的情况:SimpleInstantiationStrategy并没有提供实例化支持(JDK不支持), 65 // 只能通过动态代理CGLIB实现,这是一个模板方法,给子类继承实现 66 return instantiateWithMethodInjection(bd, beanName, owner); 67 } 68}
ok,前面是对bean实例过程的描述,接着继续跟一个关键点,Bean属性的填充,代码往上翻,找到{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean}找到代码populateBean(beanName, mbd, instanceWrapper);
1/** 2 * Populate the bean instance in the given BeanWrapper with the property values 3 * from the bean definition. 4 * @param beanName the name of the bean 5 * @param mbd the bean definition for the bean 6 * @param bw the BeanWrapper with bean instance 7 */ 8protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { 9 10 11 12 if (bw == null) { 13 14 15 16 // bean是否有属性 17 if (mbd.hasPropertyValues()) { 18 19 20 21 throw new BeanCreationException( 22 mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); 23 } 24 else { 25 26 27 28 // Skip property population phase for null instance. 29 return; 30 } 31 } 32 33 // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the 34 // state of the bean before properties are set. This can be used, for example, 35 // to support styles of field injection. 36 // 这个校验有点看不太懂 先跳过 todo 37 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { 38 39 40 41 for (BeanPostProcessor bp : getBeanPostProcessors()) { 42 43 44 45 if (bp instanceof InstantiationAwareBeanPostProcessor) { 46 47 48 49 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 50 // 返回false,代表不需要进行后续的属性设值,也不需要调用后置处理器 51 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { 52 53 54 55 return; 56 } 57 } 58 } 59 } 60 61 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); 62 63 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); 64 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 65 66 67 68 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); 69 // Add property values based on autowire by name if applicable. 70 // 通过beanname找到属性值 71 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { 72 73 74 75 autowireByName(beanName, mbd, bw, newPvs); 76 } 77 // Add property values based on autowire by type if applicable. 78 // 通用类型装配 79 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 80 81 82 83 autowireByType(beanName, mbd, bw, newPvs); 84 } 85 pvs = newPvs; 86 } 87 88 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); 89 boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); 90 91 if (hasInstAwareBpps || needsDepCheck) { 92 93 94 95 if (pvs == null) { 96 97 98 99 pvs = mbd.getPropertyValues(); 100 } 101 PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 102 if (hasInstAwareBpps) { 103 104 105 106 for (BeanPostProcessor bp : getBeanPostProcessors()) { 107 108 109 110 if (bp instanceof InstantiationAwareBeanPostProcessor) { 111 112 113 114 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 115 // 后置处理器的内容,很重要的方面,不过内容比较多,先跳过 116 pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); 117 if (pvs == null) { 118 119 120 121 return; 122 } 123 } 124 } 125 } 126 if (needsDepCheck) { 127 128 129 130 checkDependencies(beanName, mbd, filteredPds, pvs); 131 } 132 } 133 134 if (pvs != null) { 135 136 137 138 //设置 bean 实例的属性值 139 applyPropertyValues(beanName, mbd, bw, pvs); 140 } 141}
归纳
提示:这里对文章进行归纳:ok,本文对BeanDefinition的实例过程进行简单的学习,Spring源码比较复杂,需要慢慢积累,才能对整个框架有很好的理解,这款框架有一个很值得学习的地方是很好地做到的面向接口编程,很多地方也用到了模板方法设计模式,工厂模式,等等,很好地应用了设计模式,针对BeanDefinition创建的过程,都有提供一些接口给子类拓展,框架就显得灵活,可拓展
本文同步分享在 博客“smileNicky”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。