欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > Spring 启动流程分析

Spring 启动流程分析

2024/11/29 18:43:55 来源:https://blog.csdn.net/weixin_46058921/article/details/143275045  浏览:    关键词:Spring 启动流程分析

Spring 的设计

  • Bean: Spring作为一个IoC容器,最重要的当然是Bean咯

  • BeanFactory: 生产与管理Bean的工厂

  • BeanDefinition: Bean的定义,也就是我们方案中的Class,Spring对它进行了封装

  • BeanDefinitionRegistry: 类似于Bean与BeanFactory的关系,BeanDefinitionRegistry用于管理BeanDefinition

  • BeanDefinitionRegistryPostProcessor: 用于在解析配置类时的处理器,类似于我们方案中的ClassProcessor

  • BeanFactoryPostProcessor: BeanDefinitionRegistryPostProcessor父类,让我们可以再解析配置类之后进行后置处理

  • BeanPostProcessor: Bean的后置处理器,用于在生产Bean的过程中进行一些处理,比如依赖注入,类似我们的AutowiredAnnotationBeanProcessor

  • ApplicationContext: 如果说以上的角色都是在工厂中生产Bean的工人,那么ApplicationContext就是我们Spring的门面,ApplicationContext与BeanFactory是一种组合的关系,所以它完全扩展了BeanFactory的功能,并在其基础上添加了更多特定于企业的功能,比如我们熟知的ApplicationListener(事件监听器)

BeanFactory

BeanFactory是Spring中的一个顶级接口,它定义了获取Bean的方式,Spring中还有另一个接口叫SingletonBeanRegistry,它定义的是操作单例Bean的方式

  • ListableBeanFactory:接口,定义了获取Bean/BeanDefinition列表相关的方法,如getBeansOfType(Class type)

  • AutowireCapableBeanFactory:接口,定义了Bean生命周期相关的方法,如创建bean, 依赖注入,初始化

  • AbstractBeanFactory:抽象类,基本上实现了所有有关Bean操作的方法,定义了Bean生命周期相关的抽象方法

  • AbstractAutowireCapableBeanFactory:抽象类,继承了AbstractBeanFactory,实现了Bean生命周期相关的内容,虽然是个抽象类,但它没有抽象方法

  • DefaultListableBeanFactory:继承与实现以上所有类和接口,是为Spring中最底层的BeanFactory, 自身实现了ListableBeanFactory接口

  • ApplicationContext:也是一个接口

SingletonBeanRegistry

  • DefaultSingletonBeanRegistry: 定义了Bean的缓存池,类似于我们的BeanMap,实现了有关单例的操作,比如getSingleton(面试常问的三级缓存就在这里)

  • FactoryBeanRegistrySupport:提供了对FactoryBean的支持,比如从FactoryBean中获取Bean

BeanDefinition

BeanDefinition其实也是个接口,这里定义了许多和类信息相关的操作方法,方便在生产Bean的时候直接使用,比如getBeanClassName

  • AnnotatedGenericBeanDefinition:解析配置类与解析Import注解带入的类时,就会使用它进行封装

  • ScannedGenericBeanDefinition:封装通过@ComponentScan扫描包所得到的类信息

  • ConfigurationClassBeanDefinition:封装通过@Bean注解所得到的类信息

  • RootBeanDefinition:ConfigurationClassBeanDefinition父类,一般在Spring内部使用,将其他的BeanDefition转化成该类

BeanDefinitionRegistry

定义了与BeanDefiniton相关的操作,如registerBeanDefinitiongetBeanDefinition,在BeanFactory中,实现类就是DefaultListableBeanFactory

BeanDefinitionRegistryPostProcessor

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {/*** Modify the application context's internal bean definition registry after its* standard initialization. All regular bean definitions will have been loaded,* but no beans will have been instantiated yet. This allows for adding further* bean definitions before the next post-processing phase kicks in.* @param registry the bean definition registry used by the application context* @throws org.springframework.beans.BeansException in case of errors*/void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;}

该接口只定义了一个功能:处理BeanDefinitonRegistry,也就是解析配置类中的ImportComponentComponentScan等注解进行相应的处理,处理完毕后将这些类注册成对应的BeanDefinition

