boxmoe_header_banner_img

 

文章导读

Spring AnnotationConfigApplicationContext(更新)


avatar
wars 6 10 月, 2025 39

本文基于 2025-10-08 时 spring-framework 开源项目最新 main 分支编写.
25-10-07: 😄本人发现 AnnotationConfigApplicationContext 无参构造中, 有两行存在了五年的无效 Bug 代码, 已给 spring-framework 提 PR 合并进主分支了.

现代常用的 Spring Framework 核心类, 有经典的 AnnotationConfigApplicationContext, 和 Web 支持的 AnnotationConfigWebApplicationContext.

以及 Spring Boot 的嵌入式 Web 核心类: AnnotationConfigServletWebServerApplicationContext.

这三个核心类的核心实现其实大差不差, 今天开始不带目的的研究 Spring, 所以从最经典的 AnnotationConfigApplicationContext 开始.

1) 整体继承/实现链路

AnnotationConfigApplicationContext 的继承/实现链路如下:
AnnotationConfigApplication dependency tree

2) 链路分类整理

核心功能:

BeanFactory(I)
├── HierarchicalBeanFactory(I)
└── ListableBeanFactory(I)
    └── ApplicationContext(I)
        └── ConfigurableApplicationContext(I)
            └── AbstractApplicationContext(C)
                └── GenericApplicationContext(C)
                    └── AnnotationConfigApplicationContext(C)

Bean 注册:

AliasRegistry(I)
└── BeanDefinitionRegistry(I)
    └── GenericApplicationContext(C)

AnnotationConfigRegistry(I)
└── AnnotationConfigApplicationContext(C)

资源加载:

ResourceLoader(I)
├── ResourcePatternResolver(I)
|   └── ApplicationContext(I)
└── DefaultResourceLoader(C)
    └── AbstractApplicationContext(C)

消息国际化:

MessageSource(I)
└── ApplicationContext(I)

环境变量:

EnvironmentCapable(I)
└── ApplicationContext(I)

事件发布:

FunctionInterface(I)
└── ApplicationEventPublisher(I)
    └── ApplicationContext(I)

资源释放:

AutoCloseable(I)
└── Closeable(I)
    └── ConfigurableApplicationContext(I)

3) AnnotationConfigApplicationContext 构造

AnnotationConfigApplicationContext 的经典构造方法如下, 隐式 super() 调用会同时初始化 BeanFactory,ResourcePatternResolver 需要注意一下.

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
    // 1. 通用构造, 初始化 Reader、Scanner、BeanFactory、ResourcePatternResolver.
    this();
    // 2. 注册传入的 Component 类, 通常我们传 Configuration 类.
    register(componentClasses);
    // 3. 调用父类 AbstractApplicationContext.refresh(), 即 Spring 最核心的方法.
    refresh();
}

public AnnotationConfigApplicationContext() {
    // 隐式调用 super()
    // 初始化 beanFactory 为 DefaultListableBeanFactory 实现.
    // 初始化 resourcePatternResolver 为 PathMatchingResourcePatternResolver 实现.
    this.reader = new AnnotatedBeanDefinitionReader(this);
    this.scanner = new ClassPathBeanDefinitionScanner(this);
}
// 父类初始化详细流程如下
public GenericApplicationContext() {
    // 隐式调用 super()
    this.beanFactory = new DefaultListableBeanFactory();
}
public AbstractApplicationContext() {
    this.resourcePatternResolver = getResourcePatternResolver();
}
protected ResourcePatternResolver getResourcePatternResolver() {
    return new PathMatchingResourcePatternResolver(this);
}

3.1) AnnotatedBeanDefinitionReader 初始化:

  1. getOrCreateEnvironment 尝试获取传入 Context 的 environment 属性.

我们没有修改它, 最后会使用 AbstractApplicationContext#createEnvironment 创建 StandardEnvironment() 实例.

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
    this(registry, getOrCreateEnvironment(registry));
}
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
    Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
    if (registry instanceof EnvironmentCapable environmentCapable) {
        return environmentCapable.getEnvironment(); // 1. 创建 StandardEnvironment() 实例.
    }
    return new StandardEnvironment();
}
  1. this 实际默认初始化方法中的逻辑:

    1. 设置 Context 的引用.
    2. 创建 ConditionEvaluator Bean 注册条件评估器实例.
    3. 注册注解处理器为 BeanPostProcessor.
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
    Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
    Assert.notNull(environment, "Environment must not be null");
    // 1. 设置 Context 引用.
    this.registry = registry;
    // 2. 创建 ConditionEvaluator 实例.
    this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
    // 3. 注解支持初始化, 相关 BeanPostProcessor 注册为 BeanDefinition.
    AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
  1. ConditionEvaluator Bean 注册条件评估器实例创建.
