揭开 AnnotationConfigApplicationContext 类运行的神秘面纱
一、运行大抵流程图
二、解析
2.1 无参构造方法
-
AnnotationConfigApplicationContext 无参构造方法
public AnnotationConfigApplicationContext() { // 在执行此行代码之前, 先执行了父类的构造方法 // 此段代码做的事件: // 1. 初始化 bean 工厂 // 2. 初始化一个注解 BeanDefinition 读取器 // 3. 将 spring 内置的 6 个类封装成 RootBeanDefinition 并注册到 bean 工厂, // 具体是哪 6 个类能够查看上述的原理图 this.reader = new AnnotatedBeanDefinitionReader(this); // 并没啥用, 尽管 ClassPathBeanDefinitionScanner // 类的作用是扫描 @ComponentScan 注解提供的包门路。// 但实际上它并没有做扫描工作, spring 外部扫描门路 // 的时候, 是在外部新 new 了一个 ClassPathBeanDefinitionScanner, // 这个属性目前没啥用, 当然咱们能够获取这个对象 // 调用它的 scan 办法, 然而没有必要! 因为 // @ComponentScan 能够反对多个扫描门路。// 那这个类有什么用呢?跟刚刚的解释一样, // 咱们能够本人 new 一个 ClassPathBeanDefinitionScanner 对象或者扩大他, // 利用它的扫描性能(因为它是应用 ASM 来扫描的) // Mybatis 源码中就是本人扩大了 // ClassPathBeanDefinitionScanner 类 this.scanner = new ClassPathBeanDefinitionScanner(this); }
- AnnotationConfigApplicationContext 父类 GenericApplicationContext 无参构造方法
public GenericApplicationContext() { // 实例化 spring bean 工厂: DefaultListableBeanFactory this.beanFactory = new DefaultListableBeanFactory();}
- 注册 spring 内置的 6 个 bean 至 bean 工厂代码:org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object)
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) { // 解析传入的 registry, 获取 bean 工厂, // 依据调用链或 debug 可知, 它就是 // AnnotationConfigApplicationContext 上下文, // 因为它的父类 GenericApplicationContext 保护了一个 bean 工厂, // 并提供了 get 办法, 那么它天然也能领有 bean 工厂 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 (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); } // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor. 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)); } // 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)); } 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; }
2.2 register 办法
-
源码
/** * 传入的是一个被注解类的 Class 数组, 能够是配置类也能够是一般类 * (什么叫配置类什么叫一般类, 在后续的源码系列中会更新) * @param annotatedClasses one or more annotated classes */ public void register(Class<?>... annotatedClasses) {Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); // 此处用到了构造方法 new 进去的 AnnotatedBeanDefinitionReader, // 这里解释下, 为什么能用这个类来将传入的类注册到 bean 工厂中: 因为它内 // 部保护了一个 registry, 这个 registry 就是 AnnotationConfigApplicationContext this.reader.register(annotatedClasses); }
- 作用: 将传入的被注解的类以 AnnotatedGenericBeanDefinition 的类型注册到 bean 工厂。至此,还没有一个 bean 被创立进去。以下为注册 AnnotatedGenericBeanDefinition 的具体代码逻辑, 能够看到注册 bean 调用了这个办法:
registerBeanDefinition
(这个办法很重要. 后续注册 beanDefinition 到 bean 工厂基本上都会用到这个办法)
2.3 refresh 办法
- 这个办法能够说是 spring 的外围入口办法了, 在外部做了太多太多的事件。
-
源码(每行代码执行意义在正文中有写到, 先应用黑箱实践, 大抵理解它是干啥的, 具体先解析到 invokeBeanFactoryPostProcessors 此办法, 后续的办法还没往后读, 当前补充):
public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. // 这个办法执行实现, spring 的 bean 单例容器中会存在三个 bean, // 别离是 systemEnvironment, environment, systemProperties prepareBeanFactory(beanFactory); try { // 该办法没有做任何事, 外部无任何逻辑 postProcessBeanFactory(beanFactory); // 调用后置处理器, 此办法太重要了, 调用过程参考下图 invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh();} catch (BeansException ex) {if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization -" + "cancelling refresh attempt:" + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches();} } }
- invokeBeanFactoryPostProcessors 办法运行原理图, 该办法大抵蕴含: 调用 手动增加的 BeanFactoryPostProcessor 后置处理器 、 调用 spring 内置后置处理器 ConfigrationClassPostProcessor, 次要解析配置类、给全注解类增加 cglib 代理等等 这里先把它晒进去, 后续再具体
三、小结
- 上述为本次博客内容
- github 地址: https://github.com/AvengerEug
- I am a slow walker, but I never walk backwards.