Spring基于注解的IOC初始化过程(较长慎入)

Spring中基于注解的IOC容器初始化过程

文章目录

入口

我们以测试类中的这行代码为入口,来一起看一下Spring注解下是如何初始化IOC容器的。

ApplicationContext ioc = new AnnotationConfigApplicationContext(xxxConfig.class);

AnnotationConfigApplicationContext

AnnotationConfigApplicationContext是Spring注解模式下的应用上下文对象,当我们创建IOC容器时,会首先调用该类的构造方法来执行初始化操作。

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

一:初始化之构造方法——this()

可以看到无参构造中主要初始化了注解下Bean定义阅读器AnnotatedBeanDefinitionReader)及类路径下Bean定义的扫描器ClassPathBeanDefinitionScanner)。

// AnnotationConfigApplicationContext 的无参构造
public AnnotationConfigApplicationContext() {
    StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
    this.reader = new AnnotatedBeanDefinitionReader(this); //位置1
    createAnnotatedBeanDefReader.end();
	// 一个bean定义的扫描器,用来扫描类路径上的bean,主要是Spring在初始化早期提供给我们使用
    this.scanner = new ClassPathBeanDefinitionScanner(this);
}

注:StartupStep(DefaultApplicationStartup)用来标记容器初始化过程中的执行步骤。

初始化的第一步

我们来一起看一下AnnotationConfigApplicationContext调用构造方法 this() 时都做了什么(上步骤代码位置1):

首先进入 AnnotatedBeanDefinitionReader 的构造方法:

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
    this(registry, getOrCreateEnvironment(registry));
}

可以看到内部调用了另外一个有参构造:

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
    Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
    Assert.notNull(environment, "Environment must not be null");
    this.registry = registry;
    this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
 	//位置1
    AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

继续深入位置1

public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
   registerAnnotationConfigProcessors(registry, null);
}

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
    if (beanFactory != null) {
        if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
            beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
        }
        if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
            beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
        }
    }

    Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

    if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition();
        try {
            def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
                                                AnnotationConfigUtils.class.getClassLoader()));
        }
        catch (ClassNotFoundException ex) {
            throw new IllegalStateException(
                "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
        }
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
    }

    if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
    }

    return beanDefs;
}

通过上面这个方法 registerAnnotationConfigProcessors() ,完成了第一步对一些系统级处理器的注册,他们的id和name分别如下所示:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
	org.springframework.context.annotation.ConfigurationClassPostProcessor // BeanDefinitionRegistryPostProcessor实现类
    
org.springframework.context.event.internalEventListenerFactory
	org.springframework.context.event.DefaultEventListenerFactory
    
org.springframework.context.event.internalEventListenerProcessor
	org.springframework.context.event.EventListenerMethodProcessor // BeanFactoryPostProcessor 实现类
    
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor // BeanPostProcessor 
    
org.springframework.context.annotation.internalCommonAnnotationProcessor
	org.springframework.context.annotation.CommonAnnotationBeanPostProcessor // BeanPostProcessor

接下来的流程中我们会提到这些组件在初始化流程中的使用。

二:初始化之——register(componentClasses)

从上一步我们知道,在 this() 中初始化了 AnnotatedBeanDefinitionReader,这一步就是使用这个AnnotatedBeanDefinitionReader来将我们传入的配置类xxxConfig.class 注册到BeanFactory

@Override
public void register(Class<?>... componentClasses) {
    Assert.notEmpty(componentClasses, "At least one component class must be specified");
    StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
        .tag("classes", () -> Arrays.toString(componentClasses));
    // 注册配置类
    this.reader.register(componentClasses);
    registerComponentClass.end();
}
// AnnotatedBeanDefinitionReader中的register()方法
public void register(Class<?>... componentClasses) {
    for (Class<?> componentClass : componentClasses) {
        registerBean(componentClass); // 注册配置类
    }
}

如上代码所示,register() 方法通过 AnnotatedBeanDefinitionReader 将我们传入的一个或多个配置类注册到Bean定义中

总结:

经过一、二两个步骤的处理,Spring将前期初始化需要用到的一些组件和我们的配置类就加入到了Bean定义信息中

三:初始化的关键——refresh()

