spring源码分析

通过main方法作为入口

public static void main(String[] args) {
    AnnotationConfigApplicationContext annotationConfigApplicationContext =
        new AnnotationConfigApplicationContext(RetryAspectConfig.class);
    String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
    System.out.println(Arrays.toString(beanDefinitionNames));
  }

重点看refresh方法

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

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();
			}
		}
	}
1.prepareRefresh()刷新前的预处理,主要做了三件事
protected void prepareRefresh() {
		...
		// Initialize any placeholder property sources in the context environment.
		initPropertySources();
		// Validate that all properties marked as required are resolvable:
		// see ConfigurablePropertyResolver#setRequiredProperties
		getEnvironment().validateRequiredProperties();
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}
  • initPropertySources()初始化一些属性设置,子类自定义个性化的属性设置方法.
  • getEnvironment().validateRequiredProperties(),检验属性的合法等
  • earlyApplicationEvents= new LinkedHashSet(),保存容器中的一些早期的事件.
2.obtainFreshBeanFactory(),获取BeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		return getBeanFactory();
	}
  • org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory,刷新【创建】BeanFactory
    protected final void refreshBeanFactory() throws BeansException {
    		...
    		try {
    			// 调用createBeanFactory方法创建BeanFactory
    			DefaultListableBeanFactory beanFactory = createBeanFactory();
    			// 设置id
    			beanFactory.setSerializationId(getId());
    			customizeBeanFactory(beanFactory);
    			loadBeanDefinitions(beanFactory);
    			this.beanFactory = beanFactory;
    		}
    	}
    
    • 创建了一个this.beanFactory = new DefaultListableBeanFactory()
    • 设置id
  • org.springframework.context.support.GenericApplicationContext#getBeanFactory;返回刚才GenericApplicationContext创建的BeanFactory对象
  • 将创建的BeanFactory【DefaultListableBeanFactory】返回
3.prepareBeanFactory(ConfigurableListableBeanFactory beanFactory),BeanFactory的预准备工作(BeanFactory进行一些设置)
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		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());
		}
	}
  • 设置BeanFactory的类加载器、支持表达式解析器…
  • 添加部分BeanPostProcessor【ApplicationContextAwareProcessor】
    	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
    	this.applicationContext = applicationContext;
    	this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
    }
    
  • 设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware…
  • 注册可以解析的自动装配,我们能直接在任何组件中自动注入:BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
  • 添加BeanPostProcessor【ApplicationListenerDetector】
  • 添加编译时的AspectJ
  • 给BeanFactory中注册一些能用的组件environment[ConfigurableEnvironment]、org.springframework.core.env.AbstractEnvironment#getSystemProperties[Map]、org.springframework.core.env.AbstractEnvironment#getSystemEnvironment[Map]
4.postProcessBeanFactory(beanFactory),BeanFactory准备工作完成后进行的后置处理工作
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	}
  • 子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置
    以上是BeanFactory的创建及预准备工作
5.nvokeBeanFactoryPostProcessors(beanFactory),执行BeanFactoryPostProcessor的方法

涉及两个接口:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
它俩的关系:
> public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
...
		}
	}
  • org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List)
    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);
    			}
    		}
    		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();
    		}
    		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    	}
    
    	else {
    invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    	}
    	String[] postProcessorNames =
    			beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    	// 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<>(orderedPostProcessorNames.size());
    	for (String postProcessorName : orderedPostProcessorNames) {
    		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    	}
    	sortPostProcessors(orderedPostProcessors, beanFactory);
    	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
    
    	// Finally, invoke all other BeanFactoryPostProcessors.
    	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    	for (String postProcessorName : nonOrderedPostProcessorNames) {
    		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    	}
    	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
    	beanFactory.clearMetadataCache();
    }
    
    • 先执行BeanDefinitionRegistryPostProcessor

      if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
      			BeanDefinitionRegistryPostProcessor registryProcessor =
      					(BeanDefinitionRegistryPostProcessor) postProcessor;
      			registryProcessor.postProcessBeanDefinitionRegistry(registry);
      			registryProcessors.add(registryProcessor);
      		}
      
      • 获取所有的BeanDefinitionRegistryPostProcessor
      • 看先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor、
        postProcessor.postProcessBeanDefinitionRegistry(registry)
      • 再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;
        postProcessor.postProcessBeanDefinitionRegistry(registry)
      • 最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
        postProcessor.postProcessBeanDefinitionRegistry(registry)
    • 再执行BeanFactoryPostProcessor的方法

      • 获取所有的BeanFactoryPostProcessor
      • 剩下流程与上边一样 priority、order、common
6.registerBeanPostProcessors(beanFactory);注册BeanPostProcessor(Bean的后置处理器)
	BeanPostProcessor、
	DestructionAwareBeanPostProcessor、
	InstantiationAwareBeanPostProcessor、
	SmartInstantiationAwareBeanPostProcessor、
	MergedBeanDefinitionPostProcessor【internalPostProcessors】

