spring学习之源码分析--AnnotationConfigApplicationContext之register和scan 中,讲了注解形式是怎么注册BeanDefinition的,注册完后,有了bean的定义信息,当然是初始化容器了。
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. // 准备刷新的上下文环境 prepareRefresh(); // Tell the subclass to refresh the internal bean factory. // 获取beanFactory ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. // 设置beanFactory的各个属性 prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. // 模板模式,留给子类通过重写这个方法来做其他处理 postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. // BeanFactoryPostProcessorc,BeanFactory的后置处理器处理 invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. // 注册BeanPostProcessors,拦截bean的创建过程,bean在这个时候还没创建 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. // 注册ApplicationListener到applicationEventMulticaster registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. // 初始化所有的单例,除了延迟加载的bean finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. // 通知别人说已经完成了 finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
刷新前的准备,对容器属性的初始化,校验属性文件的合法性,保留早期事件
protected void prepareRefresh() { // Switch to active. // 启动时间 this.startupDate = System.currentTimeMillis(); // 容器是否关闭 this.closed.set(false); // 容器是否是活动状态 this.active.set(true); if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) { logger.trace("Refreshing " + this); } else { logger.debug("Refreshing " + getDisplayName()); } } // Initialize any placeholder property sources in the context environment. // 初始化属性,留给子类 initPropertySources(); // Validate that all properties marked as required are resolvable: // see ConfigurablePropertyResolver#setRequiredProperties // 校验属性文件是否合法 getEnvironment().validateRequiredProperties(); // Store pre-refresh ApplicationListeners... // 保留早期事件 if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { // Reset local application listeners to pre-refresh state. this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); } // Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet<>(); }
获取beanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); return getBeanFactory(); } // GenericApplicationContext.class protected final void refreshBeanFactory() throws IllegalStateException { // refreshed为false才可以,只能一个线程执行refresh方法 if (!this.refreshed.compareAndSet(false, true)) { throw new IllegalStateException( "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once"); } // 设置序列号,由于我们这个是通过AnnotationConfigApplicationContext查看的 // 所以已经由AnnotationConfigApplicationContext的父类GenericApplicationContext初始化了beanFactory this.beanFactory.setSerializationId(getId()); }
设置beanFactory的各个属性
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. // 设置类加载器 beanFactory.setBeanClassLoader(getClassLoader()); // 设置表达式解析器 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 添加属性编辑器 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks. // 添加ApplicationContextAwareProcessor,根据不同的类型加入不同的属性 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 忽略一下几个接口的自动装配 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); // BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. // 注册几个依赖类型和自动注入值 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Register early post-processor for detecting inner beans as ApplicationListeners. // 注册ApplicationListenerDetector,如果bean是ApplicationListener的,加入到事件派发器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. // 增加对AspectJ的支持 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } // Register default environment beans. // 注册默认的环境bean if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
我们先了解一下BeanFactoryPostProcessor接口,他有个方法,传递的参数是ConfigurableListableBeanFactory,也就是说,在refresh中,beanFactory初始化完成后,把这个beanFactory传给BeanFactoryPostProcessor。BeanFactoryPostProcessor可以在实例化bean前,自定义他的任何行为。与之类似的BeanPostProcessor,是bean级别的,BeanFactoryPostProcessor是容器级别的。两个针对不同的范围进行加强。
大概流程是:
1、先处理BeanDefinitionRegistryPostProcessor类型的
2、再处理其他类型的BeanFactoryPostProcessor
两种BeanFactoryPostProcessor都是按照PriorityOrdered>Ordered>其他的顺序执行。
通过AnnotationConfigApplicationContext扫描或注册后,bean里面的注解要怎么注入到容器呢,就是通过ConfigurationClassPostProcessor实现的,这个ConfigurationClassPostProcessor就是实现了BeanDefinitionRegistryPostProcessor和PriorityOrdered的接口。
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } } public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any. // 保存被处理过的beanName Set<String> processedBeans = new HashSet<>(); // 如果是BeanDefinitionRegistry if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); // BeanDefinitionRegistryPostProcessor先处理,保存在registryProcessors for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessors.add(registryProcessor); } else { // 保存常规的,非BeanDefinitionRegistryPostProcessor regularPostProcessors.add(postProcessor); } } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. // 获取BeanDefinitionRegistryPostProcessor类型的beanName String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { // 先执行实现了PriorityOrdered接口的bean if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 生成的bean保存在currentRegistryProcessors currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); // 保存被处理过的beanName processedBeans.add(ppName); } } // 对currentRegistryProcessors进行排序 sortPostProcessors(currentRegistryProcessors, beanFactory); // 全部添加到registryProcessors,此时所有的BeanFactoryPostProcessor,包括定义的bean,都保存在registryProcessors registryProcessors.addAll(currentRegistryProcessors); // 获取PriorityOrdered接口的BeanFactoryPostProcessor完后,进行后置处理 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); // 清空currentRegistryProcessors作其他用途 currentRegistryProcessors.clear(); // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. // 获取BeanDefinitionRegistryPostProcessor,且实现Ordered接口的。实现了PriorityOrdered接口的,通过processedBeans排除了 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { // 生成的bean保存在currentRegistryProcessors currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); // 保存被处理过的beanName processedBeans.add(ppName); } } // 对currentRegistryProcessors进行排序 sortPostProcessors(currentRegistryProcessors, beanFactory); // 全部添加到registryProcessors registryProcessors.addAll(currentRegistryProcessors); // 获取Ordered接口的BeanFactoryPostProcessor完后,进行后置处理 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); // 清空currentRegistryProcessors作其他用途 currentRegistryProcessors.clear(); // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. // 为false说明已经遍历完了 boolean reiterate = true; while (reiterate) { reiterate = false; // 获取processedBeans排除的BeanDefinitionRegistryPostProcessor postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); // 说明还有,继续遍历 reiterate = true; } } // 对currentRegistryProcessors进行排序 sortPostProcessors(currentRegistryProcessors, beanFactory); // 全部添加到registryProcessors registryProcessors.addAll(currentRegistryProcessors); // 获取的BeanFactoryPostProcessor完后,进行后置处理 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); // 清空currentRegistryProcessors作其他用途 currentRegistryProcessors.clear(); } // Now, invoke the postProcessBeanFactory callback of all processors handled so far. // BeanDefinitionRegistryPostProcessor处理完了,再调用BeanFactoryPostProcessor的后置处理器。 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. // 直接调用BeanFactoryPostProcessor的后置处理器。 invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // 上面主要对BeanDefinitionRegistryPostProcessor和传入的参数beanFactoryPostProcessors两种后置处理器的调用 // 下面是bean定义中BeanFactoryPostProcessor后置处理器的调用 // 获取bean定义中BeanFactoryPostProcessor String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { // 已处理过的跳过 if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 实现了PriorityOrdered接口的 priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { // 实现了Ordered接口的 orderedPostProcessorNames.add(ppName); } else { // 其他的 nonOrderedPostProcessorNames.add(ppName); } } // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. // 先对实现了PriorityOrdered接口的排序,然后再调用后置处理器 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // Next, invoke the BeanFactoryPostProcessors that implement Ordered. // 先对实现了Ordered接口的排序,然后再调用后置处理器 List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // Finally, invoke all other BeanFactoryPostProcessors. // 最后调用剩下的后置处理器 List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); // Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... // 因为后处理器可能有修改了原始的元数据,所以要清除缓存的合并bean定义 beanFactory.clearMetadataCache(); }
注册BeanPostProcessor,这边并没有调用,只是注册,传递的参数是实例及beanName。真正的调用是在bean的实例化的时候。
整体流程跟上面BeanFactoryPostProcessor差不多,只是多了一个MergedBeanDefinitionPostProcessor。
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); } public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { // 获取所有的BeanPostProcessor String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. // 获取后置处理器的个数,这个+1就是加BeanPostProcessorChecker int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 下面这段代码是不是很熟悉,跟BeanFactoryPostProcessor一样的思想,先PriorityOrdered再Ordered最后其他 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); // 保存实现了PriorityOrdered接口的BeanPostProcessor priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { // 保存实现了PriorityOrdered及MergedBeanDefinitionPostProcessor接口的BeanPostProcessor internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { // 保存实现了Ordered接口的BeanPostProcessor orderedPostProcessorNames.add(ppName); } else { // 保存其他接口的BeanPostProcessor nonOrderedPostProcessorNames.add(ppName); } } // First, register the BeanPostProcessors that implement PriorityOrdered. // PriorityOrdered接口,排序,注册到beanFactory sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. // Ordered接口,排序,注册到beanFactory,另外过滤MergedBeanDefinitionPostProcessor类型的加入到internalPostProcessors List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors. // 其他接口,注册到beanFactory,另外过滤MergedBeanDefinitionPostProcessor类型的加入到internalPostProcessors List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors. // MergedBeanDefinitionPostProcessor接口,排序,注册到beanFactory sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); // Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 添加ApplicationListenerDetector监听 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
国际化处理
protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 如果beanFactory存在messageSource,赋值给messageSource if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. // beanFactory不存在messageSource,使用默认的 DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }
初始化事件派发器
protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 如果beanFactory存在applicationEventMulticaster,赋值给applicationEventMulticaster if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { // beanFactory不存在applicationEventMulticaster,使用默认的 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); } } }
注册监听
protected void registerListeners() { // Register statically specified listeners first. // 注入到事件派发器 for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! // 从配置信息获取监听注入到事件派发器 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // Publish early application events now that we finally have a multicaster... // 早起的监听注册到事件派发器 Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. // 如果beanFactory存在conversionService,赋值给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. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactoryFactoryBean.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. // 冻结所有bean的定义,此时不希望bean的定义被修改 beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. // 初始化剩下的单例,且除了延迟加载的bean beanFactory.preInstantiateSingletons(); }
beanFactory.preInstantiateSingletons() 中,区分了普通bean和FactoryBean的实例化,如果是FactoryBean,则beanName加上&再实例化。
实例化调用的是getBean方法,实际调用的是doGetBean方法。doGetBean大概步骤如下:
1、transformedBeanName,获取beanName,有可能传过来的是原始的beanName,有可能是加了&的,有可能是别名。如果是加了&的,先去除,再获取。如果是别名,先递归到最原始的别名,再获取beanName。
2、getSingleton,获取到beanName后,通过beanName看单例缓存是否创建过了,有的话直接返回。如果singletonObjects和earlySingletonObjects两个缓存都没有,从singletonFactories加载。
3、 getObjectForBeanInstance ,得到的bean,是原始的bean,可能是普通的bean,也可能是FactoryBean,所以要通过这个方法处理一下,得到我们想要的bean。我们经常提及的后置处理器就是在这里调用的。
4、 isPrototypeCurrentlyInCreation ,如果没得到bean,就去创建一个bean,此时先判断是否是多例。在单例的时候,可能尝试解决循环依赖,如果是多例,会循环引用,是不允许的。
5、如果有父容器,当前容器没有这个bean的定义,说明了这个bean就有可能在父容器中,或者让父容器创建,一直递归上去。
6、 getMergedBeanDefinition ,父容器也没有,就只能根据bean的定义中创建了。原先的bean的定义,都是GenericBeanDefinition类型的,要转换为RootBeanDefinition类型。大体逻辑是这样的,如果mergedBeanDefinitions缓存有,直接返回,如果没有,看看有没有父类,有父类,递归上去找,并合并父类的属性。如果没有父类,判断是不是RootBeanDefinition类型的,如果是,直接复制,如果不是,就转换为RootBeanDefinition。
7、实例化之前,要先实例化依赖的对象。要判断是否循环依赖isDependent,再保存依赖的关系 registerDependentBean 。
8、如果是单例,getSingleton中先对缓存、创建状态进行处理,再通过回调createBean创建bean,最后调用getObjectForBeanInstance处理一下。(见3步骤)
9、如果是多例,调用createBean前后,要调用 beforePrototypeCreation 和 afterPrototypeCreation 来保存是否在创建的状态,防止循环引用,(见4步骤的判断)。创建bean后,再调用getObjectForBeanInstance处理一下。(见3步骤)
10、其他scope类型的判断,大概步骤同9.
11、根据类型转换需要的类型。