在Spring内部中,只有一个实现:ConfigurationClassPostProcessor

深入探究

BeanDefinitionRegistryPostProcessorSpring 容器的一个扩展点,主要用于在 Spring 容器完成对 Bean 的定义信息的加载后、但在它们真正实例化之前,进行额外的操作。

BeanDefinitionRegistryPostProcessorSpring中的一个高级扩展接口,继承自 BeanFactoryPostProcessor。它提供了更为深入的方式来干预bean定义的注册过程。

  这个接口定义于 org.springframework.beans.factory.support 包内,它的特殊之处在于,除了能够像 BeanFactoryPostProcessor 那样修改已经注册的bean定义(BeanDefinition),还能向注册中心 BeanDefinitionRegistry 中动态地添加或移除bean定义。

BeanDefinitionRegistryPostProcessor 提供了一个核心方法:postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)。通过该方法,我们可以直接操作 BeanDefinitionRegistry,这是一个专门用于bean定义注册的中心接口。它允许我们直接注册新的bean定义、修改已有的bean定义或者完全移除某些bean定义。

  与 BeanFactoryPostProcessor 的关键区别在于其执行时机。BeanDefinitionRegistryPostProcessor 的方法在所有其他 BeanFactoryPostProcessor 方法之前执行,这确保了它可以在其他处理器操作前先注册或修改bean定义。

  总的来说,BeanDefinitionRegistryPostProcessor 提供了一种在Spring容器配置解析阶段动态介入的能力,允许我们在其他配置处理器介入之前,进行更为深入的bean定义的调整和优化。

  1. 加载配置: Spring从各种来源(如XML文件、Java配置、注解)加载配置信息。

  2. 解析配置: 根据加载的配置,Spring创建对应的BeanDefinition

  3. 注册BeanDefinition: 解析完成后,Spring将这些BeanDefinition对象注册到BeanDefinitionRegistry中。

  4. 执行BeanDefinitionRegistryPostProcessor: 这个后置处理器提供了一个重要的扩展点,允许在所有BeanDefinition注册完毕后,但在Bean实例化之前进行一些操作。例如:注册新的BeanDefinition、修改或删除现有的BeanDefinition

  5. 执行BeanFactoryPostProcessor: 这个后置处理器提供了另一个扩展点,它主要允许查看或修改已经注册的BeanDefinition。例如,根据某些条件更改Bean的作用域或属性值。

  6. 实例化Bean: 这是将BeanDefinition转换为实际的Bean实例的过程。

  7. 依赖注入: 在这一步,Spring 框架会按照 BeanDefinition 的描述为 bean 实例注入所需的依赖。

  8. Bean初始化: 在所有依赖都注入后,特定的初始化方法(如通过@PostConstruct指定的)将会被调用,完成Bean的最后设置。

  9. 执行BeanPostProcessor的方法: BeanPostProcessor提供了拦截的能力,允许在Bean初始化阶段结束之前和之后进行操作。

  10. Bean完全初始化: 在此阶段,Bean 完全初始化并准备好被应用程序使用。

测试

 public abstract class Fruit {protected String type;​public String getType() {return type;}​public void setType(String type) {this.type = type;}}​​@Componentpublic class Apple extends Fruit {@Overridepublic String toString() {return "Apple{" + "type='" + type + '\'' + "}";}}​​public class Orange extends Fruit {@Overridepublic String toString() {return "Orange{" + "type='" + type + '\'' + '}';}}

Orange类没有标注@Component注解,Spring的组件扫描功能默认不会为其创建bean,这个例子中会在OrangeRegisterPostProcessor 里动态创建。

 /*** OrangeRegisterPostProcessor是一个BeanDefinitionRegistryPostProcessor。* 它的主要作用是检查IOC容器中是否已经包含了名为"orange"的bean定义。* 如果没有,它会动态创建一个Orange类的bean定义并注册到容器中。*/@Componentpublic class OrangeRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor {​@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {System.out.println("postProcessBeanDefinitionRegistry in OrangeRegisterPostProcessor started.");​if (!registry.containsBeanDefinition("orange")) {BeanDefinition orangeDefinition = BeanDefinitionBuilder.genericBeanDefinition(Orange.class).getBeanDefinition();registry.registerBeanDefinition("orange", orangeDefinition);}}@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {System.out.println("postProcessBeanFactory in OrangeRegisterPostProcessor started.");}}