AbstractApplicationContext.refresh() 方法内容如下:

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 记录步骤信息
        StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
        // 准备工作
        prepareRefresh();
		// 初始化BeanDefinition并获取beanFactory
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		// 准备BeanFactory 的一些内容
        prepareBeanFactory(beanFactory);
        try {
            // 模版方法,我们可以通过子类实现BeanFactory后置处理
            postProcessBeanFactory(beanFactory);
			// 记录步骤信息
            StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
            // 调用BeanFactory后置处理
            invokeBeanFactoryPostProcessors(beanFactory);
			// 注册Bean的后置处理器
            registerBeanPostProcessors(beanFactory);
            
            beanPostProcess.end();
            // Initialize message source for this context.
            initMessageSource();
			// 初始化上下文事件派发器
            initApplicationEventMulticaster();
            // 模版方法
            onRefresh();
			// 注册监听器
            registerListeners();
			// 初始化剩下的单实例Bean
            finishBeanFactoryInitialization(beanFactory);
			// 发布完成事件等操作
            finishRefresh();
        }
        catch (BeansException ex) {
            // 异常处理...
        }
        finally {
            resetCommonCaches();
            contextRefresh.end();
        }
    }
}

接下来我们在后续的步骤中一步步看里面做了什么操作。

1,准备工作——prepareRefresh()

进行IOC初始化前的一些准备工作,如:初始化容器状态、设置启动时间等操作

protected void prepareRefresh() {
    this.startupDate = System.currentTimeMillis();// 设置启动时间
    this.closed.set(false); // 设置初始化状态
    this.active.set(true);

    if (logger.isDebugEnabled()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Refreshing " + this);
        }
        else {
            logger.debug("Refreshing " + getDisplayName());
        }
    }
	// 模版方法 初始化一些属性设置,子类自定义个性化的属性设置方法
    initPropertySources();
	// 校验属性合法性等
    getEnvironment().validateRequiredProperties();

    if (this.earlyApplicationListeners == null) {
        this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    }
    else {
        this.applicationListeners.clear();
        this.applicationListeners.addAll(this.earlyApplicationListeners);
    }
	// 初始化早期事件
    this.earlyApplicationEvents = new LinkedHashSet<>();
}

2,获取BeanFactory——obtainFreshBeanFactory()

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   refreshBeanFactory();
   return getBeanFactory();
}
2.1,refreshBeanFactory()

该方法用来刷新BeanFactory, 源码如下

// GenericApplicationContext 中的 refreshBeanFactory() 
@Override
protected final void refreshBeanFactory() throws IllegalStateException {
	// 设置刷新状态
    if (!this.refreshed.compareAndSet(false, true)) {
        // 更新状态失败则抛出异常
        throw new IllegalStateException(
            "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
    }
    // 设置当前BeanFactory的序列化id
    this.beanFactory.setSerializationId(getId());
}
2.2,getBeanFactory()

返回刚才设置好状态的BeanFactory。

备注:创建GenericApplicationContext时,会初始化Bean工厂(DefaultListableBeanFactory)

public GenericApplicationContext() {
    this.beanFactory = new DefaultListableBeanFactory();
}
总结:

该步骤主要是用来准备我们需要使用的Bean工厂

3,准备BeanFactory——prepareBeanFactory(beanFactory)

源码如下:

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 设置类加载器
    beanFactory.setBeanClassLoader(getClassLoader());
    if (!shouldIgnoreSpel) {
        // 设置spel表达式解析器
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    }
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
	// 添加Bean后置处理器【ApplicationContextAwareProcessor】
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    // 设置忽略自动装配的接口EnvironmentAware等
    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.ignoreDependencyInterface(ApplicationStartupAware.class);

    // 注册可以解析的自动装配,我们能直接在任何组件中自动注入
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    // 添加BeanPostProcessor 【ApplicationListenerDetector】
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // 添加编译时的AspectJ
    if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

    // 注册默认组件Environment,systemProperties等
    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());
    }
    if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
        beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
    }
}

4,后置处理工作——postProcessBeanFactory(beanFactory)

模版方法,子类通过重写这个方法在BeanFactory创建并预准备完成之后做一些设置。(模版方法模式

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

5,调用BeanFactoryPostProcessor——invokeBeanFactoryPostProcessors()

该方法主要目的是在BeanFactory标准初始化执行之后执行。前面我们知道:

  1. 实现BeanDefinitionRegistryPostProcessor接口需要实现 postProcessBeanDefinitionRegistry()postProcessBeanFactory() 两个方法
  2. 实现BeanFactoryPostProcessor接口需要实现 postProcessBeanFactory() 方法

该方法的目的就是,帮助我们调用实现了这两个接口的类实现的方法

来看该方法的内部:

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    // 位置1
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    // AOP 相关
    if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
}

可以看到,这里由 PostProcessorRegistrationDelegate 的invokeBeanFactoryPostProcessors() 方法执行调用逻辑,继续进来:

public static void invokeBeanFactoryPostProcessors(
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {


    Set<String> processedBeans = new HashSet<>();

    if (beanFactory instanceof BeanDefinitionRegistry) {
        ...
        // 创建集合存储
        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

        // 位置1
        // 1,首先创建实现了优先级接口的PriorityOrdered的BeanDefinitionRegistryPostProcessors实现类
        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);
            }
        }
        // 2,排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        // 调用
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
        currentRegistryProcessors.clear();
        ...
        ...
}

只贴出了一部分方法代码,我们来着重看一下位置1的这一部分代码:

  1. 首先,使用 getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false) 从beanFactory中获取 BeanDefinitionRegistryPostProcessor 的实现类

    1. 我们知道在整个IOC初始化调用this()【步骤一】时,注册了五个组件,其中一个 ConfigurationClassPostProcessor 就是 BeanDefinitionRegistryPostProcessor 的实现类

      public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
            PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware { ... }
      

      ConfigurationClassPostProcessor 实现了 优先级接口 PriorityOrdered ,且配置优先级为最低

      @Override
      public int getOrder() {
         return Ordered.LOWEST_PRECEDENCE;  // Integer.MAX_VALUE
      }
      
    2. 又因为此时容器中只有5个系统级组件我们的配置类,因此这里获取实现类时会获取到容器中的 ConfigurationClassPostProcessor 。当然,如果你传入的配置类也是 BeanDefinitionRegistryPostProcessor 的子类且实现了优先级接口,那么从这里也能获取到

  2. 由 sortPostProcessors() 方法针对获取到的实现类优先级进行排序(getOrder()的返回值)

  3. invokeBeanDefinitionRegistryPostProcessors() 调用获取到的Processors【实现类】:

private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
	// 循环调用所有的postProcessor
    for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
        StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
            .tag("postProcessor", postProcessor::toString);
        // 位置1:调用方法
        postProcessor.postProcessBeanDefinitionRegistry(registry);
        postProcessBeanDefRegistry.end();
    }
}

可以看到这里传入的是我们获取的所有processor,然后循环调用所有 BeanDefinitionRegistryPostProcessor 实现类的 postProcessBeanDefinitionRegistry(registry) 方法

以上流程就是在 invokeBeanFactoryPostProcessors() 中首先调用所有实现了 BeanDefinitionRegistryPostProcessor 接口的实现类的 postProcessBeanDefinitionRegistry() 方法的大致流程。接下来我们来着重看一下Spring提供的一个Processor:ConfigurationClassPostProcessor 在此时是如何工作的:

5.1 ConfigurationClassPostProcessor 的前期处理

在上面的循环调用 processor 中,ConfigurationClassPostProcessor 会调用自己的处理逻辑如下:

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
    int registryId = System.identityHashCode(registry);
    if (this.registriesPostProcessed.contains(registryId)) {
        throw new IllegalStateException("...");
    }
    if (this.factoriesPostProcessed.contains(registryId)) {
        throw new IllegalStateException("...");
    }
    this.registriesPostProcessed.add(registryId);
	// 位置1
    processConfigBeanDefinitions(registry);
}

位置1:处理配置的bean定义,代码很长只保留如下部分:

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
    ...
    // 获取解析器解析配置类
    ConfigurationClassParser parser = new ConfigurationClassParser(
        this.metadataReaderFactory, this.problemReporter, this.environment,
        this.resourceLoader, this.componentScanBeanNameGenerator, registry);

    Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
    Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
    do {
        StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
        // 解析 位置1
        parser.parse(candidates);
        parser.validate();

        Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
        configClasses.removeAll(alreadyParsed);

        // Read the model and create bean definitions based on its content
        if (this.reader == null) {
            this.reader = new ConfigurationClassBeanDefinitionReader(
                registry, this.sourceExtractor, this.resourceLoader, this.environment,
                this.importBeanNameGenerator, parser.getImportRegistry());
        }
        // 位置2
        this.reader.loadBeanDefinitions(configClasses);
        alreadyParsed.addAll(configClasses);
        processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();

        candidates.clear();
        if (registry.getBeanDefinitionCount() > candidateNames.length) {
            String[] newCandidateNames = registry.getBeanDefinitionNames();
            Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
            Set<String> alreadyParsedClasses = new HashSet<>();
            for (ConfigurationClass configurationClass : alreadyParsed) {
                alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
            }
            for (String candidateName : newCandidateNames) {
                if (!oldCandidateNames.contains(candidateName)) {
                    BeanDefinition bd = registry.getBeanDefinition(candidateName);
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                        !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                        candidates.add(new BeanDefinitionHolder(bd, candidateName));
                    }
                }
            }
            candidateNames = newCandidateNames;
        }
    }
    while (!candidates.isEmpty());

    ...
}
  1. 首先看位置1:在位置1之前,创建了一个配置解析器 ConfigurationClassParser 之后调用该解析器的 parse(candidates) 方法,入参为符合条件的配置类(配置类可能有一个或多个)。
  2. 根据调用链最终可以找到 ConfigurationClassParser 中的 doProcessConfigurationClass() 方法解析配置文件,接下来我们看一下具体的解析流程:
5.1.1 解析配置类——ConfigurationClassParser.doProcessConfigurationClass()
  1. 首先来看该方法的第一部分——扫描内部类

    if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
        processMemberClasses(configClass, sourceClass, filter);
    }
    

    在该方法中,首先获取该方法的内部类,然后解析。假如有多层内部类,那么就会通过递归调用的方式层层解析。也就是说,假如我们在配置类中书写了内部类且加上了@ComponmentScan等注解,在该方法中会被首先扫描解析,就像下面这样:

    @Configuration
    public class TestConfig10 implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {
    	// 该内部类会被优先扫描
        @ComponentScan("com.zsp.demo")
        class TestSubClass { ... }
    }
    
  2. 接着看方法的第二部分——扫描@PropertySource

    for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
        sourceClass.getMetadata(), PropertySources.class,
        org.springframework.context.annotation.PropertySource.class)) {
        if (this.environment instanceof ConfigurableEnvironment) {
            // 扫描配置类
            processPropertySource(propertySource);
        }
        else {
            logger.info("...");
        }
    }
    

    这一步的操作主要使用 processPropertySource() 方法来解析我们 @PropertySource ,并最终将加载的配置文件信息解析到环境变量 environment 的 properySource 中

  3. 接着看第三部分——扫描@ComponentScan

    Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
    	...
    	Set<BeanDefinitionHolder> scannedBeanDefinitions =
    						this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
    	...
    }
    

    主要看其内部的这个 ComponentScanAnnotationParser 的 parse() 方法

    在这个方法中:

    1. 首先创建扫描器 ClassPathBeanDefinitionScanner
    2. 根据@Component的属性 includeFilters 等,过滤要扫描的包
    3. 依次扫描符合条件的包,并将扫描到的添加有 @Controller、@Service 等标签的组件注册Bean定义
  4. 接着看第四部分——扫描@Import

    // 扫描 @Import 注解
    processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
    

    该步骤的目的主要是扫描@import中配置的类

    需要注意的是从@Import,@Bean扫描到的需要注册的Bean并不会在这个方法里直接注册,而是后续在 ConfigurationClassPostProcessor 的 processConfigBeanDefinitions() 中注册

    如果说我们的@Import中传入的不是要注册的组件,而是 ImportBeanDefinitionRegistrar的实现类,那么在后面的处理方式也有不同

  5. 第五部分——扫描@ImportSource:该步骤的目的主要是将@ImportSource配置的xml或其他配置文件解析

  6. 第六部分——解析@Bean

  7. 第七:处理接口的默认实现,如果有子类实现了配置接口,则扫描

    processInterfaces(configClass, sourceClass);
    
  8. 最后:扫描子类,即如果该配置类存在子类,则扫描

5.2.2 注册剩下的Bean定义

从5.1.1的介绍中我们知道:@Bean和@Import的扫描到需要注册的组件并没有在前面直接注册,而是在 5.1 贴出代码块的位置2执行加载操作:

5.1代码位置2处代码如下:

this.reader.loadBeanDefinitions(configClasses);

private void loadBeanDefinitionsForConfigurationClass(
			ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
    ...
    for (BeanMethod beanMethod : configClass.getBeanMethods()) {
        loadBeanDefinitionsForBeanMethod(beanMethod);
    }
    loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
    loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}

该方法主要流程如下:

  1. 加载@Bean扫描到的Bean定义,并根据@Bean中的属性定义,初始化BeanDefinition
  2. 加载@Import扫描到的Bean定义
  3. 加载@Import中配置 ImportBeanDefinitionRegistrar 实现类中配置的 BeanDefinition
5.1 总结

经过上面的这些处理,我们配置的那些需要注册的组件的Bean定义就已经被加载到容器中

5.2 方法步骤(重点):
  1. 首先获取所有的BeanDefinitionRegistryPostProcessor
  2. 先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor的**postProcessBeanDefinitionRegistry() **方法,其中就有 ConfigurationClassPostProcessor 对Bean定义进行加载(重点)
  3. 接着执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor的**postProcessBeanDefinitionRegistry() **方法
  4. 最后执行没有实现任何优先级或排序接口的BeanDefinitionRegistryPostProcessor的**postProcessBeanDefinitionRegistry() **方法
  5. 最后调用他们没有执行的 postProcessBeanFactory() 方法
  6. 接着获取所有的 BeanFactoryPostProcessor
  7. 先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor的**postProcessBeanFactory() **方法
  8. 接着执行实现了Ordered顺序接口的BeanFactoryPostProcessor的**postProcessBeanFactory() **方法
  9. 最后执行没有实现任何优先级或排序接口的BeanFactoryPostProcessor的**postProcessBeanFactory() **方法
