spring容器(一): 容器创建起点

1. 起点

public class AopDemo {

    static public void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);

        context.getBean(MathCalculator.class).div(4, 2);
    }
}

2. 新建,初始化容器

AnnotationConfigApplicationContext 层级
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
        this();
        register(annotatedClasses);
        refresh();
}
  1. this(): 创建容器,并初始化beanMap
  • 创建BeanFactory
    AnnotationConfigApplicationContext 继承 GenericApplicationContext,在调用AnnotationConfigApplicationContext的构造函数时,会先调用父类的构造函数创建BeanFactory:
    public GenericApplicationContext() {
        this.beanFactory = new DefaultListableBeanFactory();
    }
  • 初始化beanMap
    添加内部管理beans
org.springframework.context.annotation.internalConfigurationAnnotationProcessor,
org.springframework.context.annotation.internalAutowiredAnnotationProcessor,
org.springframework.context.annotation.internalRequiredAnnotationProcessor,
org.springframework.context.annotation.internalCommonAnnotationProcessor,
org.springframework.context.annotation.internalPersistenceAnnotationProcessor,
org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor,
org.springframework.context.event.internalEventListenerProcessor,
org.springframework.context.event.internalEventListenerFactory
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));
}
  1. 初始化自定义类:就是例子中的MainConfig
  • register(annotatedClasses);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
  1. refresh 刷新容器:实例化bean,创建Bean代理都是在这一步
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • “早起的鸟儿有虫吃,今日大家依旧起了个大早,我们将前往洛阳,车程略长,因此请大家再次当只早鸟。”河洛哥在车上对自媒...
    輕醒阅读 336评论 0 2
  • 社交场上的情侣 对对貌合神离 悲观主义者更容易践行人性的恶 过了十九岁 单纯是傻 乖是怂 坏女孩是好女孩的梦想 背...
    孟管彤阅读 534评论 3 15
  • 我们小一班的孩子们特别喜欢兔姐姐教的韵律舞蹈,上两节课学习了《动物的声音》,这两节课学习《学古诗》,让我们一起回顾...
    南和038胡媛媛阅读 659评论 0 3
  • 记忆中岁月如吉他的弦,不经意间挑起会填满我的心 蓝天中云朵一如既往洒脱,风拂过云端就有阳光挥洒 我的那些张狂的梦想...
    阿一89阅读 324评论 0 1

友情链接更多精彩内容