// Keep a snapshot of the request attributes in case of an include, // to be able to restore the original attributes after the include. // 当include请求时对request的Attribute做快照备份 Map<String, Object> attributesSnapshot = null; if (WebUtils.isIncludeRequest(request)) { attributesSnapshot = newHashMap<>(); Enumeration<?> attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { StringattrName= (String) attrNames.nextElement(); if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) { attributesSnapshot.put(attrName, request.getAttribute(attrName)); } } }
// Make framework objects available to handlers and view objects. // 设置Spring框架中的常用对象到request属性中,这四个属性会在handler和view中使用 request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext()); request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver); request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver); request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
// FlashMap的相关配置,主要用于Redirect转发时参数的传递,此处有一个应用场景:如果post请求是提交表单,提交完之后redirect到一个显示订单的页面, // 此时需要知道一些订单的信息,但redirect本身没有提交参数的功能,如果想传递参数,那么就必须要写到url,而url有长度的限制同时还容易对外暴露,此时 // 可以使用flashMap来传递参数, if (this.flashMapManager != null) { FlashMapinputFlashMap=this.flashMapManager.retrieveAndUpdate(request, response); if (inputFlashMap != null) { request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap)); } request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, newFlashMap()); request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager); } try { // 执行请求的分发 doDispatch(request, response); } finally { // 异步处理相关 if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) { // Restore the original attribute snapshot, in case of an include. // 还原request快照的属性 if (attributesSnapshot != null) { restoreAttributesAfterInclude(request, attributesSnapshot); } } } }
// Determine handler for the current request. // 获得请求对应的HandlerExecutionChain对象(HandlerMethod和HandlerInterceptor拦截器们) mappedHandler = getHandler(processedRequest); // 如果获取不到,则根据配置抛出异常或返回404错误 if (mappedHandler == null) { noHandlerFound(processedRequest, response); return; }
// Determine handler adapter for the current request. // 获得当前handler对应的HandlerAdapter对象 HandlerAdapterha= getHandlerAdapter(mappedHandler.getHandler());
// Process last-modified header, if supported by the handler. // 处理GET、HEAD请求的Last-Modified,当浏览器第一次跟服务器请求资源时,服务器会在返回的请求头里包含一个last_modified的属性, // 代表资源最后时什么时候修改的,在浏览器以后发送请求的时候,会同时发送之前接收到的Last_modified.服务器接收到带last_modified的请求后, // 会跟实际资源的最后修改时间做对比,如果过期了返回新的资源,否则直接返回304表示未过期,直接使用之前缓存的结果即可 Stringmethod= request.getMethod(); booleanisGet="GET".equals(method); if (isGet || "HEAD".equals(method)) { // 获取请求中服务器端最后被修改时间 longlastModified= ha.getLastModified(request, mappedHandler.getHandler()); if (newServletWebRequest(request, response).checkNotModified(lastModified) && isGet) { return; } }
// 如果开启探测功能,则扫描已注册的HandlerMapping的bean,添加到handlerMappings中 if (this.detectAllHandlerMappings) { // Find all HandlerMappings in the ApplicationContext, including ancestor contexts. // 扫描已注册的handlerMapping的bean Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false); // 添加到handlerMappings中,并进行排序 if (!matchingBeans.isEmpty()) { this.handlerMappings = newArrayList<>(matchingBeans.values()); // We keep HandlerMappings in sorted order. AnnotationAwareOrderComparator.sort(this.handlerMappings); } } // 如果关闭探测功能,则获取Bean名称为handlerMapping对应的bean,将其添加到handlerMappings else { try { // HANDLER_MAPPING_BEAN_NAME = "handlerMapping" HandlerMappinghm= context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); this.handlerMappings = Collections.singletonList(hm); } catch (NoSuchBeanDefinitionException ex) { // Ignore, we'll add a default HandlerMapping later. } }
// Ensure we have at least one HandlerMapping, by registering // a default HandlerMapping if no other mappings are found. // 如果未获得到,则获得默认配置的handlerMapping类 if (this.handlerMappings == null) { this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class); if (logger.isTraceEnabled()) { logger.trace("No HandlerMappings declared for servlet '" + getServletName() + "': using default strategies from DispatcherServlet_test.properties"); } } }
if (this.detectAllHandlerAdapters) { // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts. Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false); if (!matchingBeans.isEmpty()) { this.handlerAdapters = newArrayList<>(matchingBeans.values()); // We keep HandlerAdapters in sorted order. AnnotationAwareOrderComparator.sort(this.handlerAdapters); } } else { try { // HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter" HandlerAdapterha= context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class); this.handlerAdapters = Collections.singletonList(ha); } catch (NoSuchBeanDefinitionException ex) { // Ignore, we'll add a default HandlerAdapter later. } }
// Ensure we have at least some HandlerAdapters, by registering // default HandlerAdapters if no other adapters are found. // 如果未获得到,则获得默认配置的HandlerAdapter类,HttpRequestHandlerAdapter,SimpleControllerHandlerAdapter,RequestMappingHandlerAdapter if (this.handlerAdapters == null) { this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class); if (logger.isTraceEnabled()) { logger.trace("No HandlerAdapters declared for servlet '" + getServletName() + "': using default strategies from DispatcherServlet_test.properties"); } } }
// 自动扫描handlerExceptionResolver类型的bean if (this.detectAllHandlerExceptionResolvers) { // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts. Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false); if (!matchingBeans.isEmpty()) { this.handlerExceptionResolvers = newArrayList<>(matchingBeans.values()); // We keep HandlerExceptionResolvers in sorted order. AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers); } } // 获取名字为HANDLER_EXCEPTION_RESOLVER_BEAN_NAME的bean else { try { // HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver" HandlerExceptionResolverher= context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class); this.handlerExceptionResolvers = Collections.singletonList(her); } catch (NoSuchBeanDefinitionException ex) { // Ignore, no HandlerExceptionResolver is fine too. } }
// Ensure we have at least some HandlerExceptionResolvers, by registering // default HandlerExceptionResolvers if no other resolvers are found. // 如果未获得到,则获取默认配置的handlerExceptionResolver类,ExceptionHandlerExceptionResolver,ResponseStatusExceptionResolver,DefaultHandlerExceptionResolver if (this.handlerExceptionResolvers == null) { this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class); if (logger.isTraceEnabled()) { logger.trace("No HandlerExceptionResolvers declared in servlet '" + getServletName() + "': using default strategies from DispatcherServlet_test.properties"); } } }
/// 自动扫描 ViewResolver 类型的 Bean if (this.detectAllViewResolvers) { // Find all ViewResolvers in the ApplicationContext, including ancestor contexts. Map<String, ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false); if (!matchingBeans.isEmpty()) { this.viewResolvers = newArrayList<>(matchingBeans.values()); // We keep ViewResolvers in sorted order. AnnotationAwareOrderComparator.sort(this.viewResolvers); } } // 获得名字为VIEW_RESOLVER_BEAN_NAME的bean else { try { // VIEW_RESOLVER_BEAN_NAME = "viewResolver" ViewResolvervr= context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class); this.viewResolvers = Collections.singletonList(vr); } catch (NoSuchBeanDefinitionException ex) { // Ignore, we'll add a default ViewResolver later. } }
// Ensure we have at least one ViewResolver, by registering // a default ViewResolver if no other resolvers are found. // 如果未获得到,则获取默认配置的ViewResolver对象 if (this.viewResolvers == null) { this.viewResolvers = getDefaultStrategies(context, ViewResolver.class); if (logger.isTraceEnabled()) { logger.trace("No ViewResolvers declared for servlet '" + getServletName() + "': using default strategies from DispatcherServlet_test.properties"); } } }
// org.springframework.web.context.ContextLoaderListener#contextInitialized publicvoidcontextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); } public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { // web.xml中存在多次ContextLoader定义 thrownewIllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); }
servletContext.log("Initializing Spring root WebApplicationContext"); Loglogger= LogFactory.getLog(ContextLoader.class); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } longstartTime= System.currentTimeMillis();
try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { // 初始化context,第一次执行的时候获取到一个root webApplicationcontext this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContextcwac= (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContextparent= loadParentContext(servletContext); cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } } // 将创建的context对象记录在servletContext中,创建并且准备好了spring容器 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
protectedvoidconfigureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -> assign a more useful id based on available information StringidParam= sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam); } else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath())); } }
// 设置环境变量 // The wac environment's #initPropertySources will be called in any case when the context // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironmentenv= wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); }
// 启动容器前设置上下文信息 customizeContext(sc, wac); // 启动 Spring 容器 wac.refresh(); }
if (logger.isDebugEnabled()) { Stringvalue=this.enableLoggingRequestDetails ? "shown which may lead to unsafe logging of potentially sensitive data" : "masked to prevent unsafe logging of potentially sensitive data"; logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails + "': request parameters and headers will be " + value); }
if (logger.isInfoEnabled()) { logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms"); } }
// 如果构造方法中已经传入webApplicationContext属性,则直接使用 // 此方式主要用于servlet3.0之后的环境,也就是说可以通过ServletContext.addServlet的方法注册servlet,此时就可以在创建FrameworkServlet和 // 其子类的时候通过构造方法传递已经准备好的webApplicationContext if (this.webApplicationContext != null) { // A context instance was injected at construction time -> use it wac = this.webApplicationContext; // 如果是ConfigurationWebApplicationContext类型,并且未激活,则进行初始化 if (wac instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContextcwac= (ConfigurableWebApplicationContext) wac; // 未激活 if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> set // the root application context (if any; may be null) as the parent cwac.setParent(rootContext); } // 配置和刷新上下文环境 configureAndRefreshWebApplicationContext(cwac); } } } // 从servletContext获取对应的webApplicationContext对象 // 此方式需要在配置Servlet的时候将servletContext中的webApplicationContext的name配置到contextAttribute属性就可以 /* <servlet> <servlet-name>mvc-test</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--SpringMVC配置文件--> <init-param> <param-name>contextAttribute</param-name> <param-value>val</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> */ if (wac == null) { // No context instance was injected at construction time -> see if one // has been registered in the servlet context. If one exists, it is assumed // that the parent context (if any) has already been set and that the // user has performed any initialization such as setting the context id wac = findWebApplicationContext(); } // 当前面两种方式都无效的情况下会创建一个webApplicationContext对象,一般情况下都是使用这样的方式 if (wac == null) { // No context instance is defined for this servlet -> create a local one wac = createWebApplicationContext(rootContext); }
// 将contextRefreshedEvent事件没有触发时调用此方法,模板方法,可以在子类重写 if (!this.refreshEventReceived) { // Either the context is not a ConfigurableApplicationContext with refresh // support or the context injected at construction time had already been // refreshed -> trigger initial onRefresh manually here. synchronized (this.onRefreshMonitor) { onRefresh(wac); } }
// 将applicationContext设置到servletContext中 if (this.publishContext) { // Publish the context as a servlet context attribute. StringattrName= getServletContextAttributeName(); getServletContext().setAttribute(attrName, wac); }
protectedvoidconfigureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) { // 如果wac使用了默认编号,则重新设置id属性 if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -> assign a more useful id based on available information // 使用contextId属性 if (this.contextId != null) { wac.setId(this.contextId); } // 自动生成 else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName()); } }
// The wac environment's #initPropertySources will be called in any case when the context // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh // 获取环境对象并且添加相关的属性 ConfigurableEnvironmentenv= wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig()); }
protectedvoidpublishEvent(Object event, @Nullable ResolvableType eventType) { Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary // 如果有必要,将事件装饰为 applicationEvent ApplicationEvent applicationEvent; if (event instanceof ApplicationEvent) { applicationEvent = (ApplicationEvent) event; } else { // 不是事件类型就转为事件类型 applicationEvent = newPayloadApplicationEvent<>(this, event); if (eventType == null) { eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType(); } }
// Multicast right now if possible - or lazily once the multicaster is initialized // 如果可能,立即进行多播或者一旦初始化多播器就进入懒惰状态 if (this.earlyApplicationEvents != null) { this.earlyApplicationEvents.add(applicationEvent); } else { // 获取事件广播器,发布事件 getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType); }
// Publish event via parent context as well... // 如果存在父容器,那么父容器也发布事件 if (this.parent != null) { if (this.parent instanceof AbstractApplicationContext) { ((AbstractApplicationContext) this.parent).publishEvent(event, eventType); } else { this.parent.publishEvent(event); } } }
privatevoiddoInvokeListener(ApplicationListener listener, ApplicationEvent event) { try { // 触发监听器的onApplicationEvent方法,参数为给定的事件 listener.onApplicationEvent(event); } catch (ClassCastException ex) { Stringmsg= ex.getMessage(); if (msg == null || matchesClassCastMessage(msg, event.getClass())) { // Possibly a lambda-defined listener which we could not resolve the generic event type for // -> let's suppress the exception and just log a debug message. Loglogger= LogFactory.getLog(getClass()); if (logger.isTraceEnabled()) { logger.trace("Non-matching event type for listener: " + listener, ex); } } else { throw ex; } } }
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinitionmbdToUse= mbd;
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 锁定class,根据设置的class属性或者根据className来解析class Class<?> resolvedClass = resolveBeanClass(mbd, beanName); // 进行条件筛选,重新赋值RootBeanDefinition,并设置BeanClass属性 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { // 重新创建一个RootBeanDefinition对象 mbdToUse = newRootBeanDefinition(mbd); // 设置BeanClass属性值 mbdToUse.setBeanClass(resolvedClass); }
if (earlySingletonExposure) { // 尝试从缓存中获取单例,注意后面的参数为false,表示不从第三级缓存singletonFactories中获取 // 为什么呢?因为这里不允许循环依赖 ObjectearlySingletonReference= getSingleton(beanName, false); // 如果不为null,就会进入if条件中,因为earlySingletonReference不为null,说明存在循环引用, // 为什么呢?因为第一个处理的时候,会将引用放到singletonFactories缓存中,当循环依赖注入的时候, // 会通过singletonFactories中拿到提前暴露的引用,然后放到第二级缓存earlySingletonObjects中。 // 所以,在这里拿到了earlySingletonReference,表明存在循环引用。 // earlySingletonReference只有在检测到有循环依赖的情况下才会不为空 if (earlySingletonReference != null) { // 如果相等,那么就什么也不做,将earlySingletonReference返回回去即可 // 如果exposedObject没有在初始化方法中被改变,也就是没有被增强 if (exposedObject == bean) { exposedObject = earlySingletonReference; } // 如果不相等,并且有其它bean依赖这个bean elseif (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { // 拿到依赖这个bean的所有bean String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = newLinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { // 如果存在已经创建完的bean(已经创建完的bean依赖该bean) // 返回false说明依赖还没实例化好 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { // 防止对象被改变,造成的已创建对象中持有的对象和这个对象不一致。 // 因为bean创建后所依赖的bean一定是已经创建的 // actualDependentBeans不为空则表示当前bean创建后其依赖的bean却没有全部创建完,也就是说存在循环依赖 thrownewBeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } }
// No special handling: simply use no-arg constructor. // 使用默认无参构造函数创建对象,如果没有无参构造且存在多个有参构造且没有@AutoWired注解构造,会报错 return instantiateBean(beanName, mbd); }
// 如果已经找到选用的构造函数或者需要的参数个数小于当前的构造函数参数个数则终止,前面已经经过了排序操作 if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) { // Already found greedy constructor that can be satisfied -> // do not look any further, there are only less greedy constructors left. break; } // 如果本构造函数的参数列表数量小于要求的最小数量,则遍历下一个 if (paramTypes.length < minNrOfArgs) { // 参数个数不相等 continue; }
protectedvoidpopulateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // 如果beanWrapper为空 if (bw == null) { // 如果mbd有需要设置的属性 if (mbd.hasPropertyValues()) { // 抛出bean创建异常 thrownewBeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. // 没有可填充的属性,直接跳过 return; } }
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. // 给任何实现了InstantiationAwareBeanPostProcessors的子类机会去修改bean的状态再设置属性之前,可以被用来支持类型的字段注入
if (initMethod == null) { if (mbd.isEnforceInitMethod()) { thrownewBeanDefinitionValidationException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { if (logger.isTraceEnabled()) { logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. return; } }
if (logger.isTraceEnabled()) { logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'"); } MethodmethodToInvoke= ClassUtils.getInterfaceMethodIfPossible(initMethod);
/** * 完成此上下文的beanFactory的初始化,初始化所有剩余的单例对象。 */ protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. // beanFactory 初始化 conversionService (类型转换器) 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. // 如果没有embedded的后置处理器, 则注册一个默认的embedded后置处理器。 主要用于解析注解属性值 if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. // 尽早初始化LoadTimeWeaverAware Bean,以便尽早注册其转换器。 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. // 清空临时ClassLoader (禁止使用临时类加载器进行类型匹配) beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. // 冻结所有的beanDefinition的metadata,不期被进一步的修改。 beanFactory.freezeConfiguration();
@Override publicvoidpreInstantiateSingletons()throws BeansException { if (logger.isTraceEnabled()) { logger.trace("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. // 遍历一个副本以允许使用init方法,这些方法依次注册新的bean定义。 // 尽管这可能不是常规工厂引导程序的一部分,但可以正常运行。 List<String> beanNames = newArrayList<>(this.beanDefinitionNames);
// Check with full lock now in order to enforce the same merged instance. // 检查beanName对应的MergedBeanDefinition是否存在于缓存中 if (containingBd == null) { mbd = this.mergedBeanDefinitions.get(beanName); } // mbd 为null 并且 mbd需要重新合并 if (mbd == null || mbd.stale) { previous = mbd; mbd = null; // 如果bd的parentName为空,代表bd没有父定义,无需与父定义进行合并操作 // bean的ParentName if (bd.getParentName() == null) { // Use copy of given root bean definition. // 如果bd的类型为RootBeanDefinition,则bd的MergedBeanDefinition就是bd本身,则直接克隆一个副本 if (bd instanceof RootBeanDefinition) { mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); } else { // 否则,将bd作为参数,构建一个RootBeanDefinition。 // 正常使用下,BeanDefinition在被加载后是GenericBeanDefinition或ScannedGenericBeanDefinition mbd = newRootBeanDefinition(bd); } } else { // Child bean definition: needs to be merged with parent. // bd存在父定义,需要与父定义合并 BeanDefinition pbd; try { // 获取父bean的名称,并进行转换 StringparentBeanName= transformedBeanName(bd.getParentName()); // 如果当前beanName和父beanName不相同,那么递归调用合并方法 if (!beanName.equals(parentBeanName)) { pbd = getMergedBeanDefinition(parentBeanName); } else { // 如果父定义的beanName与bd的beanName相同,则拿到父BeanFactory, // 只有在存在父BeanFactory的情况下,才允许父定义beanName与自己相同,否则就是将自己设置为父定义 BeanFactoryparent= getParentBeanFactory(); // 如果父BeanFactory是ConfigurableBeanFactory,则通过父BeanFactory获取父定义的MergedBeanDefinition if (parent instanceof ConfigurableBeanFactory) { // 从父BeanFactory获取BeanDefinition pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName); } else { // 如果父BeanFactory不是ConfigurableBeanFactory,则抛异常 thrownewNoSuchBeanDefinitionException(parentBeanName, "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent"); } } } catch (NoSuchBeanDefinitionException ex) { thrownewBeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); } // Deep copy with overridden values. // 根据父BeanFactory获取的BeanDefinition创建新的BeanDefinition mbd = newRootBeanDefinition(pbd); // 将原始的部分属性拷贝到mbd mbd.overrideFrom(bd); }
// Set default singleton scope, if not configured before. // 如果没有配置scope,则设置为默认的单例scope if (!StringUtils.hasLength(mbd.getScope())) { mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON); }
// A bean contained in a non-singleton bean cannot be a singleton itself. // Let's correct this on the fly here, since this might be the result of // parent-child merging for the outer bean, in which case the original inner bean // definition will not have inherited the merged outer bean's singleton status. // 一个bean包含非单例bean, 则他不是一个单例bean // 我们在此时进行修改scope,因为这可能是外部bean的父子合并的结果,在这种情况下,原始内部beanDefinition将不会继承合并的外部bean的单例状态 if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) { mbd.setScope(containingBd.getScope()); }
// Cache the merged bean definition for the time being // (it might still get re-merged later on in order to pick up metadata changes) // 将beanName与mbd放到mergedBeanDefinitions缓存,以便之后可以直接使用 if (containingBd == null && isCacheBeanMetadata()) { this.mergedBeanDefinitions.put(beanName, mbd); } } if (previous != null) { // 拷贝相关的MergedBeanDefinition字段 copyRelevantMergedBeanDefinitionCaches(previous, mbd); } return mbd; } }
// 传入的 name 可能是 beanName, alias, &beanName (FactoryBean) // 将 name 转换成 beanName finalStringbeanName= transformedBeanName(name); Object bean;
// Eagerly check singleton cache for manually registered singletons. // 提前检查单例缓存中是否有手动注册的单例对象,跟循环依赖有关联 // 从缓存中获取已实例化的单例对象 ObjectsharedInstance= getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } // 返回对象的实例 // 当你实现了FactoryBean接口的对象,需要获取具体的对象的时候就需要此方法来进行获取了 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. // 检查该工厂中是否存在bean定义 BeanFactoryparentBeanFactory= getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. StringnameToLookup= originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } elseif (args != null) { // Delegation to parent with explicit args. // 父级创建对象 bean 实例 return (T) parentBeanFactory.getBean(nameToLookup, args); } elseif (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } }
// 如果不是做类型检查,那么表示要创建bean,此处在集合中做一个记录 if (!typeCheckOnly) { markBeanAsCreated(beanName); }
// Guarantee initialization of beans that the current bean depends on. // 确保当前bean依赖的bean的初始化 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { // 如果存在依赖,则需要递归实例化依赖的bean for (String dep : dependsOn) { if (isDependent(beanName, dep)) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 注册各个bean的依赖关系,方便进行销毁 registerDependentBean(dep, beanName); try { // 先实例化引用的 bean 实例 getBean(dep); } catch (NoSuchBeanDefinitionException ex) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } }
// Create bean instance. if (mbd.isSingleton()) { // 创建单例对象 sharedInstance = getSingleton(beanName, () -> { try { return createBean(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); }
// Don't let calling code try to dereference the factory if the bean isn't a factory. // 通过beanName判断是否有factoryBean的前缀(即 name包含&) if (BeanFactoryUtils.isFactoryDereference(name)) { // if (beanInstance instanceof NullBean) { return beanInstance; } if (!(beanInstance instanceof FactoryBean)) { // beanInstance 没有实现 FactoryBean 接口 thrownewBeanIsNotAFactoryException(beanName, beanInstance.getClass()); } if (mbd != null) { mbd.isFactoryBean = true; } return beanInstance; }
// Now we have the bean instance, which may be a normal bean or a FactoryBean. // If it's a FactoryBean, we use it to create a bean instance, unless the // caller actually wants a reference to the factory. // 当我们有了bean的实例之后,这个实例可能是正常的bean,也可能是FactoryBean, // 如果是FactoryBean那么就直接创建实例, // 但是如果用户想要直接获取工厂实例而不是工厂的getObject方法对应的实例,那么传入的参数应该加&前缀 if (!(beanInstance instanceof FactoryBean)) { // beanInstance 没有实现 FactoryBean 接口 return beanInstance; }
// 创建FactoryBean中的bean Objectobject=null; if (mbd != null) { mbd.isFactoryBean = true; } else { // 尝试从缓存中加载bean object = getCachedObjectForFactoryBean(beanName); } if (object == null) { // Return bean instance from factory. // 将beanInstance转换为FactoryBean类型 FactoryBean<?> factory = (FactoryBean<?>) beanInstance; // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) { // 将存储xml配置文件的 GenericBeanDefinition 转换为RootBeanDefinition, // 如果指定BeanName是子Bean的话,同时会合并父类的相关属性 mbd = getMergedLocalBeanDefinition(beanName); } // 判断当前bean是否是用户定义的,而不是应用程序本身定义的 booleansynthetic= (mbd != null && mbd.isSynthetic()); object = getObjectFromFactoryBean(factory, beanName, !synthetic); // factory::getObject } return object; }
// Do not accept a null value for a FactoryBean that's not fully // initialized yet: Many FactoryBeans just return null then. if (object == null) { // 如果是正在创建的FactoryBean,还没能获得bean,就报异常 if (isSingletonCurrentlyInCreation(beanName)) { thrownewBeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } object = newNullBean(); } return object; }