(Spring源码分析)AnnotationConfigApplicationContext容器初始化 this() && register() £神魔★判官ぃ 2023-05-30 09:25 1阅读 0赞 **AnnotationConfigApplicationContext容器初始化目录** [(Spring源码分析)AnnotationConfigApplicationContext容器初始化 this() && register()][Spring_AnnotationConfigApplicationContext_ this_ _ register] [(Spring源码分析)AnnotationConfigApplicationContext容器初始化 refresh()\#invokeBeanFactoryPostProcessors][Spring_AnnotationConfigApplicationContext_ refresh_invokeBeanFactoryPostProcessors] [(Spring源码分析)AnnotationConfigApplicationContext容器初始化 refresh()\#registerBeanPostProcessors][Spring_AnnotationConfigApplicationContext_ refresh_registerBeanPostProcessors] [(Spring源码分析)AnnotationConfigApplicationContext容器初始化 refresh()\#finishBeanFactoryInitialization][Spring_AnnotationConfigApplicationContext_ refresh_finishBeanFactoryInitialization] ### 目录 ### * 使用AnnotationConfigApplicationContext容器 * AppConfig配置类 * * AnnotationConfigApplicationContext容器方法 * * 1、this() * 2、register(annotatedClasses) * * 2.1、this.reader.register(annotatedClasses) * 2.1.1、registerBean(annotatedClass) * 2.1.1.1、doRegisterBean(annotatedClass, null, null, null) * 2.1.1.1.1、BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry) * 2.1.1.1.1.1、registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()) # 使用AnnotationConfigApplicationContext容器 # public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); TestService testService = applicationContext.getBean(TestService.class); System.out.println(testService.sout()); } # AppConfig配置类 # @Configuration @ComponentScan("com.wyj.learning.build.applicationcontext") public class AppConfig { } ## AnnotationConfigApplicationContext容器方法 ## `AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);`这段代码会调用AnnotationConfigApplicationContext类的无参构造方法 /** * 这个构造方法需要传入一个javaconfig注解了的配置类 * 然后会把这个被注解了javaconfig的类通过注解读取器读取后继而解析 */ public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { // 这里由于他有父类,故而会先调用父类的无参构造方法,然后才会调用自己的无参构造方法 // 在自己构造方法中初始一个读取器和扫描器 this(); register(annotatedClasses); // 这里仅仅只是将annotatedClasses作为bean放入beanDefinitionMap中 refresh(); // AnnotationConfigApplicationContext容器中最重要的方法,将annotatedClasses中扫描的bean加入beanDefinitionMap中 } ### 1、this() ### > this()方法主要是初始化BeanFactory容器 在`AnnotationConfigApplicationContext`父类`GenericApplicationContext`的无参构造方法中 /** * 初始化BeanFactory */ public GenericApplicationContext() { this.beanFactory = new DefaultListableBeanFactory(); } 然后执行`AnnotationConfigApplicationContext`自己的无参构造方法 /** * 初始化注解读取器和扫描器 */ public AnnotationConfigApplicationContext() { this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); } ### 2、register(annotatedClasses) ### > register(annotatedClasses)方法主要是将传入的配置类加入到BeanDefinitionMap中,但是配置类中配置的包扫描路径下的bean并没有添加到BeanDefinitionMap中 /** * 判断annotatedClasses不为空,并调用AnnotatedBeanDefinitionReader注解读取器去读取配置类annotatedClasses中的配置 */ public void register(Class<?>... annotatedClasses) { Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); this.reader.register(annotatedClasses); // 调用AnnotatedBeanDefinitionReader注解读取器去读取配置类annotatedClasses中的配置 } #### 2.1、this.reader.register(annotatedClasses) #### /** * 循环调用AnnotatedBeanDefinitionReader注解读取器去读取配置类 */ public void register(Class<?>... annotatedClasses) { for (Class<?> annotatedClass : annotatedClasses) { registerBean(annotatedClass); } } #### 2.1.1、registerBean(annotatedClass) #### public void registerBean(Class<?> annotatedClass) { doRegisterBean(annotatedClass, null, null, null); } #### 2.1.1.1、doRegisterBean(annotatedClass, null, null, null) #### <T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) { // 这里的这个AnnotatedGenericBeanDefinition对象仅仅只是在new AnnotationConfigApplicationContext(传入的配置类) AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass); // 将Bean的配置信息转换成AnnotatedGenericBeanDefinition,它继承了BeanDefinition接口,包含bean的属性 // @Conditional装配条件判断是否需要跳过注册 if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) { return; } abd.setInstanceSupplier(instanceSupplier); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); // 解析bean作用域,如果使有@Scope注解指定了bean的作用域将设置成指定的作用域,否则默认为singleton(单例) abd.setScope(scopeMetadata.getScopeName()); // 为AnnotatedGenericBeanDefinition对象设置scope(作用域)属性 String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); // 生成beanName AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); // 解析AnnotatedGenericBeanDefinition对象中lazy、Primary、DependsOn、Role、Description属性 if (qualifiers != null) { // @Qualifier特殊限定符处理 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)); } } } // 处理applicationcontext容器加载完成后手动registerBean for (BeanDefinitionCustomizer customizer : definitionCustomizers) { customizer.customize(abd); } BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); // 将beanName和AnnotatedGenericBeanDefinition封装在BeanDefinitionHolder中 definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 创建代理对象 BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); // 将BeanDefinition注册到BeanDefinitionMap中 } #### 2.1.1.1.1、BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry) #### public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // 调用BeanDefinitionRegistry方法对BeanDefinition注册到ConCurrentHashMap中 // Register aliases for bean name, if any. String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String alias : aliases) { registry.registerAlias(beanName, alias); // 注册别名 } } } #### 2.1.1.1.1.1、registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()) #### /** * 对BeanDefinition注册到ConCurrentHashMap中 */ @Override public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { // 校验beanName和beanDefinition不能为空 Assert.hasText(beanName, "Bean name must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); // beanDefinition校验 if (beanDefinition instanceof AbstractBeanDefinition) { try { ((AbstractBeanDefinition) beanDefinition).validate(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", ex); } } BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); // 判断beanDefinitionMap中是否含有相同beanName的BeanDefinition // 如果beanDefinitionMap中存在相同beanName的BeanDefinition if (existingDefinition != null) { // 判断是否允许含有同样的beanName对BeanDefinition进行覆盖 if (!isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName + "': There is already [" + existingDefinition + "] bound."); } // 参数校验 else if (existingDefinition.getRole() < beanDefinition.getRole()) { // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE if (logger.isWarnEnabled()) { logger.warn("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } else if (!beanDefinition.equals(existingDefinition)) { if (logger.isInfoEnabled()) { logger.info("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } else { if (logger.isDebugEnabled()) { logger.debug("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } this.beanDefinitionMap.put(beanName, beanDefinition); // 将beanName和beanDefinition存到beanDefinitionMap中 } // 如果beanDefinitionMap中不存在相同beanName的BeanDefinition else { if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { // 同步代码块 this.beanDefinitionMap.put(beanName, beanDefinition); // 将beanName和beanDefinition存到beanDefinitionMap中 List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1); updatedDefinitions.addAll(this.beanDefinitionNames); updatedDefinitions.add(beanName); this.beanDefinitionNames = updatedDefinitions; if (this.manualSingletonNames.contains(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames); updatedSingletons.remove(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } this.frozenBeanDefinitionNames = null; } if (existingDefinition != null || containsSingleton(beanName)) { resetBeanDefinition(beanName); } } [Spring_AnnotationConfigApplicationContext_ this_ _ register]: https://blog.csdn.net/qq_35620501/article/details/102986216 [Spring_AnnotationConfigApplicationContext_ refresh_invokeBeanFactoryPostProcessors]: https://blog.csdn.net/qq_35620501/article/details/102986266 [Spring_AnnotationConfigApplicationContext_ refresh_registerBeanPostProcessors]: https://blog.csdn.net/qq_35620501/article/details/102986421 [Spring_AnnotationConfigApplicationContext_ refresh_finishBeanFactoryInitialization]: https://blog.csdn.net/qq_35620501/article/details/102986848
还没有评论,来说两句吧...