国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術文章
文章詳情頁

Spring啟動流程refresh()源碼深入解析

瀏覽:3日期:2023-08-17 15:09:54

一、Spring容器的refresh()

spring version:4.3.12 ,尚硅谷Spring注解驅動開發—源碼部分

//refresh():543, AbstractApplicationContext (org.springframework.context.support) public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //1 刷新前的預處理 prepareRefresh(); //2 獲取BeanFactory;剛創建的默認DefaultListableBeanFactory ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //3 BeanFactory的預準備工作(BeanFactory進行一些設置) prepareBeanFactory(beanFactory);​ try { // 4 BeanFactory準備工作完成后進行的后置處理工作; // 4.1)、抽象的方法,當前未做處理。子類通過重寫這個方法來在BeanFactory創建并預準備完成以后做進一步的設置 postProcessBeanFactory(beanFactory); /**************************以上是BeanFactory的創建及預準備工作 ****************/ // 5 執行BeanFactoryPostProcessor的方法;//BeanFactoryPostProcessor:BeanFactory的后置處理器。在BeanFactory標準初始化之后執行的;//他的重要兩個接口:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor invokeBeanFactoryPostProcessors(beanFactory);​ //6 注冊BeanPostProcessor(Bean的后置處理器) registerBeanPostProcessors(beanFactory);​ // 7 initMessageSource();初始化MessageSource組件(做國際化功能;消息綁定,消息解析); initMessageSource();​ // 8 初始化事件派發器 initApplicationEventMulticaster();​ // 9 子類重寫這個方法,在容器刷新的時候可以自定義邏輯; onRefresh();​ // 10 給容器中將所有項目里面的ApplicationListener注冊進來 registerListeners(); ​ // 11.初始化所有剩下的單實例bean; finishBeanFactoryInitialization(beanFactory);​ // 12.完成BeanFactory的初始化創建工作;IOC容器就創建完成; 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(); } } }

1 、prepareRefresh()刷新前的預處理;

//刷新前的預處理;protected void prepareRefresh() { this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true);​ if (logger.isInfoEnabled()) { logger.info('Refreshing ' + this); } // 初始化一些屬性設置;子類自定義個性化的屬性設置方法; initPropertySources(); // 校驗配置文件的屬性,合法性 getEnvironment().validateRequiredProperties(); //保存容器中的一些事件 this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();}

2、 obtainFreshBeanFactory();創建了一個BeanFactory

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); //創建了一個this.beanFactory = new DefaultListableBeanFactory();設置了序列化的ID //返回剛才創建的DefaultListableBeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (logger.isDebugEnabled()) { logger.debug('Bean factory for ' + getDisplayName() + ': ' + beanFactory); } return beanFactory;}

3、 BeanFactory的預準備工作

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // 1)、設置BeanFactory的類加載器 beanFactory.setBeanClassLoader(getClassLoader()); // 1)、設置支持表達式解析器 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));​ // 2)、添加部分BeanPostProcessor【ApplicationContextAwareProcessor】 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 3)、設置忽略的自動裝配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx; // 這些接口的實現類不能通過類型來自動注入 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);​ // 4)、注冊可以解析的自動裝配;我們能直接在任何組件中自動注入: //BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext /* 其他組件中可以通過下面方式直接注冊使用 @autowired BeanFactory beanFactory */ beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this);​ // 5)、添加BeanPostProcessor【ApplicationListenerDetector】后置處理器,在bean初始化前后的一些工作 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));​ // 6)、添加編譯時的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())); }​ // 7)、給BeanFactory中注冊一些能用的組件; if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { // 環境信息ConfigurableEnvironment beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } //系統屬性,systemProperties【Map<String, Object>】 if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } //系統環境變量systemEnvironment【Map<String, Object>】 if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); }}