为所有的Fruit实例设置属性:

 /*** FruitTypeSetterPostProcessor是一个BeanFactoryPostProcessor。* 它的主要作用是为所有Fruit类型的bean(Apple和Orange)设置"type"属性。* 其中,属性的值与bean的名称相同。*/@Componentpublic class FruitTypeSetterPostProcessor implements BeanFactoryPostProcessor {​@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {System.out.println("postProcessBeanFactory in FruitTypeSetterPostProcessor started.");​String[] fruitNames = beanFactory.getBeanNamesForType(Fruit.class);for (String name : fruitNames) {BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);beanDefinition.getPropertyValues().add("type", name);}}}public class DemoApplication {​public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.night.demo");Apple apple = context.getBean(Apple.class);System.out.println(apple);Orange orange = context.getBean(Orange.class);System.out.println(orange);}}

BeanFactoryPostProcessor

@FunctionalInterface
public interface BeanFactoryPostProcessor {/*** Modify the application context's internal bean factory after its standard* initialization. All bean definitions will have been loaded, but no beans* will have been instantiated yet. This allows for overriding or adding* properties even to eager-initializing beans.* @param beanFactory the bean factory used by the application context* @throws org.springframework.beans.BeansException in case of errors*/void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;}

所谓BeanFactory的后置处理器,它定义了在解析完配置类后可以调用的处理逻辑,类似于一个插槽,如果我们想在配置类解析完后做点什么,就可以实现该接口。

在Spring内部中,同样只有ConfigurationClassPostProcessor实现了它:用于专门处理加了Configuration注解的类

BeanFactoryPostProcessor位于org.springframework.beans.factory.config包中。它与BeanPostProcessor有相似的核心逻辑,但它们之间的主要区别在于它们所操作的对象。BeanFactoryPostProcessor的主要目的是对Bean的配置元数据进行操作,这意味着它可以影响Bean的初始配置数据。

  在实例化beans之前,BeanFactoryPostProcessor有权利修改这些beans的配置。在Spring中,所有的beans在被完全实例化之前都是以BeanDefinition的形式存在的。BeanFactoryPostProcessor为我们提供了一个机会,使我们能够在bean完全实例化之前调整和修改这些BeanDefinition。对BeanDefinition的任何修改都会影响后续的bean实例化和初始化过程。

测试

 public abstract class Tint {protected String label;public String getLabel() {return label;}public void setLabel(String label) {this.label = label;}}​​@Componentpublic class Blue extends Tint {@Overridepublic String toString() {return "Blue{" + "label='" + label + '\'' + "}";}}​​@Componentpublic class Yellow extends Tint {@Overridepublic String toString() {return "Yellow{" + "label='" + label + '\'' + "}";}}
 
/*** BeanFactory后置处理器,用于设置Tint子类bean的label属性。* label属性的值会设置为"postProcessBeanFactory_" + beanName。*/@Componentpublic class TintLabelSetterFactoryPostProcessor implements BeanFactoryPostProcessor {​/*** 在所有BeanDefinition加载完成之后,但bean实例化之前,设置label属性。** @param beanFactory 可配置的bean工厂,可以操作BeanDefinition。* @throws BeansException 处理过程中的异常。*/@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {// 遍历所有bean的名字for (String beanName : beanFactory.getBeanDefinitionNames()) {BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);​// 检查bean的类名是否非空,且其父类是Tintif (beanDefinition.getBeanClassName() != null &&ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), this.getClass().getClassLoader()).getSuperclass().equals(Tint.class)) {​// 添加或更新(如果属性已存在)label属性的值beanDefinition.getPropertyValues().add("label", "postProcessBeanFactory_" + beanName);}}}}public class DemoApplication {public static void main(String[] args) {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext("com.night.demo");Blue blue = ctx.getBean(Blue.class);System.out.println(blue);}}

也可以使用BeanPostProcessor达到BeanFactoryPostProcessor相似的效果:

 /*** TintLabelSetterPostProcessor类是一个BeanPostProcessor的实现,* 它为类型为Tint的bean设置'label'属性。该属性的值将被设置为"postProcessAfterInitialization_"加上bean的名称。* 这里是一个postProcessAfterInitialization方法,它会在bean初始化后,但在返回给调用者之前执行。*/@Componentpublic class TintLabelSetterPostProcessor implements BeanPostProcessor {​/*** 对bean进行后初始化处理。如果bean是Tint类型,它的'label'属性将被设置。** @param bean 将要处理的bean对象。* @param beanName bean的名称。* @return 可能已经修改过的bean。* @throws BeansException 如果在处理过程中出现错误。*/@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {if (bean instanceof Tint) {Tint tint = (Tint) bean;tint.setLabel("postProcessAfterInitialization_" + beanName);}return bean;}}

BeanPostProcessor

Bean的后置处理器,该后置处理器贯穿了Bean的生命周期整个过程,在Bean的创建过程中,一共被调用了9次

  • AutowiredAnnotationBeanPostProcessor:用于推断构造器进行实例化,以及处理Autowired和Value注解

  • CommonAnnotationBeanPostProcessor:处理Java规范中的注解,如Resource、PostConstruct

  • ApplicationListenerDetector: 在Bean的初始化后使用,将实现了ApplicationListener接口的bean添加到事件监听器列表中

  • ApplicationContextAwareProcessor:用于回调实现了Aware接口的Bean

  • ImportAwareBeanPostProcessor: 用于回调实现了ImportAware接口的Bean

ApplicationContext

ApplicationContext作为Spring的核心,以门面模式隔离了BeanFactory,以模板方法模式定义了Spring启动流程的骨架,又以策略模式调用了各式各样的Processor

  • ConfigurableApplicationContext:接口,定义了配置与生命周期相关操作,如refresh

  • AbstractApplicationContext: 抽象类,实现了refresh方法,refresh方法作为Spring核心中的核心,可以说整个Spring皆在refresh之中,所有子类都通过refresh方法启动,在调用该方法之后,将实例化所有单例

  • AnnotationConfigApplicationContext: 在启动时使用相关的注解读取器与扫描器,往Spring容器中注册需要用的处理器,而后在refresh方法在被主流程调用即可

  • AnnotationConfigWebApplicationContext:实现loadBeanDefinitions方法,以期在refresh流程中被调用,从而加载BeanDefintion

  • ClassPathXmlApplicationContext: 同上

三种后置处理器的对比

BeanFactoryPostProcessor 与 BeanPostProcessor 的差异

BeanFactoryPostProcessorBeanPostProcessor 都是 Spring 框架中为了增强容器的处理能力而提供的扩展点。它们都可以对 Bean 进行定制化处理,但它们的关注点和应用时机不同。

BeanFactoryPostProcessor:

  • 功能: 允许我们在 Spring 容器实例化任何 bean 之前读取 bean 的定义(bean 的元数据)并进行修改。

  • 作用时机: 它会在 BeanFactory 的标准初始化之后被调用,此时,所有的 bean 定义已经被加载到容器中,但还没有实例化任何 bean。此时我们可以添加、修改或移除某些 bean 的定义。

  • 常见应用: 动态修改 bean 的属性、改变 bean 的作用域、动态注册新的 bean 等。

  • 示例接口方法:void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

BeanPostProcessor:

  • 功能: 允许我们在 Spring 容器实例化 bean 之后对 bean 进行处理,提供了一种机会在 bean 的初始化前后插入我们的自定义逻辑。

  • 作用时机: 它在 bean 的生命周期中的两个时间点被调用,即在自定义初始化方法(如 @PostConstruct, init-method)之前和之后。

  • 常见应用: 对特定的 bean 实例进行一些额外处理,如进行某种代理、修改 bean 的状态等。

  • 示例接口方法:Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; 和 Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

总结:

  • BeanFactoryPostProcessor 主要关注于整个容器的配置,允许我们修改 bean 的定义或元数据。它是容器级别的。

  • BeanPostProcessor 主要关注于 bean 的实例,允许我们在初始化前后对 bean 实例进行操作。它是 bean 级别的。

BeanFactoryPostProcessor 与 BeanDefinitionRegistryPostProcessor 的关系

BeanFactoryPostProcessorBeanDefinitionRegistryPostProcessor 都是 Spring 中提供的两个重要的扩展点,它们都允许我们在 Spring 容器启动过程中对 Bean 的定义进行定制处理。但它们的应用时机和功能上存在一些不同。

BeanFactoryPostProcessor:

  • 功能: 允许我们在 Spring 容器实例化任何 bean 之前读取 bean 的定义 (BeanDefinition) 并进行修改。

  • 作用时机: 在所有的 bean 定义都被加载、但 bean 实例还未创建的时候执行。

  • 常见应用: 修改已加载到容器中的 bean 定义的属性,例如更改某个 bean 的作用域、属性值等。

  • 主要方法: void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

BeanDefinitionRegistryPostProcessor:

  • 功能: 扩展了 BeanFactoryPostProcessor,提供了一个新的方法来修改应用程序的上下文的 bean 定义。此外,还可以动态注册新的 bean 定义。

  • 作用时机: 它也是在所有 bean 定义被加载后执行,但在 BeanFactoryPostProcessor 之前。

  • 常见应用: 动态注册新的 bean 定义、修改或移除已有的 bean 定义。

  • 主要方法: void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

总结

  • BeanFactoryPostProcessor 主要是用来修改已经定义的 bean 定义,而不是注册新的 bean

  • BeanDefinitionRegistryPostProcessorBeanFactoryPostProcessor 的扩展,并提供了额外的能力来动态地注册、修改、移除 bean 定义。

Spring 容器的启动过程中,首先执行的是 BeanDefinitionRegistryPostProcessor 的方法,之后才是 BeanFactoryPostProcessor

Spring的流程

源码解析

整个启动过程分为了两个部分,即容器的初始化与刷新

初始化流程

类继承关系
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {private final AnnotatedBeanDefinitionReader reader;private final ClassPathBeanDefinitionScanner scanner;}public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {private final DefaultListableBeanFactory beanFactory;}

构造方法
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {this();register(componentClasses);refresh();
}public AnnotationConfigApplicationContext() {StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");this.reader = new AnnotatedBeanDefinitionReader(this);createAnnotatedBeanDefReader.end();this.scanner = new ClassPathBeanDefinitionScanner(this);
}

this()

调用父类的构造方法,创建 beanFactory

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

调用 AnnotatedBeanDefinitionReader 的构造方法,添加 postProcessor

// AnnotationConfigApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry
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);// 向容器中添加 postProcessorAnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

register

把配置类包装成 beanDefinition 注册到容器中

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));// 把自己注入到 beanDefinitionthis.reader.register(componentClasses);registerComponentClass.end();
}// AnnotatedBeanDefinitionReader.register()
public void register(Class<?>... componentClasses) {for (Class<?> componentClass : componentClasses) {registerBean(componentClass);}
}

