• 【spring 注解驱动开发】spring ioc 原理


    尚学堂spring 注解驱动开发学习笔记之 - Spring容器创建

    Spring容器创建

      1、Spring容器创建-BeanFactory预准备
      2、Spring容器创建-执行BeanFactoryPostProcessor
      3、Spring容器创建-注册BeanPostProcessors
      4、Spring容器创建-初始化MessageSource
      5、Spring容器创建-初始化事件派发器、监听器等
      6、Spring容器创建-创建Bean
      7、Spring容器创建-容器创建完成
      8、Spring源码总结

    一、总体流程

    AnnotationConfigApplicationContext类的构造器方法

    public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
    		this();
    		register(componentClasses);
    		refresh();
    	}
    

    AbstractApplicationContext类中的refresh()方法,即为spring容器的创建/刷数流程

    @Override
    	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();
    			}
    		}
    	} 

    二、详细分析

    1、Spring容器创建-BeanFactory预准备

    BeanFactory的创建及预准备工作

    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的创建及预准备工作==================================

    对应的以下步骤:

    			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);

    2、Spring容器创建-执行BeanFactoryPostProcessor

    执行BeanFactoryPostProcessor的方法;

    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()  

    对应执行的代码:

    // Invoke factory processors registered as beans in the context.
    invokeBeanFactoryPostProcessors(beanFactory);
    
    具体invokeBeanFactoryPostProcessors(beanFactory)方法为:
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    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()));
    		}
    	}
    
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    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();
    	}  

    3、Spring容器创建-注册BeanPostProcessors

    注册BeanPostProcessor(Bean的后置处理器)

    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); 

    对应执行的代码:

    // Register bean processors that intercept bean creation.
    registerBeanPostProcessors(beanFactory);
    

    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);

    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));
    	}
    

    4、Spring容器创建-初始化MessageSource

    初始化MessageSource组件

    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);  

    对应执行的代码:

    // Initialize message source for this context.
    initMessageSource();
    
    initMessageSource();
    /**
    	 * Initialize the MessageSource.
    	 * Use parent's if none defined in this context.
    	 */
    	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.isTraceEnabled()) {
    				logger.trace("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.isTraceEnabled()) {
    				logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
    			}
    		}
    	}
    

    5、Spring容器创建-初始化事件派发器、监听器等

    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、派发之前步骤产生的事件;

    对应执行的代码:

    // 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();

    6、Spring容器创建-创建Bean准备

    初始化所有剩下的单实例bean:

    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接口的方法
    						 		BeanNameAwareBeanClassLoaderAwareBeanFactoryAware
    						 	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,环境信息。。。。;即这些所有的Map就构成了ioc容器。
    		所有Bean都利用getBean创建完成以后;
    			检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();

    对应代码

    // Instantiate all remaining (non-lazy-init) singletons.
    finishBeanFactoryInitialization(beanFactory);
    

    AbstractApplicationContext类的finishBeanFactoryInitialization(beanFactory);  

    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();
    	}
    

    DefaultListableBeanFactory类的preInstantiateSingletons()方法  

    @Override
    	public void preInstantiateSingletons() 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.
    		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    
    		// Trigger initialization of all non-lazy singleton beans...
    		for (String beanName : beanNames) {
    			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
    				if (isFactoryBean(beanName)) {
    					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
    					if (bean instanceof FactoryBean) {
    						final FactoryBean<?> factory = (FactoryBean<?>) bean;
    						boolean isEagerInit;
    						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
    							isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
    											((SmartFactoryBean<?>) factory)::isEagerInit,
    									getAccessControlContext());
    						}
    						else {
    							isEagerInit = (factory instanceof SmartFactoryBean &&
    									((SmartFactoryBean<?>) factory).isEagerInit());
    						}
    						if (isEagerInit) {
    							getBean(beanName);
    						}
    					}
    				}
    				else {
    					getBean(beanName);
    				}
    			}
    		}
    
    		// Trigger post-initialization callback for all applicable beans...
    		for (String beanName : beanNames) {
    			Object singletonInstance = getSingleton(beanName);
    			if (singletonInstance instanceof SmartInitializingSingleton) {
    				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
    				if (System.getSecurityManager() != null) {
    					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    						smartSingleton.afterSingletonsInstantiated();
    						return null;
    					}, getAccessControlContext());
    				}
    				else {
    					smartSingleton.afterSingletonsInstantiated();
    				}
    			}
    		}
    	}
    

    AbstractBeanFactory类的getBean(String name)方法  

            @Override
    	public Object getBean(String name) throws BeansException {
    		return doGetBean(name, null, null, false);
    	}    
    

    AbstractBeanFactory类的doGetBean(name, null, null, false);方法。创建bean的最终执行方法  

    @SuppressWarnings("unchecked")
    	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
    			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    
    		final String beanName = transformedBeanName(name);
    		Object bean;
    
    		// Eagerly check singleton cache for manually registered singletons.
    		Object sharedInstance = 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 + "'");
    				}
    			}
    			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)) {
    				throw new BeanCurrentlyInCreationException(beanName);
    			}
    
    			// Check if bean definition exists in this factory.
    			BeanFactory parentBeanFactory = getParentBeanFactory();
    			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
    				// Not found -> check parent.
    				String nameToLookup = originalBeanName(name);
    				if (parentBeanFactory instanceof AbstractBeanFactory) {
    					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
    							nameToLookup, requiredType, args, typeCheckOnly);
    				}
    				else if (args != null) {
    					// Delegation to parent with explicit args.
    					return (T) parentBeanFactory.getBean(nameToLookup, args);
    				}
    				else if (requiredType != null) {
    					// No args -> delegate to standard getBean method.
    					return parentBeanFactory.getBean(nameToLookup, requiredType);
    				}
    				else {
    					return (T) parentBeanFactory.getBean(nameToLookup);
    				}
    			}
    
    			if (!typeCheckOnly) {
    				markBeanAsCreated(beanName);
    			}
    
    			try {
    				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    				checkMergedBeanDefinition(mbd, beanName, args);
    
    				// Guarantee initialization of beans that the current bean depends on.
    				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);
    						try {
    							getBean(dep);
    						}
    						catch (NoSuchBeanDefinitionException ex) {
    							throw new BeanCreationException(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);
    				}
    
    				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, () -> {
    							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 && !requiredType.isInstance(bean)) {
    			try {
    				T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
    				if (convertedBean == null) {
    					throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    				}
    				return convertedBean;
    			}
    			catch (TypeMismatchException ex) {
    				if (logger.isTraceEnabled()) {
    					logger.trace("Failed to convert bean '" + name + "' to required type '" +
    							ClassUtils.getQualifiedName(requiredType) + "'", ex);
    				}
    				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    			}
    		}
    		return (T) bean;
    	}
    

    7、Spring容器创建-容器创建完成

    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);
    

    执行的代码

    // Last step: publish corresponding event.
    finishRefresh();
    

    finishRefresh();

    protected void finishRefresh() {
    		// Clear context-level resource caches (such as ASM metadata from scanning).
    		clearResourceCaches();
    
    		// Initialize lifecycle processor for this context.
    		initLifecycleProcessor();
    
    		// Propagate refresh to lifecycle processor first.
    		getLifecycleProcessor().onRefresh();
    
    		// Publish the final event.
    		publishEvent(new ContextRefreshedEvent(this));
    
    		// Participate in LiveBeansView MBean, if active.
    		LiveBeansView.registerApplicationContext(this);
    	}
    

    8、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;事件派发:
  • 相关阅读:
    从数据仓库系统对比看Hive发展前景
    Greenplum技术浅析
    MySQL索引背后的数据结构及算法原理zz
    超详细单机版搭建hadoop环境图文解析
    ActionScript 3.0 Step By Step系列(六):学对象事件模型,从点击按扭开始
    ActionScript 3.0 Step By Step系列(五):走在面向对象开发的路上,以类为基础去思考编程问题
    ActionScript 3.0 Step By Step系列(八):动态的数据展现源于灵活的数据绑定
    ActionScript 3.0 Step By Step系列(七):使用XML和XMLList类处理XML数据
    高质量的开源Flex UI组件库项目(FlexLib)
    什么是回调 CallBack
  • 原文地址:https://www.cnblogs.com/wjqhuaxia/p/12262250.html
Copyright © 2020-2023  润新知