5 執行BeanFactoryPostProcessor的后置處理器方法(BeanFactory);

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { //執行BeanFactoryPostProcessor的方法 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())); }}

5.1 執行invokeBeanFactoryPostProcessors

public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {​ // Invoke BeanDefinitionRegistryPostProcessors first, if any. Set<String> processedBeans = new HashSet<String>(); // 判斷beanFatory類型 if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>(); List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>(); //得到所有的BeanFactoryPostProcessor 遍歷 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<BeanDefinitionRegistryPostProcessor>();​ //從容器中獲取所有的BeanDefinitionRegistryPostProcessor, String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); // 第一步,先執行實現了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor 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); //執行BeanDefinitionRegistryPostProcessor的 postProcessor.postProcessBeanDefinitionRegistry(registry) invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear();​ // 在執行實現了Ordered順序接口的BeanDefinitionRegistryPostProcessor; 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); //執行postProcessor.postProcessBeanDefinitionRegistry(registry) invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear();​ // 最后執行沒有實現任何優先級或者是順序接口的BeanDefinitionRegistryPostProcessors; 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(); }​ // 現在執行 BeanFactoryPostProcessor的postProcessBeanFactory()方法 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); }​ else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); }​ //再執行BeanFactoryPostProcessor的方法 //1)、獲取所有的BeanFactoryPostProcessor 和執行BeanDefinitionRegistryPostProcessors的接口邏輯一樣 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);​ List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>(); List<String> orderedPostProcessorNames = new ArrayList<String>(); List<String> nonOrderedPostProcessorNames = new ArrayList<String>(); //把BeanFactoryPostProcessor 分類 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); } }​ // 2)、看先執行實現了PriorityOrdered優先級接口的BeanFactoryPostProcessor、 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);​ // 3)、在執行實現了Ordered順序接口的BeanFactoryPostProcessor; List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);​ // 4)、最后執行沒有實現任何優先級或者是順序接口的BeanFactoryPostProcessor; List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>(); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); beanFactory.clearMetadataCache();}

6、注冊BeanPostProcessor(Bean的后置處理器)

bean的創建攔截器

不同接口類型的BeanPostProcessor;在Bean創建前后的執行時機是不一樣的

BeanPostProcessor、 DestructionAwareBeanPostProcessor、 InstantiationAwareBeanPostProcessor、 在createBean()方法中處理的,bean創建之前調用的 SmartInstantiationAwareBeanPostProcessor、 MergedBeanDefinitionPostProcessor【internalPostProcessors】 (bean創建完成后調用,11章節中)

registerBeanPostProcessors(beanFactory);

​public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {//1)、獲取所有的 BeanPostProcessor;后置處理器都默認可以通過PriorityOrdered、Ordered接口來執行優先級 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);​ //檢查器,檢查所有的BeanPostProcessor 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<BeanPostProcessor>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>(); List<String> orderedPostProcessorNames = new ArrayList<String>(); List<String> nonOrderedPostProcessorNames = new ArrayList<String>(); 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); } }​ /* 2)、先注冊PriorityOrdered優先級接口的BeanPostProcessor; 把每一個BeanPostProcessor;添加到BeanFactory中 beanFactory.addBeanPostProcessor(postProcessor);*/ sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);​ // 3)、再注冊Ordered接口的 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>(); 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);​ // 4)、最后注冊沒有實現任何優先級接口的 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);​ // 5)、最終注冊MergedBeanDefinitionPostProcessor; sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors);​ // 6)、注冊一個ApplicationListenerDetector;判斷創建完成的bean是否監聽器 /* 在Bean創建完成后ApplicationListenerDetector.postProcessAfterInitialization()中檢查是否是ApplicationListener 類型,如果是applicationContext.addApplicationListener((ApplicationListener<?>) bean);如果是添加到容器中 */ beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));}

7、initMessageSource();國際化

初始化MessageSource組件(做國際化功能;消息綁定,消息解析);

​protected void initMessageSource() { // 1)、獲取BeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); /* 2)、看容器中是否有id為messageSource的,類型是MessageSource的組件 如果有賦值給messageSource,如果沒有自己創建一個DelegatingMessageSource; MessageSource作用:取出國際化配置文件中的某個key的值;能按照區域信息獲?。?*/ 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 { // 如果沒有自己創建一個DelegatingMessageSource; DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; //把創建好的messageSource注冊到容器中,以后獲取國際化配置文件的值的時候,可以自動注入MessageSource; //注入后通過這個方法使用MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale); 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 + ']'); } }}

8、初始化事件派發器initApplicationEventMulticaster()

​protected void initApplicationEventMulticaster() { //1)、獲取BeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //判斷容器中是否有applicationEventMulticaster 的這個bean ,如果有獲取,沒有創建 if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { //2)、從BeanFactory中獲取applicationEventMulticaster的ApplicationEventMulticaster; this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isDebugEnabled()) { logger.debug('Using ApplicationEventMulticaster [' + this.applicationEventMulticaster + ']'); } } else { //3) 個SimpleApplicationEventMulticaster 類型的 applicationEventMulticaster this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); //4)、將創建的ApplicationEventMulticaster添加到BeanFactory中,以后其他組件直接自動注入 beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isDebugEnabled()) { logger.debug('Unable to locate ApplicationEventMulticaster with name ’' + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + '’: using default [' + this.applicationEventMulticaster + ']'); } }}

9、onRefresh();留給子容器(子類)

1、子類重寫AbstractApplicationContext.onRefresh()這個方法,在容器刷新的時候可以自定義邏輯;

10、registerListeners();檢查和注冊 Listener

將所有項目里面的ApplicationListener注冊到容器中;

​protected void registerListeners() { //1、從容器中拿到所有的ApplicationListener for (ApplicationListener<?> listener : getApplicationListeners()) { //2、將每個監聽器添加到事件派發器中; getApplicationEventMulticaster().addApplicationListener(listener); }​ // 1.獲取所有的ApplicationListener String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { //2、將每個監聽器添加到事件派發器中; getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); }​ // earlyApplicationEvents 中保存之前的事件, Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { //3、派發之前步驟產生的事件; getApplicationEventMulticaster().multicastEvent(earlyEvent); } }}

11、初始化所有剩下的單實例bean;finishBeanFactoryInitialization(beanFactory);

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // 類型裝換器 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)); }​ //值解析器 if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { return 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();​ // 初始化剩下的單實例bean beanFactory.preInstantiateSingletons();}

11.1 beanFactory.preInstantiateSingletons()初始化剩下的單實例bean

//preInstantiateSingletons():781, DefaultListableBeanFactory public void preInstantiateSingletons() throws BeansException { if (this.logger.isDebugEnabled()) { this.logger.debug('Pre-instantiating singletons in ' + this); } //1)、獲取容器中的所有Bean,依次進行初始化和創建對象 List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames); for (String beanName : beanNames) { //2)、獲取Bean的定義信息;RootBeanDefinition RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //3)、Bean不是抽象的,是單實例的,不是懶加載; if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 3.1)、判斷是否是FactoryBean;是否是實現FactoryBean接口的Bean; if (isFactoryBean(beanName)) { final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { @Override public Boolean run() { return ((SmartFactoryBean<?>) factory).isEagerInit(); } }, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } else { //3.2)、不是工廠Bean。利用getBean(beanName);創建對象 getBean(beanName); //詳情請見 (11.1.3.2 創建bean ->doGetBean)章節 } } }​ // 循環所有的bean for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); //判斷bean是否實現了SmartInitializingSingleton 接口如果是;就執行afterSingletonsInstantiated(); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { smartSingleton.afterSingletonsInstantiated(); return null; } }, getAccessControlContext()); } else { //執行實現類的afterSingletonsInstantiated(); smartSingleton.afterSingletonsInstantiated(); } } }}

11.1.3.2 創建bean ->doGetBean

AbstractBeanFactory.doGetBean()方法

5)、將創建的Bean添加到緩存中singletonObjects;ioc容器就是這些Map;很多的Map里面保存了單實例Bean,環境信息。。。。;

protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {​ final String beanName = transformedBeanName(name); Object bean;​/**2、先獲取緩存中保存的單實例Bean。如果能獲取到說明這個Bean之前被創建過(所有創建過的單實例Bean都會被緩存起來)從private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);獲取的 **/ Object sharedInstance = getSingleton(beanName); //如果沒有獲取到創建bean 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 {//3、緩存中獲取不到,開始Bean的創建對象流程; // Fail if we’re already creating this bean instance: // We’re assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); }​ // 獲取父beanFatory 檢查這個bean是否創建了 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (args != null) { return (T) parentBeanFactory.getBean(nameToLookup, args); } else { return parentBeanFactory.getBean(nameToLookup, requiredType); } }​ // 4、標記當前bean已經被創建 if (!typeCheckOnly) { markBeanAsCreated(beanName); }​ try { // 5、獲取Bean的定義信息; final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args);​ // 6、【獲取當前Bean依賴的其他Bean;如果有按照getBean()把依賴的Bean先創建出來;】 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, 'Circular depends-on relationship between ’' + beanName + '’ and ’' + dep + '’'); } registerDependentBean(dep, beanName); getBean(dep); //先創建依賴的bean } }​ // 啟動單實例的bean的創建流程 if (mbd.isSingleton()) { //獲取到單實例bean后,添加到緩存中 singletonObjects() //Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256); sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { try { //創建Bean ,見11.1.3.2.6.1 return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); }// 下面部分不重要了 else if (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) { throw new IllegalStateException('No Scope registered for scope name ’' + scopeName + '’'); } try { Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try {return createBean(beanName, mbd, args); } finally {afterPrototypeCreation(beanName); } } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(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 { return getTypeConverter().convertIfNecessary(bean, requiredType); } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug('Failed to convert bean ’' + name + '’ to required type ’' +ClassUtils.getQualifiedName(requiredType) + '’', ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean;}

11.1.3.2.6.1 創建單實例bean

AbstractAutowireCapableBeanFactory.createBean() 這個類中

​protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug('Creating instance of bean ’' + beanName + '’'); } RootBeanDefinition mbdToUse = mbd; //bean定義信息​ // 解析bean的類型 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }​ // Prepare method overrides. try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, 'Validation of method overrides failed', ex); }​ try { //讓BeanPostProcessor先攔截返回代理對象; /** 判斷是否為:InstantiationAwareBeanPostProcessor 的,如果是執行前后置方法 【InstantiationAwareBeanPostProcessor】:提前執行; 先觸發:postProcessBeforeInstantiation(); 如果有返回值:再觸發postProcessAfterInitialization(); **/ Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { //如果 有對象返回 return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, 'BeanPostProcessor before instantiation of bean failed', ex); } // 沒有對象 創建一個bean Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isDebugEnabled()) { logger.debug('Finished creating instance of bean ’' + beanName + '’'); } //返回創建的bean return beanInstance;}

1、doCreateBean()創建一個bean

后置處理器:MergedBeanDefinitionPostProcessor ,bean實例化之后調用

//doCreateBean():508, AbstractAutowireCapableBeanFactory 類中protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException {​ // bean的包裝 BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 1)、【創建Bean實例】利用工廠方法或者對象的構造器創建出Bean實例; instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); mbd.resolvedTargetType = beanType;​ // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { //調用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName); //判斷是否為:MergedBeanDefinitionPostProcessor 類型的,如果是,調用方法 //MergedBeanDefinitionPostProcessor 后置處理器是在bean實例換之后調用的 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, 'Post-processing of merged bean definition failed', ex); } mbd.postProcessed = true; } }​ //判斷bean 是否為單實例的,如果是單實例的添加到緩存中 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isDebugEnabled()) { logger.debug('Eagerly caching bean ’' + beanName + '’ to allow for resolving potential circular references'); } //添加bean到緩存中 addSingletonFactory(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); }​ // Initialize the bean instance. Object exposedObject = bean; try { //為bean 賦值,見1.1部分 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { // 4)、【Bean初始化】 exposedObject = initializeBean(beanName, exposedObject, mbd); } } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, 'Initialization of bean failed', ex); } }​ if (earlySingletonExposure) { //獲取單實例bean,此時已經創建好了 Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(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.'); } } } }​ // 5)、注冊實現了DisposableBean 接口Bean的銷毀方法;只是注冊沒有去執行,容器關閉之后才去調用的 try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, 'Invalid destruction signature', ex); }​ return exposedObject;}

1.1 populateBean()創建bean后屬性賦值

//populateBean():1204, AbstractAutowireCapableBeanFactory protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { PropertyValues pvs = mbd.getPropertyValues();​ if (bw == null) { if (!pvs.isEmpty()) { throw new BeanCreationException( 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. boolean continueWithPropertyPopulation = true;​ //賦值之前: /* 1)、拿到InstantiationAwareBeanPostProcessor后置處理器; 執行處理器的postProcessAfterInstantiation(); 方法*/ if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //執行 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; } } } }​ if (!continueWithPropertyPopulation) { return; }​ if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs);​ // autowire 按name注入 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); }​ // autowire 按類型注入 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); }​ pvs = newPvs; }​ boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);/*2)、拿到InstantiationAwareBeanPostProcessor后置處理器; 執行 postProcessPropertyValues(); 獲取到屬性的值,此時還未賦值*/ if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } }//=====賦值之前:=== //3)、應用Bean屬性的值;為屬性利用setter方法等進行賦值; applyPropertyValues(beanName, mbd, bw, pvs);}

1.2 、Bean初始化 initializeBean

initializeBean():1605, AbstractAutowireCapableBeanFactory

//初始化protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { invokeAwareMethods(beanName, bean); return null; } }, getAccessControlContext()); } else { //1)、【執行Aware接口方法】invokeAwareMethods(beanName, bean);執行xxxAware接口的方法 //判斷是否實現了 BeanNameAwareBeanClassLoaderAwareBeanFactoryAware 這些接口的bean,如果是執行相應的方法 invokeAwareMethods(beanName, bean); }​ Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { //2)、【執行后置處理器BeanPostProcessor初始化之前】 執行所有的 BeanPostProcessor.postProcessBeforeInitialization(); wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); }​ try { //3)、【執行初始化方法】 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, 'Invocation of init method failed', ex); } //4)、【執行后置處理器初始化之后】 執行所有的beanProcessor.postProcessAfterInitialization(result, beanName);方法 if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean;}

1.2.1 執行bean的初始化方法init

1)、是否是InitializingBean接口的實現;執行接口規定的初始化;

2)、是否自定義初始化方法;通過注解的方式添加了initMethod方法的,

​ 例如: @Bean(initMethod='init',destroyMethod='detory')

//invokeInitMethods():1667, AbstractAutowireCapableBeanFactory protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {//1)、是否是InitializingBean接口的實現;執行接口規定的初始化 ,執行afterPropertiesSet()這個方法; boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod('afterPropertiesSet'))) { if (logger.isDebugEnabled()) { logger.debug('Invoking afterPropertiesSet() on bean with name ’' + beanName + '’'); } if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ((InitializingBean) bean).afterPropertiesSet(); return null; } }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { //執行實現InitializingBean的afterPropertiesSet方法 ((InitializingBean) bean).afterPropertiesSet(); } }​ if (mbd != null) { //執行通過注解自定義的initMethod 方法 String initMethodName = mbd.getInitMethodName(); if (initMethodName != null && !(isInitializingBean && 'afterPropertiesSet'.equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { invokeCustomInitMethod(beanName, bean, mbd); } }}

12、完成BeanFactory的初始化創建工作;IOC容器就創建完成;刷新

protected void finishRefresh() { //1. 初始化生命周期有關的后置處理器,BeanFactory創建完成后刷新相關的工作 //默認從容器中找是否有lifecycleProcessor的組件【LifecycleProcessor】;如果沒有new DefaultLifecycleProcessor();加入到容器; initLifecycleProcessor(); //2. 拿到前面定義的生命周期處理器(LifecycleProcessor);回調onRefresh(); getLifecycleProcessor().onRefresh();​ //3. 發布容器刷新完成事件; publishEvent(new ContextRefreshedEvent(this));​ //4.暴露 LiveBeansView.registerApplicationContext(this);}

二、Spring 啟動流程的總結

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;事件派發:

總結

到此這篇關于Spring啟動流程refresh()源碼深入解析的文章就介紹到這了,更多相關Spring 啟動流程refresh()源碼內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 丁香婷婷影音先锋5566 | 国产成人tv在线观看 | 亚洲午夜一区二区三区 | 国产三级a三级三级天天 | 亚洲爽| 精品在线观看国产 | 欧美日韩中文一区二区三区 | 国产看片视频 | 99视频九九精品视频在线观看 | 91成人免费在线视频 | 成人午夜私人影院入口 | 欧美亚洲另类久久综合 | a级精品九九九大片免费看 a级毛片免费观看网站 | 天天看夜夜操 | 在线观看亚洲免费 | 美女被免费网站在线视频软件 | 久久6视频| 67194国产精品 | 日韩美女视频网站 | 高清精品女厕在线观看 | 成年人免费网站视频 | japanese色系国产在线高清 | 中文字幕一区日韩在线视频 | 在线播放国产真实女同事 | 九九99九九在线精品视频 | 亚洲综合无码一区二区 | 偷拍精品视频一区二区三区 | 一级毛片私人影院免费 | 最近免费手机中文字幕3 | 国产男女爽爽爽爽爽视频 | 欧美精品久久天天躁 | www中文字幕在线观看 | 经典香港a毛片免费观看 | 精品欧美一区二区精品久久 | 我要看a级毛片 | 99爱视频| 日韩久久影院 | 国产在线观看网址你懂得 | 成人国产在线看不卡 | 97在线看 | 久草在线新视频 |