源码:
@Override3.publicvoidrefresh()throws BeansException, IllegalStateException {synchronized(this.startupShutdownMonitor){// Prepare this context for refreshing.//容器准备刷新prepareRefresh();// Tell the subclass to refresh the internal bean factory.//Spring解析xml配置文件将要创建的所有bean的配置信息并保存起来,创建所有bean工厂,把xml配置文件里每一个bean配置解析读取保存起来,方便下一次使用
ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();// Prepare the bean factory for use in this context.//准备下beanFactoryprepareBeanFactory(beanFactory);try{// Allows post-processing of the bean factory in context subclasses.//bean工厂的后置处理器postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.//执行bean工厂的后置处理器注册invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.//注册bean工厂的后置处理器(Spring自己的组件的后置处理器)registerBeanPostProcessors(beanFactory);// Initialize message source for this context.//支持国际化功能initMessageSource();// Initialize event multicaster for this context.//初始化事件转换器initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.//留给子类的方法onRefresh();// Check for listener beans and register them.//注册监听器(内部的)registerListeners();// Instantiate all remaining (non-lazy-init) singletons.//初始化所有单实例bean的地方finishBeanFactoryInitialization(beanFactory);finishRefresh();}catch(BeansException ex){if(logger.isWarnEnabled()){
logger.warn("Exception encountered during context initialization - "+"cancelling refresh attempt: "+ ex);}destroyBeans();cancelRefresh(ex);throw ex;}finally{resetCommonCaches();}}}
源码:
4.protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){// Initialize conversion service for this context.//初始化类型转换的组件服务,自定义类型转换if(beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME)&&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)){
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));}// Register a default embedded value resolver if no bean post-processor// (such as a PropertyPlaceholderConfigurer bean) registered any before:// at this point, primarily for resolution in annotation attribute values.if(!beanFactory.hasEmbeddedValueResolver()){
beanFactory.addEmbeddedValueResolver(newStringValueResolver(){@Overridepublic String resolveStringValue(String strVal){returngetEnvironment().resolvePlaceholders(strVal);}});}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.//初始化加载时WeaverAware
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class,false,false);for(String weaverAwareName : weaverAwareNames){getBean(weaverAwareName);}// Stop using the temporary ClassLoader for type matching.//设置临时的类加载器
beanFactory.setTempClassLoader(null);// Allow for caching all bean definition metadata, not expecting further changes.//冻结配置,别人无法修改
beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.//预初始化所有单实例
beanFactory.preInstantiateSingletons();}
preInstantiateSingletons()//预初始化所有单实例
源码:
@OverridepublicvoidpreInstantiateSingletons()throws BeansException {if(this.logger.isDebugEnabled()){this.logger.debug("Pre-instantiating singletons in "+this);}// 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<String>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...//按顺序创建beanfor(String beanName : beanNames){//根据beanId获取到bean的定义信息
RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);//判断bean是单实例的,并且不是抽象的,并且不是懒加载的if(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){//是否是一个实现了FactoryBean接口的beanif(isFactoryBean(beanName)){final FactoryBean<?> factory =(FactoryBean<?>)getBean(FACTORY_BEAN_PREFIX + beanName);boolean isEagerInit;if(System.getSecurityManager()!= null && factory instanceofSmartFactoryBean){
isEagerInit = AccessController.doPrivileged(newPrivilegedAction<Boolean>(){@Overridepublic Boolean run(){return((SmartFactoryBean<?>) factory).isEagerInit();}},getAccessControlContext());}else{
isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}else{//创建bean的细节对象getBean(beanName);}}}}
源码:
@SuppressWarnings("unchecked")protected<T> T doGetBean(final String name,final Class<T> requiredType,final Object[] args,boolean typeCheckOnly)throws BeansException {//拿到bean名final String beanName =transformedBeanName(name);
Object bean;// Eagerly check singleton cache for manually registered singletons.//先从已经注册的单实例bean缓存里有没有这个bean,第一次创建bean是没有的
Object sharedInstance =getSingleton(beanName);if(sharedInstance != null && args == null){if(logger.isDebugEnabled()){if(isSingletonCurrentlyInCreation(beanName)){
logger.debug("Returning eagerly cached instance of singleton bean '"+ beanName +"' that is not fully initialized yet - a consequence of a circular reference");}else{
logger.debug("Returning cached instance of singleton bean '"+ beanName +"'");}}
bean =getObjectForBeanInstance(sharedInstance, name, beanName, null);}else{// Fail if we're already creating this bean instance:// We're assumably within a circular reference.if(isPrototypeCurrentlyInCreation(beanName)){thrownewBeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.//拿父工厂
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// Not found -> check parent.
String nameToLookup =originalBeanName(name);if(args != null){// Delegation to parent with explicit args.return(T) parentBeanFactory.getBean(nameToLookup, args);}else{// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}}//判断doGetBean(name, null, null, false),最后的参数if(!typeCheckOnly){//标记bean已经创建了markBeanAsCreated(beanName);}try{//获取合并的本地bean信息,总是获取到当前bean的定义信息final RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.//拿到创建当前bean之前需要提前创建的bean(depends-on)
String[] dependsOn = mbd.getDependsOn();//如果有就循环创建if(dependsOn != null){for(String dep : dependsOn){if(isDependent(beanName, dep)){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Circular depends-on relationship between '"+ beanName +"' and '"+ dep +"'");}registerDependentBean(dep, beanName);getBean(dep);}}// Create bean instance.//如果DependsOn是单例的,创建bean实例if(mbd.isSingleton()){
sharedInstance =getSingleton(beanName,newObjectFactory<Object>(){@Overridepublic Object getObject()throws BeansException {try{//bean的创建returncreateBean(beanName, mbd, args);}catch(BeansException ex){// 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);throw ex;}}});
bean =getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}elseif(mbd.isPrototype()){// It's a prototype -> create a new instance.
Object prototypeInstance = null;try{beforePrototypeCreation(beanName);
prototypeInstance =createBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}
bean =getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}else{
String scopeName = mbd.getScope();final Scope scope =this.scopes.get(scopeName);if(scope == null){thrownewIllegalStateException("No Scope registered for scope name '"+ scopeName +"'");}try{
Object scopedInstance = scope.get(beanName,newObjectFactory<Object>(){@Overridepublic Object getObject()throws BeansException {beforePrototypeCreation(beanName);try{returncreateBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}}});
bean =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch(IllegalStateException ex){thrownewBeanCreationException(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);}}}catch(BeansException ex){cleanupAfterBeanCreationFailure(beanName);throw ex;}}// Check if required type matches the type of the actual bean instance.if(requiredType != null && bean != null &&!requiredType.isInstance(bean)){try{returngetTypeConverter().convertIfNecessary(bean, requiredType);}catch(TypeMismatchException ex){if(logger.isDebugEnabled()){
logger.debug("Failed to convert bean '"+ name +"' to required type '"+
ClassUtils.getQualifiedName(requiredType)+"'", ex);}thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return(T) bean;}
getSingleton()//如果DependsOn是单例的,创建bean实例
源码:
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory){
Assert.notNull(beanName,"'beanName' must not be null");synchronized(this.singletonObjects){//先从一个地方将一个将bean,get出来
Object singletonObject =this.singletonObjects.get(beanName);if(singletonObject == null){if(this.singletonsCurrentlyInDestruction){thrownewBeanCreationNotAllowedException(beanName,"Singleton bean creation not allowed while singletons of this factory are in destruction "+"(Do not request a bean from a BeanFactory in a destroy method implementation!)");}if(logger.isDebugEnabled()){
logger.debug("Creating shared instance of singleton bean '"+ beanName +"'");}//创建bean之前beforeSingletonCreation(beanName);boolean newSingleton =false;boolean recordSuppressedExceptions =(this.suppressedExceptions == null);if(recordSuppressedExceptions){this.suppressedExceptions =newLinkedHashSet<Exception>();}try{//利用反射,bean创建
singletonObject = singletonFactory.getObject();
newSingleton =true;}catch(IllegalStateException ex){// Has the singleton object implicitly appeared in the meantime ->// if yes, proceed with it since the exception indicates that state.
singletonObject =this.singletonObjects.get(beanName);if(singletonObject == null){throw ex;}}catch(BeanCreationException ex){if(recordSuppressedExceptions){for(Exception suppressedException :this.suppressedExceptions){
ex.addRelatedCause(suppressedException);}}throw ex;}finally{if(recordSuppressedExceptions){this.suppressedExceptions = null;}afterSingletonCreation(beanName);}if(newSingleton){//添加创建的bean,单实例addSingleton(beanName, singletonObject);}}return(singletonObject != NULL_OBJECT ? singletonObject : null);}}
singletonObjects()//先从一个地方将一个将bean,get出来
源码:
//IOC容器之一:保存单实例bean的地方publicclassDefaultSingletonBeanRegistryextendsSimpleAliasRegistryimplementsSingletonBeanRegistry{//缓存所有单实例的对象,按照对象的名字创建对象的实例/** Cache of singleton objects: bean name --> bean instance */privatefinal Map<String, Object> singletonObjects =newConcurrentHashMap<String, Object>(256);}