5.3 最后一步

从5.2我们知道,方法的最后一步是【执行没有实现任何优先级或排序接口的BeanFactoryPostProcessor的postProcessBeanFactory() 方法】,我们通过观察可以知道:EventListenerMethodProcessor 是一个未实现任何优先级接口的 BeanFactoryPostProcessor 实现类(EventListenerMethodProcessor 在this()中已经注册)。因此,在该环节,将会由 EventListenerMethodProcessor 先设置一个默认的监听工厂 DefaultListableBeanFactory 用来后续处理

总结一下:其实就是优先调用 BeanDefinitionRegistryPostProcessor 接口的实现方法后调用 BeanFactoryPostProcessor的实现方法。

6,注册Bean的后置处理器——registerBeanPostProcessors(beanFactory)

方法源码:

public static void registerBeanPostProcessors(
    ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

    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<>();
    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<>(orderedPostProcessorNames.size());
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String ppName : nonOrderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // Finally, re-register all internal BeanPostProcessors.
    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));
}

方法步骤:

  1. 首先获取所有的BeanPostProcessor(后置处理器默认可以通过PriorityOrdered、ordered接口来设定执行优先级)
  2. 先注册实现了PriorityOrdered优先级接口的BeanPostProcessor
  3. 再注册Ordered接口的
  4. 最后注册没有实现任何优先级接口的
  5. 最终注册MergedBeanDefinitionPostProcessor
  6. 最后注册一个ApplicationListenerDetector的后置处理器

总结:其实就是将我们容器中的BeanPostProcessor给添加到BeanFactory中(List< BeanPostProcess >);

private final List<BeanPostProcessor> beanPostProcessors = new BeanPostProcessorCacheAwareList();

7,初始化MessageSource组件——initMessageSource()

源码如下:

protected void initMessageSource() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
        this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
        // Make MessageSource aware of parent MessageSource.
        if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
            HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
            if (hms.getParentMessageSource() == null) {
                // Only set parent context as parent MessageSource if no parent MessageSource
                // registered already.
                hms.setParentMessageSource(getInternalParentMessageSource());
            }
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Using MessageSource [" + this.messageSource + "]");
        }
    }
    else {
        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 + "]");
        }
    }
}

方法步骤:

  1. 获取BeanFactory

  2. 看容器中是否有id为messageSource,类型是MessageSource的组件

    1. 如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource

    2. MessageSource:主要用来做国际化功能(消息绑定,解析等),可以取出国际化配置文件中某个key的值,能按照区域信息获取

      String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;
      
  3. 把创建好的MessageSource注册到容器中

8,初始化事件派发器——initApplicationEventMulticaster()

该方法的作用是初始化事件派发器。ApplicationEventMulticaster:事件派发器,可以管理大量的ApplicationListener对象并向其发布事件。

源码如下:

protected void initApplicationEventMulticaster() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    // 获取BeanFactory中的事件派发器
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isTraceEnabled()) {
            logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    // 如果没有初始化事件派发器,则创建一个SimpleApplicationEventMulticaster
    else {
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
                         "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
        }
    }
}

方法步骤:

  1. 获取BeanFactory
  2. 从BeanFactory中获取事件派发器
  3. 如果没获取到就创建一个SimpleApplicationEventMulticaster

9,模版方法——onRefresh()

protected void onRefresh() throws BeansException {
   // For subclasses: do nothing by default.
}

10,注册监听器——registerListeners()

源码如下:

protected void registerListeners() {
    // Register statically specified listeners first.
    for (ApplicationListener<?> listener : getApplicationListeners()) {
        getApplicationEventMulticaster().addApplicationListener(listener);
    }
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    for (String listenerBeanName : listenerBeanNames) {
        getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }
    // 发布早期事件
    Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
        for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
            getApplicationEventMulticaster().multicastEvent(earlyEvent);
        }
    }
}

方法步骤:

  1. 获取所有的 ApplicationListener
  2. 将每个监听器添加到事件派发器中
  3. 派发之前步骤产生的事件

11,初始化所有剩余的单实例Bean——finishBeanFactoryInitialization(beanFactory)

该方法是完成IOC容器初始化之前的最后一步,主要目的是初始化所有剩余的单例bean。方法源码如下所示:

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));
    }
    // 如果没有值解析器就先创建一个并添加 注意这里在后面@Value注入时用到
    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }
    // AOP相关
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    beanFactory.setTempClassLoader(null);

    beanFactory.freezeConfiguration();

    // 初始化所有剩余的单例Bean 位置1
    beanFactory.preInstantiateSingletons();
}

从方法名和前面的流程介绍中我们可以知道:在初始化剩余单例bean之前,一些Spring的组件(派发器、处理器等)和我们定义的一些组件(自定义处理器、配置类)会先被注入到容器中

代码最后一行(位置1)的方法就是来初始化剩余的单例Bean(非懒加载的):

// DefaultListableBeanFactory 中
@Override
public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
        logger.trace("Pre-instantiating singletons in " + this);
    }
    // 获取所有的bean定义
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    // 触发所有非懒加载单例Bean的初始化
    for (String beanName : beanNames) {
        // 根据bean名称获取详细的Bean定义信息
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 如果Bean是单例的,且非懒加载,非抽象
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            // 判断是否是FactoryBean,即bean如果实现了FactoryBean接口,就会调用getObject()创建对象
            if (isFactoryBean(beanName)) {
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                    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 {
                // 如果不是就在这里初始化 位置1
                getBean(beanName);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
                .tag("beanName", beanName);
            SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                    smartSingleton.afterSingletonsInstantiated();
                    return null;
                }, getAccessControlContext());
            }
            else {
                smartSingleton.afterSingletonsInstantiated();
            }
            smartInitialize.end();
        }
    }
}

上面方法步骤如下:

  1. 首先获取所有的bean定义名称,然后遍历

  2. 然后根据名称获取具体的bean定义信息

  3. 如果bean是单例且非懒加载,非抽象就尝试获取bean

  4. 获取bean时,如果bean是FactoryBean的实现类,那么就使用 FactoryBean 的getObject() 方法获取并初始化bean

  5. 否则使用 Abstract BeanFactory.getBean(beanName) 获取(位置1),接下来我们一起看一下这个方法:

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

    该方法调用 doGetBean() 方法获取Bean。

11.1 获取Bean——doGetBean()

下面来看该方法的源码:

@SuppressWarnings("unchecked")
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
	// 1,转化beanName,可以通过&前缀获取FactoryBean实例
    String beanName = transformedBeanName(name);
    Object beanInstance;
    // 2,尝试获取单例 位置1
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isTraceEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.trace(" ... ");
            } else { logger.trace("..."); }
        }
        beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
        // 如果bean已经被创建则报错
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // ...
            // 检查父工厂中是否已经注册,存在就返回
            // ...
        }
		// 将bean标记为准备创建状态
        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        }
		// 记录步骤信息
        StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate").tag("beanName", name);
        try {
            if (requiredType != null) {
                beanCreation.tag("beanType", requiredType::toString);
            }
            // 获取Bean定义
            RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);

            // 如果有依赖的组件,则先去实例化依赖的组件
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(...);
                    }
                    registerDependentBean(dep, beanName);
                    try {
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(...);
                    }
                }
            }
			// 创建bean实例 
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        // 销毁单例
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            } else if (mbd.isPrototype()) { // 如果是多例的,创建一个新的实例
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    afterPrototypeCreation(beanName);
                }
                beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            } else {
                String scopeName = mbd.getScope();
                if (!StringUtils.hasLength(scopeName)) {
                    throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
                }
                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);
                        }
                    });
                    beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                    throw new ScopeNotActiveException(beanName, scopeName, ex);
                }
            }
        }
        catch (BeansException ex) {
            beanCreation.tag("exception", ex.getClass().toString());
            beanCreation.tag("message", String.valueOf(ex.getMessage()));
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
        finally {
            beanCreation.end();
        }
    }
    return adaptBeanInstance(name, beanInstance, requiredType);
}

该方法有以下几个步骤:

  1. 首先根据传入的beanName,尝试 getSingleton(beanName) 从缓存中获取(11.1.1步)

  2. 如果没有获取到则将bean标记为创建状态

  3. 判断要实例化的bean有没有依赖其他的Bean(@DependsOn标注),如果有则先加载依赖的bean,需要注意的是,如果这里出现了A依赖B而B又依赖A,那么将会报错,例子如下:

    // 互相依赖
    @Repository
    @DependsOn("testService")
    public class TestDao {}
    @Service
    @DependsOn("testDao")
    public class TestService {}
    
  4. 创建Bean实例(11.1.2步)

  5. 如果是多例的,则新建一个bean实例

11.1.1 尝试获取单例——getSingleton(beanName)

该方法用于尝试获取完成实例化的bean,代码如下:

@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
   // 检查一级缓存中是否存在该bean
   Object singletonObject = this.singletonObjects.get(beanName);
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      singletonObject = this.earlySingletonObjects.get(beanName);
      if (singletonObject == null && allowEarlyReference) {
         synchronized (this.singletonObjects) {
            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;
}

singletonObjects、earlySingletonObjects、singletonFactories 分别为Spring的三级缓存。

在该方法中,首先从一级缓存中获取;如果获取不到,则从二级缓存中获取,如果二级缓存中也获取不到,那么将会尝试从三级缓存 singletonFactories 中获取

11.1.2 创建bean实例——createBean()

部分代码省略:

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
      throws BeanCreationException {
    ...
    // 位置1
    Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
    if (bean != null) { // 有返回值则返回
        return bean;
    }
	...
    // 创建bean 位置2
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
	...
}

位置1:提前执行 InstantiationAwareBeanPostProcessor 实现类的处理方法,主要用于阻断Bean实例化进程,自定义我们需要的bean。

位置2:AbstractAutowireCapableBeanFactory.doCreateBean(beanName, mbdToUse, args) 创建Bean

我们来一起看一下这个方法:

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {

    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 位置1:创建Bean实例
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // 位置2:处理MergedBeanDefinitionPostProcessor
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException("...");
            }
            mbd.postProcessed = true;
        }
    }

    // 位置3 将早期bean引用添加到三级缓存
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                                      isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) { logger.trace("..."); }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    Object exposedObject = bean;
    try {
        // 位置4 属性赋值
        populateBean(beanName, mbd, instanceWrapper);
        // 位置5 实例化bean
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
        ...
    }
    // 最后检查有没有实例化完成
    if (earlySingletonExposure) {
        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<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException("...");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
}
位置1——createBeanInstance()

方法流程:

  1. 如果Bean定义中配置了 InstanceSupplier 信息,则使用 instanceSupplier 中配置的方法进行实例化,比如:

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Color.class);
        // 配置instanceSupplier
        rootBeanDefinition.setIinstanceSupplier(Color::new);
        registry.registerBeanDefinition("color", new RootBeanDefinition(Color.class));
    }
    
  2. 如果有工厂bean的相关配置,则使用工厂方法创建对象(例如实现了FactoryBean接口)

  3. 如果以上两种方式皆否,则寻找最优的构造函数进行初始化

  4. 如果没有找到最优的构造函数,则使用默认的构造函数创建bean实例

位置2——applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)

方法流程:

  1. 首先处理 CommonAnnotationBeanPostProcessor,主要用来扫描bean上是否存在 @PreDestroy、@Resource、@PostConstruct这些JSR250规范中定义的注解
  2. 处理 AutowiredAnnotationBeanPostProcessor,主要用来扫描bean上的@Autowired、@Value注入相关的注解
  3. 处理 ApplicationListenerDetetor,用来扫描我们注册到容器中的监听器
位置3——addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean))

主要目的:将bean的早期引用添加到三级缓存中(用来解决循环依赖问题)

protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
   Assert.notNull(singletonFactory, "Singleton factory must not be null");
   synchronized (this.singletonObjects) {
      if (!this.singletonObjects.containsKey(beanName)) {
         this.singletonFactories.put(beanName, singletonFactory);// 添加到三级缓存
         this.earlySingletonObjects.remove(beanName);
         this.registeredSingletons.add(beanName);
      }
   }
}
位置4——populateBean(beanName, mbd, instanceWrapper)
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    if (bw == null) { 
        ...
    }
    // 位置1:在设置之前给 InstantiationAwareBeanPostProcessor 最后一次机会进行后置处理
    // 主要是用来修改bean的属性值,如果返回false,那么方法将会返回,不进行后续操作
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
            if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                return;
            }
        }
    }
	// 如果存在属性定义就获取,不存在就返回空(前面可能设置了属性)
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
	// 位置2:获取自动装配的类型:如按类型、按名称装配等,默认为0
    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    // 如果是按名称或类型自动装配则进行以下操作
    if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);// 按名称注入
        }
        if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);// 按类型注入
        }
        pvs = newPvs;
    }
	// 是否存在 InstantiationAwareBeanPostProcessor
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    // 返回是否进行依赖项检查(默认false)
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
	
    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        // 遍历容器中所有 InstantiationAwareBeanPostProcessor
        //  1,ConfigurationClassPostProcessor
        //  2,CommonAnnotationBeanPostProcessor(处理@Resource)
        //  3,AutowiredAnnotationBeanPostProcessor(处理@Autowired,@Value)
        for ( bp : getBeanPostProcessorCache().instantiationAware) {
            PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
                if (filteredPds == null) {
                    filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                }
                pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    return;
                }
            }
            pvs = pvsToUse;
        }
    }
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        // 进行依赖检查
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        // 应用给定的属性值
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

