spring-ioc(二)-註冊配置類

不要問我閱讀spring源碼有什麼用,問就是沒有用,只是讓我本身使用spring的過程當中自信點!java

相關文章

spring-相關文章spring

註冊配置類

直接看代碼app

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
        //這裏在上篇已經說過了,主要是註冊了幾個spring內部的bean
	this();
	//本文的主要內容爲下面這句的代碼
	register(annotatedClasses);
	refresh();
}
複製代碼
public void register(Class<?>... annotatedClasses) {
	Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
	//這個讀取器應該記得是 AnnotationConfigApplicationContext 的無參構造器中建立的吧,裏面有一個註冊器
	this.reader.register(annotatedClasses);
}
複製代碼
public void register(Class<?>... annotatedClasses) {
	for (Class<?> annotatedClass : annotatedClasses) {
	       // 這裏
		registerBean(annotatedClass);
	}
}
複製代碼
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
        //annotatedClass爲你傳遞的參數,也就是本身的配置類
        //這個地方根據你的配置類的class類型去建立一個beanDefinition
        //之前額文章中我記得我說過 beanDefinition 是對bean 的描述,就行是Class 是對類的描述同樣,只不過可能裏面東西多了點
	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
	//這個地方是判斷當前類是否被Conditional註釋
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}
    
	abd.setInstanceSupplier(instanceSupplier);
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
	//設置做用於 默認爲singleton
	abd.setScope(scopeMetadata.getScopeName());
	//獲取beanNam
	String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
    //設置一些屬性,例如Primary ,懶加載之類
	AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
	if (qualifiers != null) {
		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));
			}
		}
	}
	for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
		customizer.customize(abd);
	}
        //建立beanDefinition 的持有者,其實呢也就是對beanDefinition進行封裝
	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
	//註冊beanDefinition
	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
複製代碼

解釋beanDefinitionide

public AnnotatedGenericBeanDefinition(Class<?> beanClass) {
        //把當前class類型賦值給beanClass屬性
	setBeanClass(beanClass);
	//建立一個註解元數據,這個還挺重要,其實也就是對當前類的註解進行封裝保存下
	this.metadata = new StandardAnnotationMetadata(beanClass, true);
}
複製代碼
public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {

	// Register bean definition under primary name.
	String beanName = definitionHolder.getBeanName();
	//去註冊,傳遞的參數爲 beanName beanDefinition
	registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

	// Register aliases for bean name, if any.
	String[] aliases = definitionHolder.getAliases();
	//假如配置了別名,去設置別名
	if (aliases != null) {
		for (String alias : aliases) {
			registry.registerAlias(beanName, alias);
		}
	}
}
複製代碼

註冊的最後一段代碼post

@Override
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");

	if (beanDefinition instanceof AbstractBeanDefinition) {
		try {
			((AbstractBeanDefinition) beanDefinition).validate();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
					"Validation of bean definition failed", ex);
		}
	}
    //去beanDefinitionMap這個map中根據beanName查詢下是否存在
	BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
	if (existingDefinition != null) {
	    //假如存在
		if (!isAllowBeanDefinitionOverriding()) {
			throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
		}
		else if (existingDefinition.getRole() < beanDefinition.getRole()) {
			// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
			if (logger.isInfoEnabled()) {
				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 (logger.isDebugEnabled()) {
				logger.debug("Overriding bean definition for bean '" + beanName +
						"' with a different definition: replacing [" + existingDefinition +
						"] with [" + beanDefinition + "]");
			}
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("Overriding bean definition for bean '" + beanName +
						"' with an equivalent definition: replacing [" + existingDefinition +
						"] with [" + beanDefinition + "]");
			}
		}
		//直接覆蓋了
		this.beanDefinitionMap.put(beanName, beanDefinition);
	}
	else {
	        //不存在
		if (hasBeanCreationStarted()) {
			// Cannot modify startup-time collection elements anymore (for stable iteration)
			synchronized (this.beanDefinitionMap) {
				this.beanDefinitionMap.put(beanName, beanDefinition);
				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
			//以beanName爲key,beanDefinition爲vlaue存入beanDefinitionMap
			//如今應該知道註冊是意思了吧,就是把描述bean信息的beanDefinition 存放在一個map中
			this.beanDefinitionMap.put(beanName, beanDefinition);
			//把bean名字也存放下
			this.beanDefinitionNames.add(beanName);
			//這個暫時不知道幹啥的
			this.manualSingletonNames.remove(beanName);
		}
		this.frozenBeanDefinitionNames = null;
	}

	if (existingDefinition != null || containsSingleton(beanName)) {
		resetBeanDefinition(beanName);
	}
}
複製代碼

總結

  1. 本文只是註冊了一個配置類
  2. 所謂的註冊就是把描述bean信息的beanDefinition 存放在一個map中
  3. 這個map叫作beanDefinitionMap它是bean工廠的一個屬性
  4. 註冊器就是bean工廠自己
相關文章
相關標籤/搜索