public ConditionEvaluator(@Nullable BeanDefinitionRegistry registry,
        @Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
    // 实例创建.
    this.context = new ConditionContextImpl(registry, environment, resourceLoader);
}
public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,
        @Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
    // 1. Context 引用传递为 registry、beanFactory.
    this.registry = registry;
    this.beanFactory = deduceBeanFactory(registry);
    // 2. Environment 引用传递.
    this.environment = (environment != null ? environment : deduceEnvironment(registry));
    // 3. Context 引用传递为 this.resourceLoader.
    this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
    // 4. Context.getBeanClassLoader() 引用传递为 this.classLoader.
    this.classLoader = deduceClassLoader(resourceLoader, this.beanFactory);
}
// 以下为两个 instanceof 推断方法不太重要不需要看.
private static ResourceLoader deduceResourceLoader(@Nullable BeanDefinitionRegistry source) {
    if (source instanceof ResourceLoader resourceLoader) {
        return resourceLoader;
    }
    return new DefaultResourceLoader();
}
private static @Nullable ClassLoader deduceClassLoader(@Nullable ResourceLoader resourceLoader,
        @Nullable ConfigurableListableBeanFactory beanFactory) {
    if (resourceLoader != null) {
        ClassLoader classLoader = resourceLoader.getClassLoader();
        if (classLoader != null) {
            return classLoader;
        }
    }
    if (beanFactory != null) {
        return beanFactory.getBeanClassLoader();
    }
    return ClassUtils.getDefaultClassLoader();
}
  1. 依赖排序器, 注解注入检查器初始化, 注解处理 PostProcessor 注册, 包括 ConfigurationClassPostProcessor,AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,EventListenerMethodProcessor,DefaultEventListenerFactory 后续会分章节解析.
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
    registerAnnotationConfigProcessors(registry, null);
}
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
        BeanDefinitionRegistry registry, @Nullable Object source) {
    // 1. 转换 Context 为 BeanFactory 类型引用.
    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
    if (beanFactory != null) {
        if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
            // 2. Context 的默认依赖排序比较器为空, 设置为 AnnotationAwareOrderComparator.
            beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
        }
        if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
            // 3. Context 的默认注入检查器是 SimpleAutowireCandidateResolver, 不支持注解注入.
            // 替换成 ContextAnnotationAutowireCandidateResolver 带注解注入的检查器实现.
            beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
        }
    }
    // 定义已注册的 PostProcessor BeanDefinition 信息集合最后返回.
    // 但当前流程并未用到该集合, 可忽略.
    Set<BeanDefinitionHolder> beanDefs = CollectionUtils.newLinkedHashSet(6);
    // 因为默认 Context 中不包含任何 BeanDefinition.
    // 以下 !registry.containsBeanDefinition if 判断都进入.
    if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        // 4. 注册配置类后置处理器, 处理 @Configuration,@ComponentScan,@Import 等注解.
        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)) {
        // 5. 注册依赖注入后置处理器, 处理 @Autowired,@Value,@Inject 等注解.
        RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
    // 判断项目是否包含 Jakarta 注解, 现代 SpringBoot Web 项目都包含.
    // Check for Jakarta Annotations support, and if present add the CommonAnnotationBeanPostProcessor.
    if (JAKARTA_ANNOTATIONS_PRESENT && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        // 6. 注册 Jakarta 基础注解后置处理器, 处理 @Resource,@PostConstruct 等注解.
        RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    // 判断项目是否包含 JPA 注解.
    // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
    if (JPA_PRESENT && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition();
        try {
            // 7. 注册 JPA 持久化注解后置处理器, 处理 @PersistenceContext,@PersistenceUnit 等注解.
            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)) {
        // 8. 注册事件监听注解后置处理器, 处理 @EventListener 等注解.
        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)) {
        // 9. 注册事件监听器默认工厂, 处理 @EventListener 适配器.
        RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
    }

    return beanDefs;
}

3.2) ClassPathBeanDefinitionScanner 初始化:



评论(0)

查看评论列表

暂无评论


发表评论

表情 颜文字

插入代码