spring Ioc源码解读(注解类的)一

Spring IoC(Inversion of Control,控制反转)容器是Spring框架的核心组件之一,用于管理和组织应用中的Java对象(也称为Bean)。IoC容器负责创建、配置、组装并管理Bean的生命周期。

springIoc的容器加载过程

配置代码:

  public static void main(String[] args) {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(MainConfig.class);
        var employee=context.getBean("employee", Employee.class);
        System.out.println(employee.getName());
    }
     AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(MainConfig.class); 创建AnnotationConfigApplicationContext对象

构造对象,首先回调用父类的构造方法:

GenericApplicationContext
public GenericApplicationContext() {
//父类的构造函数里面就是初始化DefaultListableBeanFactory,并且赋值给beanFactory
		this.beanFactory = new DefaultListableBeanFactory();
	}

接下来调用

public AnnotationConfigApplicationContext(Class... componentClasses) {
		this();
		register(componentClasses);
		refresh();
	}

 一下是关于this的源码解读

/**
Spring IoC 容器初始化过程中启动了与注解驱动的 Bean 定义读取和扫描相关的步骤
**/
public AnnotationConfigApplicationContext() {
        //这行代码创建了一个名为 "spring.context.annotated-bean-reader.create" 的启动步骤。StartupStep 是 Spring 用于跟踪应用程序启动过程的一种机制。
		StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
        //这一行代码创建了一个 AnnotatedBeanDefinitionReader 对象。AnnotatedBeanDefinitionReader 负责处理带有注解的类,并根据注解生成相应的 Bean 定义。通常,它用于处理类级别的注解,例如 @Component、@Service、@Repository 和 @Controller。

		this.reader = new AnnotatedBeanDefinitionReader(this);
		createAnnotatedBeanDefReader.end();
//这一行代码创建了一个 ClassPathBeanDefinitionScanner 对象。ClassPathBeanDefinitionScanner 负责在类路径下扫描带有特定注解的组件,并将它们注册为 Spring Bean。
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}

实例化建BeanDefinition读取器: AnnotatedBeanDefinitionReader:

public static Set registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {


		Set beanDefs = new LinkedHashSet<>(8);

//判断是否有ConfigurationClassPostProcessor Bean
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
 //就通过RootBeanDefinition的构造方法获得
//ConfigurationClassPostProcessor的BeanDefinition,RootBeanDefinition是BeanDefinition的子类
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
//执行registerPostProcessor方法,registerPostProcessor方法内部就是注册Bean,当然这里注册
//其他Bean也是一样的流程。
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		return beanDefs;
	}
创建 BeanDefinition扫描器:ClassPathBeanDefinitionScanner
注册配置类为BeanDefinition: register(annotatedClasses);
register(componentClasses);

org.springframework.context.annotation.AnnotatedBeanDefinitionReader#doRegisterBean

private  void doRegisterBean(Class beanClass, @Nullable String name,
			@Nullable Class[] qualifiers, @Nullable Supplier supplier,
			@Nullable BeanDefinitionCustomizer[] customizers) {

//拿到类上的注解
		AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
     //判断是否需要注解
		if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
			return;
		}

		abd.setInstanceSupplier(supplier);
        //判断bean的作用域,如果没有默认为单列
		ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
		abd.setScope(scopeMetadata.getScopeName());
		String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));

		AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
		if (qualifiers != null) {
			for (Class qualifier : qualifiers) {
				if (Primary.class == qualifier) {
					abd.setPrimary(true);
				}
				else if (Lazy.class == qualifier) {
					abd.setLazyInit(true);
				}
				else {
					abd.addQualifier(new AutowireCandidateQualifier(qualifier));
				}
			}
		}
		if (customizers != null) {
			for (BeanDefinitionCustomizer customizer : customizers) {
				customizer.customize(abd);
			}
		}

		BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
		definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
		BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
	}

org.springframework.beans.factory.support.BeanDefinitionReaderUtils#registerBeanDefinition

public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {
        //获取注册的bean的名称
        String beanName = definitionHolder.getBeanName();
        //将 Bean 定义注册到容器中。这个步骤将 Bean 的定义信息加入到容器的 BeanDefinitionMap 中。
        registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
        String[] aliases = definitionHolder.getAliases();
        if (aliases != null) {
            String[] var4 = aliases;
            int var5 = aliases.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String alias = var4[var6];
                registry.registerAlias(beanName, alias);
            }
        }

    }

org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition

/**
向容器注册一个 Bean 定义,包括了处理同名 BeanDefinition 的情况,验证 AbstractBeanDefinition,更新 BeanDefinitionMap 和 BeanDefinitionNames 等步骤。它是 Spring IoC 容器中注册 Bean 定义的核心逻辑。
**/
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
        Assert.hasText(beanName, "Bean name must not be empty");
        Assert.notNull(beanDefinition, "BeanDefinition must not be null");
        //如果 BeanDefinition 是 AbstractBeanDefinition 的实例,则进行验证
        if (beanDefinition instanceof AbstractBeanDefinition) {
            try {
                ((AbstractBeanDefinition)beanDefinition).validate();
            } catch (BeanDefinitionValidationException var8) {
                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", var8);
            }
        }

        BeanDefinition existingDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);
        if (existingDefinition != null) {
           //判断是否存在同名
处理存在同名 BeanDefinition 的情况
            if (!this.isAllowBeanDefinitionOverriding()) {
                throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
            }
             //
            if (existingDefinition.getRole() < beanDefinition.getRole()) {
                if (this.logger.isInfoEnabled()) {
                    this.logger.info("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
                }
            } else if (!beanDefinition.equals(existingDefinition)) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
                }
            } else if (this.logger.isTraceEnabled()) {
                this.logger.trace("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
            }

            this.beanDefinitionMap.put(beanName, beanDefinition);
        } else {
            if (this.hasBeanCreationStarted()) {
                synchronized(this.beanDefinitionMap) {
                    this.beanDefinitionMap.put(beanName, beanDefinition);
                    List updatedDefinitions = new ArrayList(this.beanDefinitionNames.size() + 1);
                    updatedDefinitions.addAll(this.beanDefinitionNames);
                    updatedDefinitions.add(beanName);
                    this.beanDefinitionNames = updatedDefinitions;
                    this.removeManualSingletonName(beanName);
                }
            } else {
                this.beanDefinitionMap.put(beanName, beanDefinition);
                this.beanDefinitionNames.add(beanName);
                this.removeManualSingletonName(beanName);
            }

            this.frozenBeanDefinitionNames = null;
        }

        if (existingDefinition == null && !this.containsSingleton(beanName)) {
            if (this.isConfigurationFrozen()) {
                this.clearByTypeCache();
            }
        } else {
            this.resetBeanDefinition(beanName);
        }

    }

你可能感兴趣的:(spring,java,前端)