揭开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
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 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.