看完流程图,我们应该思考一下:如果让你去设计一个 IOC 容器,你会怎么做?首先我肯定会提供一个入口(AnnotationConfigApplicationContext )给用户使用,然后需要去初始化一系列的工具组件:

①:如果我想生成 bean 对象,那么就需要一个 beanFactory 工厂(DefaultListableBeanFactory);

②:如果我想对加了特定注解(如 @Service@Repository)的类进行读取转化成 BeanDefinition 对象(BeanDefinition 是 Spring 中极其重要的一个概念,它存储了 bean 对象的所有特征信息,如是否单例,是否懒加载,factoryBeanName 等),那么就需要一个注解配置读取器(AnnotatedBeanDefinitionReader);

③:如果我想对用户指定的包目录进行扫描查找 bean 对象,那么还需要一个路径扫描器(ClassPathBeanDefinitionScanner)。

org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors

为容器添加一些内置组件了,其中最主要的组件便是 ConfigurationClassPostProcessorAutowiredAnnotationBeanPostProcessor ,前者是一个 beanFactory 后置处理器,用来完成 bean 的扫描与注入工作,后者是一个 bean 后置处理器,用来完成 @AutoWired 自动注入

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);// ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor// BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessorif (!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));}// AutowiredAnnotationBeanPostProcessor implements MergedBeanDefinitionPostProcessor// MergedBeanDefinitionPostProcessor extends BeanPostProcessorif (!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));}// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.// CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor// InitDestroyAnnotationBeanPostProcessor implements MergedBeanDefinitionPostProcessorif (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));}// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.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));}// EventListenerMethodProcessor BeanFactoryPostProcessorif (!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;
}

org.springframework.context.annotation.AnnotatedBeanDefinitionReader#doRegisterBean

这个步骤主要是用来解析用户传入的 Spring 配置类,其实也是解析成一个 BeanDefinition 然后注册到容器中

private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,@Nullable BeanDefinitionCustomizer[] customizers) {// 解析传入的配置类,实际上这个方法既可以解析配置类,也可以解析 Spring bean 对象AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);// 判断是否需要跳过,判断依据是此类上有没有 @Conditional 注解if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {return;}abd.setInstanceSupplier(supplier);ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);abd.setScope(scopeMetadata.getScopeName());String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);if (qualifiers != null) {for (Class<? extends Annotation> qualifier : qualifiers) {if (Primary.class == qualifier) {abd.setPrimary(true);}else if (Lazy.class == qualifier) {abd.setLazyInit(true);}else {abd.addQualifier(new AutowireCandidateQualifier(qualifier));}}}if (customizers != null) {// 封装成一个 BeanDefinitionHolderfor (BeanDefinitionCustomizer customizer : customizers) {customizer.customize(abd);}}BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);// 处理 scopedProxyModedefinitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);// 把 BeanDefinitionHolder 注册到 registryBeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}

刷新流程

我们知道了如何去初始化一个 IOC 容器,那么接下来就是让这个 IOC 容器真正起作用的时候了:即先扫描出要放入容器的 bean,将其包装成 BeanDefinition 对象,然后通过反射创建 bean,并完成赋值操作,这个就是 IOC 容器最简单的功能了

如果用户想在扫描完 bean 之后做一些自定义的操作:假设容器中包含了 a 和 b,那么就动态向容器中注入 c,不满足就注入 d,这种骚操作 Spring 也是支持的,得益于它提供的 BeanFactoryPostProcessor 后置处理器,对应的是上图中的 invokeBeanFactoryPostProcessors 操作

如果用户还想在 bean 的初始化前后做一些操作呢?比如生成代理对象,修改对象属性等,Spring 为我们提供了 BeanPostProcessor 后置处理器,实际上 Spring 容器中的大多数功能都是通过 Bean 后置处理器完成的,Spring 也是给我们提供了添加入口,对应的是上图中的 registerBeanPostProcessors 操作

整个容器创建过程中,如果用户想监听容器启动、刷新等事件,根据这些事件做一些自定义的操作呢?Spring 也早已为我们考虑到了,提供了添加监听器接口和容器事件通知接口,对应的是上图中的 registerListeners 操作

org.springframework.context.support.AbstractApplicationContext#refresh

Spring 中的每一个容器都会调用 refresh 方法进行刷新,无论是 Spring 的父子容器,还是 Spring Cloud Feign 中的 feign 隔离容器,每一个容器都会调用这个方法完成初始化。

public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");// 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);StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);beanPostProcess.end();// 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();}

prepareBeanFactory

org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory

顾名思义,这个接口是为 beanFactory 工厂添加一些内置组件,预处理过程

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {// Tell the internal bean factory to use the context's class loader etc.beanFactory.setBeanClassLoader(getClassLoader());// 设置 bean 表达式解析器if (!shouldIgnoreSpel) {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.ignoreDependencyInterface(ApplicationStartupAware.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.// 添加编译时的 AspectJif (!NativeDetector.inNativeImage() && 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());}if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());}
}

invokeBeanFactoryPostProcessors

org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

Spring 在扫描完所有的 bean 转成 BeanDefinition 时候,我们是可以做一些自定义操作的,这得益于 Spring 为我们提供的 BeanFactoryPostProcessor 接口。

其中 BeanFactoryPostProcessor 又有一个子接口 BeanDefinitionRegistryPostProcessor ,前者会把 ConfigurableListableBeanFactory 暴露给我们使用,后者会把 BeanDefinitionRegistry 注册器暴露给我们使用,一旦获取到注册器,我们就可以按需注入了,例如搞定这种需求:假设容器中包含了 a 和 b,那么就动态向容器中注入 c,不满足就注入 d。

熟悉 Spring 的同学都知道,Spring 中的同类型组件是允许我们控制顺序的,比如在 AOP 中我们常用的 @Order 注解,这里的 BeanFactoryPostProcessor 接口当然也是提供了顺序,最先被执行的是实现了 PriorityOrdered 接口的实现类,然后再到实现了 Ordered 接口的实现类,最后就是剩下来的常规 BeanFactoryPostProcessor

public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {// WARNING: Although it may appear that the body of this method can be easily// refactored to avoid the use of multiple loops and multiple lists, the use// of multiple lists and multiple passes over the names of processors is// intentional. We must ensure that we honor the contracts for PriorityOrdered// and Ordered processors. Specifically, we must NOT cause processors to be// instantiated (via getBean() invocations) or registered in the ApplicationContext// in the wrong order.//// Before submitting a pull request (PR) to change this method, please review the// list of all declined PRs involving changes to PostProcessorRegistrationDelegate// to ensure that your proposal does not result in a breaking change:// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22// Invoke BeanDefinitionRegistryPostProcessors first, if any.// 代表执行过的 BeanDefinitionRegistryPostProcessorSet<String> processedBeans = new HashSet<>();if (beanFactory instanceof BeanDefinitionRegistry) {BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;// 常规后置处理器集合,即实现了 BeanFactoryPostProcessor 接口List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();// 注册后置处理器集合,即实现了 BeanDefinitionRegistryPostProcessor 接口List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();// 处理自定义的 beanFactoryPostProcessors(指调用 context.addBeanFactoryPostProcessor() 方法),一般这里都没有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.// 定义一个变量 currentRegistryProcessors,表示当前要处理的 BeanFactoryPostProcessorsList<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.// 这里只会查找出一个【ConfigurationClassPostProcessor】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,表示已经处理过这个类了processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);// 添加到 registry 中registryProcessors.addAll(currentRegistryProcessors);// 执行 [postProcessBeanDefinitionRegistry] 回调方法invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());// 将 currentRegistryProcessors 变量清空,下面会继续用到currentRegistryProcessors.clear();// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.// 因为【ConfigurationClassPostProcessor】已经完成了 postProcessBeanDefinitionRegistry() 方法,已经向容器中完成扫描工作,所以容器会有很多个组件postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {// 判断 processedBeans 是否处理过这个类,且是否实现 Ordered 接口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, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.// 最后,从容器中查找剩余所有常规的 BeanDefinitionRegistryPostProcessors 类型boolean reiterate = true;while (reiterate) {reiterate = false;postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {// 判断 processedBeans 是否处理过这个类if (!processedBeans.contains(ppName)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);// 将标识设置为 true,继续循环查找,可能随时因为防止下面调用了 invokeBeanDefinitionRegistryPostProcessors() 方法引入新的后置处理器reiterate = true;}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();}// Now, invoke the postProcessBeanFactory callback of all processors handled so far.// 现在执行 registryProcessors 的 [postProcessBeanFactory] 回调方法invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);// 执行 regularPostProcessors 的 [postProcessBeanFactory] 回调方法,也包含用户手动调用 addBeanFactoryPostProcessor() 方法添加的 BeanFactoryPostProcessorinvokeBeanFactoryPostProcessors(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) {// 判断是否已经处理过,因为 postProcessorNames 其实包含了上面步骤处理过的 BeanDefinitionRegistry 类型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.// 接下来,把 orderedPostProcessorNames 转成 orderedPostProcessors 集合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.// 最后把 nonOrderedPostProcessorNames 转成 nonOrderedPostProcessors 集合List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());for (String postProcessorName : nonOrderedPostProcessorNames) {nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));}invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);// Clear cached merged bean definitions since the post-processors might have// modified the original metadata, e.g. replacing placeholders in values...beanFactory.clearMetadataCache();
}

registerBeanPostProcessors

org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors

这一步是向容器中注入 BeanPostProcessor ,注意这里仅仅是向容器中注入而非使用。

public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {// WARNING: Although it may appear that the body of this method can be easily// refactored to avoid the use of multiple loops and multiple lists, the use// of multiple lists and multiple passes over the names of processors is// intentional. We must ensure that we honor the contracts for PriorityOrdered// and Ordered processors. Specifically, we must NOT cause processors to be// instantiated (via getBean() invocations) or registered in the ApplicationContext// in the wrong order.//// Before submitting a pull request (PR) to change this method, please review the// list of all declined PRs involving changes to PostProcessorRegistrationDelegate// to ensure that your proposal does not result in a breaking change:// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22String[] 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<>(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).// 给容器中添加【ApplicationListenerDetector】 beanPostProcessor,判断是不是监听器,如果是就把 bean 放到容器中保存起来// 此时容器中默认会有 6 个内置的 beanPostProcessor// 0 = {ApplicationContextAwareProcessor@1632}// 1 = {ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor@1633}// 2 = {PostProcessorRegistrationDelegate$BeanPostProcessorChecker@1634}// 3 = {CommonAnnotationBeanPostProcessor@1635}// 4 = {AutowiredAnnotationBeanPostProcessor@1636}// 5 = {ApplicationListenerDetector@1637}beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

initApplicationEventMulticaster

org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster

在整个容器创建过程中,Spring 会发布很多容器事件,如容器启动、刷新、关闭等,这个功能的实现得益于这里的 ApplicationEventMulticaster 广播器组件,通过它来派发事件通知。

在这里 Spring 也为我们提供了扩展,SimpleApplicationEventMulticaster 默认是同步的,如果我们想改成异步的,只需要在容器里自定义一个 name 为 applicationEventMulticaster 的容器即可,类似的思想在后续的 Spring Boot 中会有更多的体现,这里不再赘述。

protected void initApplicationEventMulticaster() {ConfigurableListableBeanFactory beanFactory = getBeanFactory();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 + "]");}}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() + "]");}}
}

org.springframework.context.support.AbstractApplicationContext#registerListeners

如果用户想监听容器事件,那么就必须按照规范实现 ApplicationListener 接口并放入到容器中,在这里会被 Spring 扫描到,添加到 ApplicationEventMulticaster 广播器里,以后就可以发布事件通知,对应的 Listener 就会收到消息进行处理。

protected void registerListeners() {// Register statically specified listeners first.for (ApplicationListener<?> listener : getApplicationListeners()) {getApplicationEventMulticaster().addApplicationListener(listener);}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let post-processors apply to them!String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);for (String listenerBeanName : listenerBeanNames) {getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);}// Publish early application events now that we finally have a multicaster...Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;this.earlyApplicationEvents = null;if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {for (ApplicationEvent earlyEvent : earlyEventsToProcess) {getApplicationEventMulticaster().multicastEvent(earlyEvent);}}
}

preInstantiateSingletons

org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons

在上面的步骤中,Spring 的大多数组件都已经初始化完毕了,剩下来的这个步骤就是初始化所有剩余的单实例 bean,在 Spring 中初始化一个 bean 对象是非常复杂的,如循环依赖、bean 后置处理器运用、aop 代理等,这些内容都不在此展开赘述了,后面的系列文章会具体探究,这里我们只需要明白 Spring 是通过这个方法把容器中的 bean 都初始化完毕即可。

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,它表示自己的 BeanDefinition 和可能存在父类的 BeanDefinition 合并后的对象RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);// 如果是非抽象的,且单实例,非懒加载if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {// 如果是 factoryBean,利用下面这种方法创建对象if (isFactoryBean(beanName)) {// 如果是 factoryBean,则 加上 &,先创建工厂 beanObject 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 {getBean(beanName);}}}// Trigger post-initialization callback for all applicable beans...for (String beanName : beanNames) {Object singletonInstance = getSingleton(beanName);// 检查所有的 bean 是否是 SmartInitializingSingleton 接口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 {// 回调 afterSingletonsInstantiated() 方法,可以在回调中做一些事情smartSingleton.afterSingletonsInstantiated();}smartInitialize.end();}}
}

org.springframework.context.support.AbstractApplicationContext#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.// 拿到前面定义的生命周期处理器【LifecycleProcessor】回调 onRefresh() 方法getLifecycleProcessor().onRefresh();// Publish the final event.// 发布容器刷新完成事件publishEvent(new ContextRefreshedEvent(this));// Participate in LiveBeansView MBean, if active.if (!NativeDetector.inNativeImage()) {LiveBeansView.registerApplicationContext(this);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com