步骤总结:

  1. 首先给 InstantiationAwareBeanPostProcessor 最后一次机会进行后置处理,主要是用来修改bean的属性值,如果返回false,那么方法将会返回,不进行后续操作(位置1)。

  2. 然后判断自动注入的类型,选择按照类型,名称还是其他的注入方式(默认为0)。

  3. 获取容器中所有的 InstantiationAwareBeanPostProcessor 执行他们实现的 postProcessProperties方法:

    1. ConfigurationClassPostProcessor

      用来增强bean工厂

    2. CommonAnnotationBeanPostProcessor(处理@Resource)

      处理JSR250相关的注入 @Resource

    3. AutowiredAnnotationBeanPostProcessor(处理@Autowired,@Value)

      主要用来处理 @Autowired 和 @Value 的注入

      1. 获取注入元数据 InjectionMetadata

      2. InjectionMetadata.inject() 注入

      3. 遍历所有需要注入的属性,挨个注入

      4. 如果是@Value

        AbstractBeanFactory.resoloveEmbeddedValue(value) 获取

        从 this.embeddedValueResolver 中获取解析器解析并返回值

      5. 如果是@Autowired

        最终会走到 DependencyDescriptor.resolveCandidate() 获取依赖的bean

        本质上是调用 getBean 方法,不存在就先初始化依赖的bean

位置5——initializeBean(beanName, exposedObject, mbd)
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    } else {
        // 位置1:如果是 BeanNameAware、BeanClassLoaderAware、
        // BeanFactoryAware 那么调用该实现类的实现方法
        invokeAwareMethods(beanName, bean);
    }
	// 获取所有的 BeanPostProcessor 的before方法并调用,需要注意的是这里如果
    // 有一个 BeanPostProcessor 返回null,那么剩下不执行,跳出循环
    // 这里如果bean配置了 @PostConstruct注解,将会被 
    // CommonAnnotationBeanPostProcessor调用
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }
	
    try {
        // 1,如果bean实现了 InitializingBean 初始化接口,将会先调用该方法
        // 2,如果 @Bean 配置了init-method,那么将会调用该方法
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
    }
    // 获取所有的 BeanPostProcessor 的 after 方法并调用,需要注意的是这里如果
    // 有一个 BeanPostProcessor 返回null,那么剩下不执行,跳出循环
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
}

最终完成了Bean的创建之后,回到11.1的getSingleton(beanName, () -> {…})位置,使用addSingleton()方法将实例化好的单例添加到一级缓存中(同时从三级缓存中删除)。

12,初始化的最后一步——finishRefresh()

protected void finishRefresh() {
    clearResourceCaches();
    // 初始化和生命周期相关的处理器,如果没有则初始化一个DefaultLifecycleProcessor
    // LifecycleProcessor 定义了容器启动,关闭,刷新,停止的方法
    initLifecycleProcessor();
	// 调用 LifecycleProcessor 的刷新容器方法
    getLifecycleProcessor().onRefresh();
	// 发布容器刷新完成事件
    publishEvent(new ContextRefreshedEvent(this));
   if (!NativeDetector.inNativeImage()) {
        LiveBeansView.registerApplicationContext(this);
    }
}

方法步骤:

  1. 初始化和生命周期相关的处理器,如果没有则初始化一个DefaultLifecycleProcessor

    LifecycleProcessor 定义了容器启动,关闭,刷新,停止的方法,我们可以通过向容器中注册一个id为 lifecycleProcessor 的 LifecycleProcessor 处理器来实现自定义

    public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
    
  2. 调用处理器 LifecycleProcessor 的刷新容器方法,如果我们自定义了生命周期处理器,那么在这里将会被调用刷新方法 onRefresh()

  3. 发布容器刷新完成事件

    ApplicationContext 继承了 ApplicationEventPublisher ,也是一个事件发布器

总结:

1,该过程用到的设计模式

  1. 观察者模式:如Spring的事件发布处理模型(这也是我们在开发中常用的,如MQ)

    派发器(ApplicationEventMulticaster)派发事件,事件派发到具体的监听器Listener(相当于Observer),Listener做出处理

  2. 单例模式:单例Bean实现都是通过单例模式

  3. 代理模式:AOP的实现用到了代理模式

  4. 模版方法模式:如Spring在初始化过程中为我们或出示例提供的一些模版方法

  5. 工厂方法模式:例如我们配置了一个FactoryBean的子类,使用工厂方法getObject()的方式获取对象。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值