publicabstractclassAbstractApplicationContextextendsDefaultResourceLoaderimplementsConfigurableApplicationContext{@Overridepublicvoidrefresh()throwsBeansException,IllegalStateException{synchronized(this.startupShutdownMonitor){// Prepare this context for refreshing.// 不太重要,预刷新,做一些准备工作。记录了启动时间戳,标记为活动,非关闭状态。prepareRefresh();/**
* TODO 重点:解析xml配置文件,创建beanFactory,包装BeanDefinition
*/// Tell the subclass to refresh the internal bean factory.ConfigurableListableBeanFactorybeanFactory=obtainFreshBeanFactory();// Prepare the bean factory for use in this context.// 注册一些对事件、监听器等的支持prepareBeanFactory(beanFactory);// 钩子方法,BeanFactory创建后,对BeanFactory的自定义操作。// Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);// TODO 重点:这里调用了postProcessBeanDefinitionRegistry(registry);springboot中很多激活自动配置的注解都是通过这里导入的。// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// TODO 重点:从beanFactory中获取所有的BeanPostProcessor,优先进行getBean操作,实例化// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);// 国际化支持// Initialize message source for this context.initMessageSource();// 初始化ApplicationEventMulticaster。 如果上下文中未定义,则使用SimpleApplicationEventMulticaster。// Initialize event multicaster for this context.initApplicationEventMulticaster();// 钩子方法,springBoot中的嵌入式tomcat就是通过此方法实现的// Initialize other special beans in specific context subclasses.onRefresh();// 监听器注册// Check for listener beans and register them.registerListeners();// TODO 重点方法:完成容器中bean的实例化,及代理的生成等操作。// Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);// 完成此上下文的刷新,调用LifecycleProcessor的onRefresh()方法并发布// Last step: publish corresponding event.finishRefresh();// ... 省略无关代码}}}
publicclassDefaultListableBeanFactoryextendsAbstractAutowireCapableBeanFactoryimplementsConfigurableListableBeanFactory,BeanDefinitionRegistry,Serializable{@OverridepublicvoidpreInstantiateSingletons()throwsBeansException{// 容器中所有的beanName,循环、实例化// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.List<String>beanNames=newArrayList<>(this.beanDefinitionNames);// 循环调用,进行实例化// Trigger initialization of all non-lazy singleton beans...for(StringbeanName:beanNames){RootBeanDefinitionbd=getMergedLocalBeanDefinition(beanName);// 非抽象的、单例的、并且非懒加载的,才会在容器启动时就实例化。if(!bd.isAbstract()&&bd.isSingleton()&&!bd.isLazyInit()){if(isFactoryBean(beanName)){Objectbean=getBean(FACTORY_BEAN_PREFIX+beanName);if(beaninstanceofFactoryBean){finalFactoryBean<?>factory=(FactoryBean<?>)bean;booleanisEagerInit;if(System.getSecurityManager()!=null&&factoryinstanceofSmartFactoryBean){isEagerInit=AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>)factory)::isEagerInit,getAccessControlContext());}else{isEagerInit=(factoryinstanceofSmartFactoryBean&&((SmartFactoryBean<?>)factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}}else{getBean(beanName);}}}}}
publicabstractclassAbstractBeanFactoryextendsFactoryBeanRegistrySupportimplementsConfigurableBeanFactory{@SuppressWarnings("unchecked")protected<T>TdoGetBean(finalStringname,@NullablefinalClass<T>requiredType,@NullablefinalObject[]args,booleantypeCheckOnly)throwsBeansException{/*
TODO 重要程度 5
单例实例第一次创建bean入口,这里的getSingleton方法中,调用了参数中匿名对象的getObject()
在bean创建完成后,将bean放入到一级缓存,并从二三级缓存中移除:addSingleton(beanName, singletonObject);
*/// Create bean instance.if(mbd.isSingleton()){sharedInstance=getSingleton(beanName,()->{try{//创建Bean实例returncreateBean(beanName,mbd,args);}catch(BeansExceptionex){// Explicitly remove instance from singleton cache: It might have been put there// eagerly by the creation process, to allow for circular reference resolution.// Also remove any beans that received a temporary reference to the bean.destroySingleton(beanName);throwex;}});/*
TODO 重要程度 5
如果bean不是FactoryBean类型或者beanName以&开头,则直接返回。
否则调用FactoryBean的getObject(),且将返回的bean替换为getObject()的返回值。
FactoryBean接口很重要,具体应用场景见FactoryBean接口注释。
*/bean=getObjectForBeanInstance(sharedInstance,name,beanName,mbd);}}}
publicabstractclassAbstractAutowireCapableBeanFactoryextendsAbstractBeanFactoryimplementsAutowireCapableBeanFactory{@OverrideprotectedObjectcreateBean(StringbeanName,RootBeanDefinitionmbd,@NullableObject[]args)throwsBeanCreationException{// ...省略无关代码// 这里如果满足条件,会调用 InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()和// BeanPostProcessor.postProcessAfterInitialization(),直接返回。// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.Objectbean=resolveBeforeInstantiation(beanName,mbdToUse);if(bean!=null){returnbean;}// ...省略无关代码//创建Bean实例ObjectbeanInstance=doCreateBean(beanName,mbdToUse,args);if(logger.isTraceEnabled()){logger.trace("Finished creating instance of bean '"+beanName+"'");}returnbeanInstance;}}
publicabstractclassAbstractAutowireCapableBeanFactoryextendsAbstractBeanFactoryimplementsAutowireCapableBeanFactory{@NullableprotectedObjectresolveBeforeInstantiation(StringbeanName,RootBeanDefinitionmbd){Objectbean=null;// 如果满足条件,会在这里通过InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()进行实例化。// 如果此方法最终返回的值不为空,则会调用所有BeanPostProcessor的postProcessAfterInitialization(),// 标记是否已经提前实例化了bean,然后返回。if(!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)){// Make sure bean class is actually resolved at this point.if(!mbd.isSynthetic()&&hasInstantiationAwareBeanPostProcessors()){Class<?>targetType=determineTargetType(beanName,mbd);if(targetType!=null){bean=applyBeanPostProcessorsBeforeInstantiation(targetType,beanName);if(bean!=null){bean=applyBeanPostProcessorsAfterInitialization(bean,beanName);}}}mbd.beforeInstantiationResolved=(bean!=null);}returnbean;}}
publicabstractclassAbstractAutowireCapableBeanFactoryextendsAbstractBeanFactoryimplementsAutowireCapableBeanFactory{protectedObjectdoCreateBean(finalStringbeanName,finalRootBeanDefinitionmbd,final@NullableObject[]args)throwsBeanCreationException{// Instantiate the bean.BeanWrapperinstanceWrapper=null;if(mbd.isSingleton()){instanceWrapper=this.factoryBeanInstanceCache.remove(beanName);}// 创建bean实例if(instanceWrapper==null){instanceWrapper=createBeanInstance(beanName,mbd,args);}// 省略无关代码...// Allow post-processors to modify the merged bean definition.synchronized(mbd.postProcessingLock){if(!mbd.postProcessed){applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName);// 省略无关代码...mbd.postProcessed=true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.booleanearlySingletonExposure=(mbd.isSingleton()&&this.allowCircularReferences&&isSingletonCurrentlyInCreation(beanName));if(earlySingletonExposure){// 省略无关代码...addSingletonFactory(beanName,()->getEarlyBeanReference(beanName,mbd,bean));}// Initialize the bean instance.ObjectexposedObject=bean;// 依赖注入,类似属性上带有@Autowired注解的,都会在这里进行依赖注入populateBean(beanName,mbd,instanceWrapper);// 初始化beanexposedObject=initializeBean(beanName,exposedObject,mbd);// 省略无关代码...//注册bean的销毁方法registerDisposableBeanIfNecessary(beanName,bean,mbd);returnexposedObject;}}
publicabstractclassAbstractAutowireCapableBeanFactoryextendsAbstractBeanFactoryimplementsAutowireCapableBeanFactory{protectedBeanWrappercreateBeanInstance(StringbeanName,RootBeanDefinitionmbd,@NullableObject[]args){// Make sure bean class is actually resolved at this point.Class<?>beanClass=resolveBeanClass(mbd,beanName);// 只有public修饰的class才可以被创建if(beanClass!=null&&!Modifier.isPublic(beanClass.getModifiers())&&!mbd.isNonPublicAccessAllowed()){thrownewBeanCreationException(mbd.getResourceDescription(),beanName,"Bean class isn't public, and non-public access not allowed: "+beanClass.getName());}// 通过BeanDefinition中的回调,来创建bean实例。一般不会走到这个条件里。Supplier<?>instanceSupplier=mbd.getInstanceSupplier();if(instanceSupplier!=null){returnobtainFromSupplier(instanceSupplier,beanName);}// 使用FactoryMethod创建bean实例。factory-method标签属性,或者@Bean注解标注的方法,会从这里创建实例。if(mbd.getFactoryMethodName()!=null){returninstantiateUsingFactoryMethod(beanName,mbd,args);}// 重新创建相同bean,会走到这里。// Shortcut when re-creating the same bean...booleanresolved=false;booleanautowireNecessary=false;if(args==null){synchronized(mbd.constructorArgumentLock){if(mbd.resolvedConstructorOrFactoryMethod!=null){resolved=true;autowireNecessary=mbd.constructorArgumentsResolved;}}}if(resolved){if(autowireNecessary){returnautowireConstructor(beanName,mbd,null,null);}else{returninstantiateBean(beanName,mbd);}}// 判断是否是通过构造函数注入参数,如果是,则通过@Autowired标注的构造函数实例化。// Candidate constructors for autowiring?Constructor<?>[]ctors=determineConstructorsFromBeanPostProcessors(beanClass,beanName);if(ctors!=null||mbd.getResolvedAutowireMode()==AUTOWIRE_CONSTRUCTOR||mbd.hasConstructorArgumentValues()||!ObjectUtils.isEmpty(args)){returnautowireConstructor(beanName,mbd,ctors,args);}// 默认构造的首选函数// Preferred constructors for default construction?ctors=mbd.getPreferredConstructors();if(ctors!=null){returnautowireConstructor(beanName,mbd,ctors,null);}// 使用无参构造实例化bean,实际大多数bean的实例化,都是走的这个方法。// No special handling: simply use no-arg constructor.returninstantiateBean(beanName,mbd);}}
publicclassSimpleInstantiationStrategyimplementsInstantiationStrategy{// 第一步@OverridepublicObjectinstantiate(RootBeanDefinitionbd,@NullableStringbeanName,BeanFactoryowner){// Don't override the class with CGLIB if no overrides.if(!bd.hasMethodOverrides()){// 省略无关代码...// 获取无参构造函数constructorToUse=clazz.getDeclaredConstructor();bd.resolvedConstructorOrFactoryMethod=constructorToUse;// 省略无关代码...// TODO 实例化beanreturnBeanUtils.instantiateClass(constructorToUse);}else{// Must generate CGLIB subclass.returninstantiateWithMethodInjection(bd,beanName,owner);}}}publicabstractclassBeanUtils{// 第二步publicstatic<T>TinstantiateClass(Constructor<T>ctor,Object...args)throwsBeanInstantiationException{Assert.notNull(ctor,"Constructor must not be null");// 设置构造函数setAccessible=true// newInstance:反射调用构造函数,创建bean对象。ReflectionUtils.makeAccessible(ctor);return(KotlinDetector.isKotlinReflectPresent()&&KotlinDetector.isKotlinType(ctor.getDeclaringClass())?KotlinDelegate.instantiateClass(ctor,args):ctor.newInstance(args));// 省略无关代码...}}
publicclassAutowiredAnnotationBeanPostProcessorextendsInstantiationAwareBeanPostProcessorAdapterimplementsMergedBeanDefinitionPostProcessor,PriorityOrdered,BeanFactoryAware{/**
* 在依赖注入之前,调用此方法搜集需要依赖注入的类的信息,并封装成InjectionMetadata对象,缓存到当前BeanPostProcessor实例中。
*
* @param beanDefinition the merged bean definition for the bean
* @param beanType the actual type of the managed bean instance
* @param beanName the name of the bean
*/@OverridepublicvoidpostProcessMergedBeanDefinition(RootBeanDefinitionbeanDefinition,Class<?>beanType,StringbeanName){// 查找带有Autowired注解的成员的属性信息信息。InjectionMetadatametadata=findAutowiringMetadata(beanName,beanType,null);metadata.checkConfigMembers(beanDefinition);}}
publicclassAutowiredAnnotationBeanPostProcessorextendsInstantiationAwareBeanPostProcessorAdapterimplementsMergedBeanDefinitionPostProcessor,PriorityOrdered,BeanFactoryAware{// 无参构造函数中添加了对应注解的支持publicAutowiredAnnotationBeanPostProcessor(){// 初始化autowiredAnnotationTypes,这里添加了Autowired Value Inject注解的支持this.autowiredAnnotationTypes.add(Autowired.class);this.autowiredAnnotationTypes.add(Value.class);try{this.autowiredAnnotationTypes.add((Class<?extendsAnnotation>)ClassUtils.forName("javax.inject.Inject",AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");}catch(ClassNotFoundExceptionex){// JSR-330 API not available:simply skip.}}privateInjectionMetadatabuildAutowiringMetadata(finalClass<?>clazz){List<InjectionMetadata.InjectedElement>elements=newArrayList<>();Class<?>targetClass=clazz;do{finalList<InjectionMetadata.InjectedElement>currElements=newArrayList<>();// 循环所有的字段,并以此字段为参数,执行回调。ReflectionUtils.doWithLocalFields(targetClass,field->{// 查找当前带有autowiredAnnotationTypes中支持的注解的字段。AnnotationAttributesann=findAutowiredAnnotation(field);if(ann!=null){if(Modifier.isStatic(field.getModifiers())){if(logger.isInfoEnabled()){logger.info("Autowired annotation is not supported on static fields: "+field);}return;}booleanrequired=determineRequiredStatus(ann);currElements.add(newAutowiredFieldElement(field,required));}});// 循环所有的方法,并以此方法为参数,执行回调。ReflectionUtils.doWithLocalMethods(targetClass,method->{MethodbridgedMethod=BridgeMethodResolver.findBridgedMethod(method);if(!BridgeMethodResolver.isVisibilityBridgeMethodPair(method,bridgedMethod)){return;}// 查找当前带有autowiredAnnotationTypes中支持的注解的方法。AnnotationAttributesann=findAutowiredAnnotation(bridgedMethod);if(ann!=null&&method.equals(ClassUtils.getMostSpecificMethod(method,clazz))){if(Modifier.isStatic(method.getModifiers())){if(logger.isInfoEnabled()){logger.info("Autowired annotation is not supported on static methods: "+method);}return;}if(method.getParameterCount()==0){if(logger.isInfoEnabled()){logger.info("Autowired annotation should only be used on methods with parameters: "+method);}}booleanrequired=determineRequiredStatus(ann);PropertyDescriptorpd=BeanUtils.findPropertyForMethod(bridgedMethod,clazz);currElements.add(newAutowiredMethodElement(method,required,pd));}});elements.addAll(0,currElements);targetClass=targetClass.getSuperclass();}while(targetClass!=null&&targetClass!=Object.class);returnnewInjectionMetadata(clazz,elements);}@NullableprivateAnnotationAttributesfindAutowiredAnnotation(AccessibleObjectao){if(ao.getAnnotations().length>0){// autowiring annotations have to be local// autowiredAnnotationTypes中的注解值,是在无参构造函数中设置的。for(Class<?extendsAnnotation>type:this.autowiredAnnotationTypes){AnnotationAttributesattributes=AnnotatedElementUtils.getMergedAnnotationAttributes(ao,type);if(attributes!=null){returnattributes;}}}returnnull;}}
publicclassInitDestroyAnnotationBeanPostProcessorimplementsDestructionAwareBeanPostProcessor,MergedBeanDefinitionPostProcessor,PriorityOrdered,Serializable{privateLifecycleMetadatafindLifecycleMetadata(Class<?>clazz){if(this.lifecycleMetadataCache==null){// Happens after deserialization, during destruction...returnbuildLifecycleMetadata(clazz);}// Quick check on the concurrent map first, with minimal locking.LifecycleMetadatametadata=this.lifecycleMetadataCache.get(clazz);if(metadata==null){synchronized(this.lifecycleMetadataCache){metadata=this.lifecycleMetadataCache.get(clazz);if(metadata==null){// 上面代码是缓存,这里加锁的技巧,先无锁尝试,尝试失败再加锁。// 细节:加锁中需要再次尝试获取一次。metadata=buildLifecycleMetadata(clazz);this.lifecycleMetadataCache.put(clazz,metadata);}returnmetadata;}}returnmetadata;}}
publicclassInitDestroyAnnotationBeanPostProcessorimplementsDestructionAwareBeanPostProcessor,MergedBeanDefinitionPostProcessor,PriorityOrdered,Serializable{privateLifecycleMetadatabuildLifecycleMetadata(finalClass<?>clazz){List<LifecycleElement>initMethods=newArrayList<>();List<LifecycleElement>destroyMethods=newArrayList<>();Class<?>targetClass=clazz;do{finalList<LifecycleElement>currInitMethods=newArrayList<>();finalList<LifecycleElement>currDestroyMethods=newArrayList<>();// 循环遍历所有的方法,查找初始化、销毁方法,如果查找到,就封装为LifecycleMetadata返回。ReflectionUtils.doWithLocalMethods(targetClass,method->{if(this.initAnnotationType!=null&&method.isAnnotationPresent(this.initAnnotationType)){LifecycleElementelement=newLifecycleElement(method);currInitMethods.add(element);if(logger.isTraceEnabled()){logger.trace("Found init method on class ["+clazz.getName()+"]: "+method);}}if(this.destroyAnnotationType!=null&&method.isAnnotationPresent(this.destroyAnnotationType)){currDestroyMethods.add(newLifecycleElement(method));if(logger.isTraceEnabled()){logger.trace("Found destroy method on class ["+clazz.getName()+"]: "+method);}}});// 添加初始化、销毁方法initMethods.addAll(0,currInitMethods);destroyMethods.addAll(currDestroyMethods);targetClass=targetClass.getSuperclass();}while(targetClass!=null&&targetClass!=Object.class);// 将上面步骤搜集到的初始化、销毁方法封装起来返回。returnnewLifecycleMetadata(clazz,initMethods,destroyMethods);}}
publicabstractclassAbstractBeanFactoryextendsFactoryBeanRegistrySupportimplementsConfigurableBeanFactory{protectedvoidregisterDisposableBeanIfNecessary(StringbeanName,Objectbean,RootBeanDefinitionmbd){AccessControlContextacc=(System.getSecurityManager()!=null?getAccessControlContext():null);// BeanDefinition非多例,并且需要销毁。if(!mbd.isPrototype()&&requiresDestruction(bean,mbd)){if(mbd.isSingleton()){// Register a DisposableBean implementation that performs all destruction// work for the given bean: DestructionAwareBeanPostProcessors,// DisposableBean interface, custom destroy method.// 注册bean的销毁前调用的方法registerDisposableBean(beanName,newDisposableBeanAdapter(bean,beanName,mbd,getBeanPostProcessors(),acc));}else{// A bean with a custom scope...Scopescope=this.scopes.get(mbd.getScope());if(scope==null){thrownewIllegalStateException("No Scope registered for scope name '"+mbd.getScope()+"'");}scope.registerDestructionCallback(beanName,newDisposableBeanAdapter(bean,beanName,mbd,getBeanPostProcessors(),acc));}}}}publicclassDefaultSingletonBeanRegistryextendsSimpleAliasRegistryimplementsSingletonBeanRegistry{publicvoidregisterDisposableBean(StringbeanName,DisposableBeanbean){synchronized(this.disposableBeans){this.disposableBeans.put(beanName,bean);}}}