不同接口类型的BeanPostProcessor;在Bean创建前后的执行时机是不一样的

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
	}
  • 获取所有的 BeanPostProcessor,后置处理器都默认可以通过PriorityOrdered、Ordered接口来执行优先级
    	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
    	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    	List<String> orderedPostProcessorNames = new ArrayList<>();
    	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    
  • 先注册PriorityOrdered优先级接口的BeanPostProcessor,把每一个BeanPostProcessor,添加到BeanFactory中
    private static void registerBeanPostProcessors(
    		ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
    
    	for (BeanPostProcessor postProcessor : postProcessors) {			// 所谓的注册就是把postProcessor 加入到
    		beanFactory.addBeanPostProcessor(postProcessor);
    	}
    }
    
  • 再注册Ordered接口的
  • 最后注册没有实现任何优先级接口的
  • 最终注册MergedBeanDefinitionPostProcessor
  • 注册一个ApplicationListenerDetector,来在Bean创建完成后检查是否是ApplicationListener,如果是,添加
    applicationContext.addApplicationListener((ApplicationListener<?>) bean);
    
7.initMessageSource(),初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
protected void initMessageSource() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
			this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
			if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
				HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
				if (hms.getParentMessageSource() == null) {	hms.setParentMessageSource(getInternalParentMessageSource());
				}
			}
		}
		else {
			DelegatingMessageSource dms = new DelegatingMessageSource();
			dms.setParentMessageSource(getInternalParentMessageSource());
			this.messageSource = dms;
			beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
		}
	}
  • 获取BeanFactory
    ConfigurableListableBeanFactory beanFactory = getBeanFactory()
    
  • 看容器中是否有id为messageSource的,类型是MessageSource的组件,如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource,[MessageSource:取出国际化配置文件中的某个key的值,能按照区域信息获取]
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
    		this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
    }else {
    		// Use empty MessageSource to be able to accept getMessage calls.
    		DelegatingMessageSource dms = new DelegatingMessageSource();
    		dms.setParentMessageSource(getInternalParentMessageSource());
    		this.messageSource = dms;
    	}
    	
    
  • 把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource
    beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
    
8.initApplicationEventMulticaster(),初始化事件派发器
  • 获取beanFactory
    ConfigurableListableBeanFactory beanFactory = getBeanFactory()
    
  • 从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster
    this.applicationEventMulticaster =
    				beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class);
    
  • 如果上一步没有配置,创建一个SimpleApplicationEventMulticaster
    this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
    		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
    
  • 将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入
9.onRefresh(),留给子容器(子类)
10.registerListeners(),给容器中将所有项目里面的ApplicationListener注册进来
  • 从容器中拿到所有的ApplicationListener
  • 将每个监听器添加到事件派发器中
    getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    
  • 派发之前步骤产生的事件
  • 派发之前步骤产生的事件
    getApplicationEventMulticaster().multicastEvent(earlyEvent)
    
11.finishBeanFactoryInitialization(beanFactory);初始化所有剩下的单实例bean
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		...
		// Instantiate all remaining (non-lazy-init) singletons.
		beanFactory.preInstantiateSingletons();
	}
  • beanFactory.preInstantiateSingletons(),初始化后剩下的单实例bean
    • 获取容器中的所有Bean,依次进行初始化和创建对象
      for (String beanName : beanNames) {
      }
      
    • 获取Bean的定义信息;RootBeanDefinition
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      
    • Bean不是抽象的,是单实例的,是懒加载;
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit())
      
      • 判断是否是FactoryBean,是否是实现FactoryBean接口的Bean.

        public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
        String beanName = transformedBeanName(name);
        Object beanInstance = getSingleton(beanName, false);
        if (beanInstance != null) {
        	return (beanInstance instanceof FactoryBean);
        }
        // No singleton instance found -> check bean definition.
        if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        	// No bean definition found in this factory -> delegate to parent.
        	return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
        }
        return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
        
      }
      ```
      • 不是工厂Bean。利用getBean(beanName)创建对象
        • getBean(beanName)

        • doGetBean(name, null, null, false)

        • 先获取缓存中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)

          			protected Object getSingleton(String beanName, boolean allowEarlyReference) {
          	// Quick check for existing instance without full singleton lock
          	Object singletonObject = this.singletonObjects.get(beanName);
          	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
          		singletonObject = this.earlySingletonObjects.get(beanName);
          		if (singletonObject == null && allowEarlyReference) {
          			synchronized (this.singletonObjects) {
          				// Consistent creation of early reference within full singleton lock
          				singletonObject = this.singletonObjects.get(beanName);
          				if (singletonObject == null) {
          					singletonObject = this.earlySingletonObjects.get(beanName);
          					if (singletonObject == null) {
          						ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
          						if (singletonFactory != null) {
          							singletonObject = singletonFactory.getObject();
          							this.earlySingletonObjects.put(beanName, singletonObject);
          							this.singletonFactories.remove(beanName);
          						}
          					}
          				}
          			}
          		}
          	}
          	return singletonObject;
          }
          
        private final Map singletonObjects = new ConcurrentHashMap<>(16);
        • 缓存中获取不到,开始Bean的创建对象流程

        • 标记当前bean已经被创建

          if (!typeCheckOnly) {
          				markBeanAsCreated(beanName);
          			}
          
        • 获取Bean的定义信息

        • 获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来

          String[] dependsOn = mbd.getDependsOn();
          
        • 启动单实例Bean的创建流程

          if (mbd.isSingleton()) {
          	sharedInstance = getSingleton(beanName, () -&gt; {
          		try {
          			return createBean(beanName, mbd, args);
          		}
          		catch (BeansException ex) {
          			destroySingleton(beanName);
          			throw ex;
          		}
          	});
          
          • createBean(beanName, mbd, args)

          • Object bean = resolveBeforeInstantiation(beanName,mbdToUse),让BeanPostProcessor先拦截返回代理对象.

          • 如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象

          • Object beanInstance = doCreateBean(beanName, mbdToUse, args);创建Bean

            protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
              throws BeanCreationException {
            ...
            if (instanceWrapper == null) {
              // createBeanInstance(beanName, mbd, args),利用工厂方法或者对象的构造器创建出Bean实例
              instanceWrapper = createBeanInstance(beanName, mbd, args);
            }
            Object bean = instanceWrapper.getWrappedInstance();
            Class&lt;?&gt; beanType = instanceWrapper.getWrappedClass();
            if (beanType != NullBean.class) {
              mbd.resolvedTargetType = beanType;
            }
            
            synchronized (mbd.postProcessingLock) {
              if (!mbd.postProcessed) {
                try {
                  // 调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
                  applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                ...
                mbd.postProcessed = true;
              }
            }
            
            boolean earlySingletonExposure = (mbd.isSingleton() &amp;&amp; this.allowCircularReferences &amp;&amp;
                isSingletonCurrentlyInCreation(beanName));
            if (earlySingletonExposure) {
              addSingletonFactory(beanName, () -&gt; getEarlyBeanReference(beanName, mbd, bean));
            }
            
            Object exposedObject = bean;
            try {
              // Bean属性赋值
              // populateBean方法中:拿到InstantiationAwareBeanPostProcessor后置处理器,postProcessAfterInstantiation();拿到InstantiationAwareBeanPostProcessor后置处理器,postProcessPropertyValues()
              // 应用Bean属性的值:为属性利用setter方法等进行赋值,applyPropertyValues(beanName, mbd, bw, pvs)
              populateBean(beanName, mbd, instanceWrapper);
              // 初始化bean
              // [执行Aware接口方法]invokeAwareMethods(beanName,bean);执行Aware接口的方法BeanNameAware\BeanClassLoaderAware\BeanFactoryAware
              // [执行后置处理器初始化之前]applyBeanPostProcessorsBeforeInitialization(wrappedBean,beanName);BeanPostProcessor.postProcessBeforeInitialization()
              // [执行初始化方法]invokeInitMethods(beanName, wrappedBean, mbd)
              // [执行后置处理器初始化之后]applyBeanPostProcessorsAfterInitialization,BeanPostProcessor.postProcessAfterInitialization()
              exposedObject = initializeBean(beanName, exposedObject, mbd);
            }
            ...
            try {
              // 注册Bean的销毁方法
              registerDisposableBeanIfNecessary(beanName, bean, mbd);
            }
            catch (BeanDefinitionValidationException ex) {
              throw new BeanCreationException(
                  mbd.getResourceDescription(), beanName, &quot;Invalid destruction signature&quot;, ex);
            }
            
            return exposedObject;
            }
            
          • 将创建的Bean添加到缓存中singletonObjects
            ioc容器就是这些Map;很多的Map里面保存了单实例Bean,环境信息…所有Bean都利用getBean创建完成以后,检查所有的Bean是否是SmartInitializingSingleton接口的,如果是,就执行afterSingletonsInstantiated()

12.finishRefresh(),完成BeanFactory的初始化创建工作,IOC容器就创建完成
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);
	}
  • initLifecycleProcessor();初始化和生命周期有关的后置处理器
  • 拿到前面定义的生命周期处理器(BeanFactory),回调onRefresh()
  • publishEvent(new ContextRefreshedEvent(this));发布容器刷新完成事件
  • liveBeansView.registerApplicationContext(this);

总结

  1. Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息
    • xml注册bean,
    • 注解注册Bean,@Service、@Component、@Bean…
  2. Spring容器会合适的时机创建这些Bean
    • 用到这个bean的时候,利用getBean创建bean,创建好以后保存在容器中
    • 统一创建剩下所有的bean的时候
  3. 后置处理器BeanPostProcessor
    • 每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能
      > AutowiredAnnotationBeanPostProcessor:处理自动注入,AnnotationAwareAspectJAutoProxyCreator:来做AOP功能…
  4. 事件驱动模型
    • ApplicationListener事件监听
    • ApplicationEventMulticaster事件派发

你可能感兴趣的:(spring,java,大数据)