spring註解開發(七) 容器建立過程
傳入配置類後,
註冊配置類,主要是 refresh()
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. 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. 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(); } } }
prepareRefresh();
記錄一下日期,設定一些狀態,初始化一些屬性並校驗,準備收集一些早期事件,一旦有了multicaster就釋出等等
obtainFreshBeanFactory();
建立之後返回beanFactory
prepareBeanFactory(beanFactory); beanFactory的預處理工作
/** * Configure the factory's standard context characteristics, * such as the context's ClassLoader and post-processors. * @param beanFactory the BeanFactory to configure */ 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. 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. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. 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. 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()); } }
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
BeanFactoryPostProcessors 是對 BeanFactory已經初始化之後做一些處理
public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any. Set<String> processedBeans = new HashSet<>(); if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessors.add(registryProcessor); } else { 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. String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. boolean reiterate = true; while (reiterate) { reiterate = false; 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; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); } // Now, invoke the postProcessBeanFactory callback of all processors handled so far. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. 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! 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)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // Next, invoke the BeanFactoryPostProcessors that implement Ordered. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(); 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<>(); 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... beanFactory.clearMetadataCache(); }
registerBeanPostProcessors(beanFactory); 註冊 BeanPostProcessors
public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { 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. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. 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); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, register the BeanPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(); 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. List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); 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. 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). beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
initMessageSource(); 國際化,訊息繫結,訊息解析
protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); 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.isDebugEnabled()) { logger.debug("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isDebugEnabled()) { logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME + "': using default [" + this.messageSource + "]"); } } }
initApplicationEventMulticaster(); 初始化事件Multicaster
onRefresh();自容器在容器刷心的時候觸發,自己定義
registerListeners();註冊監聽器
/** * Add beans that implement ApplicationListener as listeners. * Doesn't affect other listeners, which can be added without being beans. */ 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); } } }
finishBeanFactoryInitialization(beanFactory); 完成剩下的還沒初始化的bean
/** * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protected void finishBeanFactoryInitialization(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(strVal -> getEnvironment().resolvePlaceholders(strVal)); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. 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(); }
finishRefresh(); 釋出事件監聽
Spring容器的refresh()【建立重新整理】;
1、prepareRefresh()重新整理前的預處理;
1)、initPropertySources()初始化一些屬性設定;子類自定義個性化的屬性設定方法;
2)、getEnvironment().validateRequiredProperties();檢驗屬性的合法等
3)、earlyApplicationEvents= new LinkedHashSet<ApplicationEvent>();儲存容器中的一些早期的事件;
2、obtainFreshBeanFactory();獲取BeanFactory;
1)、refreshBeanFactory();重新整理【建立】BeanFactory;
建立了一個this.beanFactory = new DefaultListableBeanFactory();
設定id;
2)、getBeanFactory();返回剛才GenericApplicationContext建立的BeanFactory物件;
3)、將建立的BeanFactory【DefaultListableBeanFactory】返回;
3、prepareBeanFactory(beanFactory);BeanFactory的預準備工作(BeanFactory進行一些設定);
1)、設定BeanFactory的類載入器、支援表示式解析器...
2)、新增部分BeanPostProcessor【ApplicationContextAwareProcessor】
3)、設定忽略的自動裝配的介面EnvironmentAware、EmbeddedValueResolverAware、xxx;
4)、註冊可以解析的自動裝配;我們能直接在任何元件中自動注入:
BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
5)、新增BeanPostProcessor【ApplicationListenerDetector】
6)、新增編譯時的AspectJ;
7)、給BeanFactory中註冊一些能用的元件;
environment【ConfigurableEnvironment】、
systemProperties【Map<String, Object>】、
systemEnvironment【Map<String, Object>】
4、postProcessBeanFactory(beanFactory);BeanFactory準備工作完成後進行的後置處理工作;
1)、子類通過重寫這個方法來在BeanFactory建立並預準備完成以後做進一步的設定
======================以上是BeanFactory的建立及預準備工作==================================
5、invokeBeanFactoryPostProcessors(beanFactory);執行BeanFactoryPostProcessor的方法;
BeanFactoryPostProcessor:BeanFactory的後置處理器。在BeanFactory標準初始化之後執行的;
兩個介面:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
1)、執行BeanFactoryPostProcessor的方法;
先執行BeanDefinitionRegistryPostProcessor
1)、獲取所有的BeanDefinitionRegistryPostProcessor;
2)、看先執行實現了PriorityOrdered優先順序介面的BeanDefinitionRegistryPostProcessor、
postProcessor.postProcessBeanDefinitionRegistry(registry)
3)、在執行實現了Ordered順序介面的BeanDefinitionRegistryPostProcessor;
postProcessor.postProcessBeanDefinitionRegistry(registry)
4)、最後執行沒有實現任何優先順序或者是順序介面的BeanDefinitionRegistryPostProcessors;
postProcessor.postProcessBeanDefinitionRegistry(registry)
再執行BeanFactoryPostProcessor的方法
1)、獲取所有的BeanFactoryPostProcessor
2)、看先執行實現了PriorityOrdered優先順序介面的BeanFactoryPostProcessor、
postProcessor.postProcessBeanFactory()
3)、在執行實現了Ordered順序介面的BeanFactoryPostProcessor;
postProcessor.postProcessBeanFactory()
4)、最後執行沒有實現任何優先順序或者是順序介面的BeanFactoryPostProcessor;
postProcessor.postProcessBeanFactory()
6、registerBeanPostProcessors(beanFactory);註冊BeanPostProcessor(Bean的後置處理器)【 intercept bean creation】
不同介面型別的BeanPostProcessor;在Bean建立前後的執行時機是不一樣的
BeanPostProcessor、
DestructionAwareBeanPostProcessor、
InstantiationAwareBeanPostProcessor、
SmartInstantiationAwareBeanPostProcessor、
MergedBeanDefinitionPostProcessor【internalPostProcessors】、
1)、獲取所有的 BeanPostProcessor;後置處理器都預設可以通過PriorityOrdered、Ordered介面來執行優先順序
2)、先註冊PriorityOrdered優先順序介面的BeanPostProcessor;
把每一個BeanPostProcessor;新增到BeanFactory中
beanFactory.addBeanPostProcessor(postProcessor);
3)、再註冊Ordered介面的
4)、最後註冊沒有實現任何優先順序介面的
5)、最終註冊MergedBeanDefinitionPostProcessor;
6)、註冊一個ApplicationListenerDetector;來在Bean建立完成後檢查是否是ApplicationListener,如果是
applicationContext.addApplicationListener((ApplicationListener<?>) bean);
7、initMessageSource();初始化MessageSource元件(做國際化功能;訊息繫結,訊息解析);
1)、獲取BeanFactory
2)、看容器中是否有id為messageSource的,型別是MessageSource的元件
如果有賦值給messageSource,如果沒有自己建立一個DelegatingMessageSource;
MessageSource:取出國際化配置檔案中的某個key的值;能按照區域資訊獲取;
3)、把建立好的MessageSource註冊在容器中,以後獲取國際化配置檔案的值的時候,可以自動注入MessageSource;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale);
8、initApplicationEventMulticaster();初始化事件派發器;
1)、獲取BeanFactory
2)、從BeanFactory中獲取applicationEventMulticaster的ApplicationEventMulticaster;
3)、如果上一步沒有配置;建立一個SimpleApplicationEventMulticaster
4)、將建立的ApplicationEventMulticaster新增到BeanFactory中,以後其他元件直接自動注入
9、onRefresh();留給子容器(子類)
1、子類重寫這個方法,在容器重新整理的時候可以自定義邏輯;
10、registerListeners();給容器中將所有專案裡面的ApplicationListener註冊進來;
1、從容器中拿到所有的ApplicationListener
2、將每個監聽器新增到事件派發器中;
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
3、派發之前步驟產生的事件;
11、finishBeanFactoryInitialization(beanFactory);初始化所有剩下的單例項bean;
1、beanFactory.preInstantiateSingletons();初始化後剩下的單例項bean
1)、獲取容器中的所有Bean,依次進行初始化和建立物件
2)、獲取Bean的定義資訊;RootBeanDefinition
3)、Bean不是抽象的,是單例項的,是懶載入;
1)、判斷是否是FactoryBean;是否是實現FactoryBean介面的Bean;
2)、不是工廠Bean。利用getBean(beanName);建立物件
0、getBean(beanName); ioc.getBean();
1、doGetBean(name, null, null, false);
2、先獲取快取中儲存的單例項Bean。如果能獲取到說明這個Bean之前被建立過(所有建立過的單例項Bean都會被快取起來)
從private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);獲取的
3、快取中獲取不到,開始Bean的建立物件流程;
4、標記當前bean已經被建立
5、獲取Bean的定義資訊;
6、【獲取當前Bean依賴的其他Bean;如果有按照getBean()把依賴的Bean先創建出來;】
7、啟動單例項Bean的建立流程;
1)、createBean(beanName, mbd, args);
2)、Object bean = resolveBeforeInstantiation(beanName, mbdToUse);讓BeanPostProcessor先攔截返回代理物件;
【InstantiationAwareBeanPostProcessor】:提前執行;
先觸發:postProcessBeforeInstantiation();
如果有返回值:觸發postProcessAfterInitialization();
3)、如果前面的InstantiationAwareBeanPostProcessor沒有返回代理物件;呼叫4)
4)、Object beanInstance = doCreateBean(beanName, mbdToUse, args);建立Bean
1)、【建立Bean例項】;createBeanInstance(beanName, mbd, args);
利用工廠方法或者物件的構造器創建出Bean例項;
2)、applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
呼叫MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
3)、【Bean屬性賦值】populateBean(beanName, mbd, instanceWrapper);
賦值之前:
1)、拿到InstantiationAwareBeanPostProcessor後置處理器;
postProcessAfterInstantiation();
2)、拿到InstantiationAwareBeanPostProcessor後置處理器;
postProcessPropertyValues();
=====賦值之前:===
3)、應用Bean屬性的值;為屬性利用setter方法等進行賦值;
applyPropertyValues(beanName, mbd, bw, pvs);
4)、【Bean初始化】initializeBean(beanName, exposedObject, mbd);
1)、【執行Aware介面方法】invokeAwareMethods(beanName, bean);執行xxxAware介面的方法
BeanNameAware\BeanClassLoaderAware\BeanFactoryAware
2)、【執行後置處理器初始化之前】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
BeanPostProcessor.postProcessBeforeInitialization();
3)、【執行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
1)、是否是InitializingBean介面的實現;執行介面規定的初始化;
2)、是否自定義初始化方法;
4)、【執行後置處理器初始化之後】applyBeanPostProcessorsAfterInitialization
BeanPostProcessor.postProcessAfterInitialization();
5)、註冊Bean的銷燬方法;
5)、將建立的Bean新增到快取中singletonObjects;
ioc容器就是這些Map;很多的Map裡面儲存了單例項Bean,環境資訊。。。。;
所有Bean都利用getBean建立完成以後;
檢查所有的Bean是否是SmartInitializingSingleton介面的;如果是;就執行afterSingletonsInstantiated();
12、finishRefresh();完成BeanFactory的初始化建立工作;IOC容器就建立完成;
1)、initLifecycleProcessor();初始化和生命週期有關的後置處理器;LifecycleProcessor
預設從容器中找是否有lifecycleProcessor的元件【LifecycleProcessor】;如果沒有new DefaultLifecycleProcessor();
加入到容器;
寫一個LifecycleProcessor的實現類,可以在BeanFactory
void onRefresh();
void onClose();
2)、 getLifecycleProcessor().onRefresh();
拿到前面定義的生命週期處理器(BeanFactory);回撥onRefresh();
3)、publishEvent(new ContextRefreshedEvent(this));釋出容器重新整理完成事件;
4)、liveBeansView.registerApplicationContext(this);
======總結===========
1)、Spring容器在啟動的時候,先會儲存所有註冊進來的Bean的定義資訊;
1)、xml註冊bean;<bean>
2)、註解註冊Bean;@Service、@Component、@Bean、xxx
2)、Spring容器會合適的時機建立這些Bean
1)、用到這個bean的時候;利用getBean建立bean;建立好以後儲存在容器中;
2)、統一建立剩下所有的bean的時候;finishBeanFactoryInitialization();
3)、後置處理器;BeanPostProcessor
1)、每一個bean建立完成,都會使用各種後置處理器進行處理;來增強bean的功能;
AutowiredAnnotationBeanPostProcessor:處理自動注入
AnnotationAwareAspectJAutoProxyCreator:來做AOP功能;
xxx....
增強的功能註解:
AsyncAnnotationBeanPostProcessor
....
4)、事件驅動模型;
ApplicationListener;事件監聽;
ApplicationEventMulticaster;事件派發: