spring-IOC容器原始碼分析(二)BeanDefinition註冊流程

暱稱又又被用了發表於2018-11-19

本篇文章主要介紹以下幾個部分:

  1. BeanFactory介面體系
  2. BeanDefinition的介面實現類體系
  3. 梳理註冊註解配置類流程
  4. 從解析@Scope的流程入手,分析一個通用的spring解析註解屬性的流程
  5. java code config基於註解配置的原理

BeanFactory介面體系

以DefaultListableBeanFactory為例梳理一下BeanFactory介面體系的細節

spring-IOC容器原始碼分析(二)BeanDefinition註冊流程

主要介面、抽象類的作用如下:

  1. BeanFactory(根據註冊的bean定義來生產bean的功能)
  2. BeanRegistry(bean定義的註冊功能)
  3. BeanDefinition(bean的定義資訊)

BeanFactory

  1. BeanFactory:用於訪問Spring bean容器的根介面,提供多個過載的getBean方法來獲取註冊到容器中的bean的例項
  2. HierarchicalBeanFactory:為Spring bean 容器提供父子容器的上下層級關係的能力
  3. ListableBeanFactory:提供遍歷Spring bean容器中bean的能力但其方法只檢查容器內部bean的定義,而不會真正的例項化bean;並且不會包含其父容器中的bean定義
  4. ConfigurableBeanFactory:提供遍歷Spring bean容器的能力,比如向container中增加BeanPostProcessor
  5. AutowireCapableBeanFactory:提供自動注入bean屬性的能力,以及其他框架的整合程式碼可以利用這個介面來連線和填充Spring無法控制的現有bean例項生命週期

BeanRegistry

  1. AliasRegistry:用於管理bean別名的介面
  2. BeanDefinitionRegistry:提供註冊BeanDefinition的能力

BeanDefinition

  1. AnnotatedBeanDefinition:註解的後設資料
  2. RootBeanDefinition:在Spring bean容器執行期間,通過合併註冊到容器中的bean定義生成的bean後設資料

總結

在spring的容器介面體系中,我們可以使用原材料、工廠、生產線操作工人、最終產品的關係來類比BeanDefinition、BeanFactory、BeanRegistry、bean例項。 BeanRegistry提供能力將BeanDefinition註冊到BeanFactory中,BeanFactory通過其內部的生產線來生成bean例項

BeanDefinition的介面實現類體系

以AnnotatedGenericBeanDefinition為例梳理一下BeanDefinition介面實現類體系

Metadata後設資料部分

Metadata後設資料部分在其內部包裝了需要註冊到BeanFactory的類的資訊

類圖

spring-IOC容器原始碼分析(二)BeanDefinition註冊流程

類關係說明

  1. ClassMetadata,抽象出類的後設資料的介面。提供獲取類名、判斷是否為介面類、是否為註解類、是否為抽象類等功能;
  2. AnnotatedTypeMetadata,定義了介面,用於訪問AnnotationMetadata、MethodMetadata這兩個類的註解。提供判斷是否被指定註解標記、獲取指定註解的屬性等功能;
  3. AnnotationMetadata,定義了介面,用於訪問指定類的註解;如getMetaAnnotationTypes(String annotationName)用於獲取指定註解annotationName的元註解集合
  4. StandardClassMetadata,用標準的反射功能實現了ClassMetadata類
  5. StandardAnnotationMetadata,擴充套件StandardClassMetadata類並實現AnnotationMetadata介面

BeanDefinition部分

BeanDefinition作為註冊到BeanFactory中的載體,在具體的實現類中,持有metadata例項。

類圖

spring-IOC容器原始碼分析(二)BeanDefinition註冊流程

類關係說明

  1. AttributeAccessor,定義設定和獲取屬性後設資料的介面;
  2. AttributeAccessorSupport,在內部通過LinkedHashMap實現了AttributeAccessor介面;
  3. BeanMetadataElement,持有一個source,具體用途待考究;
  4. BeanMetadataAttribute,實現BeanMetadataElement介面,在其內部以key-value的形式持有bean definition的屬性;
  5. BeanMetadataAttributeAccessor,實現BeanMetadataElement介面,並重寫部分AttributeAccessorSupport的介面,用於設定和獲取BeanMetadataElement;
  6. BeanDefinition,一個BeanDefinition物件用於描述一個bean instance,其中擁有屬性值、構造器屬性值以及更多由其子類提供的資訊;
  7. AbstractBeanDefinition:實現了BeanDefinition介面,提供了設定和獲取bean definition中的各個屬性(即類的各種屬性資料)
  8. AnnotatedBeanDefinition,提供介面用於獲取被包裝的類的後設資料
  9. GenericBeanDefinition,提供parent bean的設定功能
  10. AnnotatedGenericBeanDefinition,擴充套件自GenericBeanDefinition,實現AnnotatedBeanDefinition提供暴露註解後設資料的支援功能

註冊註解配置類流程

主流程

spring-IOC容器原始碼分析(二)BeanDefinition註冊流程

原始碼分析

public class AnnotatedBeanDefinitionReader {

    // 省略部分程式碼
    public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {
		AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
		if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
			return;
		}
        // 解析@Scope註解,獲取bean的作用域配置資訊
		ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
		abd.setScope(scopeMetadata.getScopeName());
		String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
        // 解析通用註解,如@Lazy等
		AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
        // 定義qualifier資訊,主要涉及到後續指定bean注入的註解@Qualifier
		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));
				}
			}
		}

		BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
        // 根據ScopeMetadata生成對應的Scope代理
		definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
        // 實際bean的注入,在registry內部用一個ConcurrentHashMap持有了beandefinition資訊
		BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
	}

}
複製程式碼

解析@Scope的流程,分析spring解析註解類屬性值的流程

主流程

spring-IOC容器原始碼分析(二)BeanDefinition註冊流程

原始碼分析

// @Scope註解的解析器
public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {

    // 解析@Scope註解,構造ScopeMetadata例項,持有bean作用域的配置資訊
    @Override
	public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
		ScopeMetadata metadata = new ScopeMetadata();
		if (definition instanceof AnnotatedBeanDefinition) {
			AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
            // 獲取指定註解的屬性值對,此處為@Scope註解
			AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
					annDef.getMetadata(), this.scopeAnnotationType);
            // 如果屬性不為null,則根據屬性值對修改ScopeMetadata的值
			if (attributes != null) {
				metadata.setScopeName(attributes.getString("value"));
				ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
				if (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) {
					proxyMode = this.defaultProxyMode;
				}
				metadata.setScopedProxyMode(proxyMode);
			}
		}
		return metadata;
	}

}

// 註解配置資訊的輔助工具類
public class AnnotationConfigUtils {

    // 獲取metadata中,annotationClass註解型別的屬性值,用AnnotationAttributes(繼承自LinkedHashMap,額外儲存了註解型別等資訊)持有
    static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annotationClass) {
		return attributesFor(metadata, annotationClass.getName());
	}

    // 獲取metadata中,annotationClass註解型別的屬性值,用AnnotationAttributes(繼承自LinkedHashMap,額外儲存了註解型別等資訊)持有
    static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annotationClassName) {
		return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClassName, false));
	}

}

// 持有類的後設資料
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {

    // 獲取指定註解名annotationName中的屬性值對
    @Override
	public Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString) {
		return (this.annotations.length > 0 ? AnnotatedElementUtils.getMergedAnnotationAttributes(
				getIntrospectedClass(), annotationName, classValuesAsString, this.nestedAnnotationsAsMap) : null);
	}

}

// 用於在AnnotatedElement上查詢註解、元註解、可重複註解的工具類
public class AnnotatedElementUtils {

    public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element,
			String annotationName, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {

		Assert.hasLength(annotationName, "'annotationName' must not be null or empty");
        // 根據註解名查詢註解的屬性值對
		AnnotationAttributes attributes = searchWithGetSemantics(element, null, annotationName,
				new MergedAnnotationAttributesProcessor(classValuesAsString, nestedAnnotationsAsMap));

        // 處理註解別名
		AnnotationUtils.postProcessAnnotationAttributes(element, attributes, classValuesAsString, nestedAnnotationsAsMap);
		return attributes;
	}

    private static <T> T searchWithGetSemantics(AnnotatedElement element,
			Class<? extends Annotation> annotationType, String annotationName, Processor<T> processor) {
        // 將查詢工作,轉發給processor處理(Processor -> MergedAnnotationAttributesProcessor)
		return searchWithGetSemantics(element, annotationType, annotationName, null, processor);
	}

    private static <T> T searchWithGetSemantics(AnnotatedElement element,
			Class<? extends Annotation> annotationType, String annotationName,
			Class<? extends Annotation> containerType, Processor<T> processor) {

		try {
            // 進行第一層查詢(metaDepth=0)
			return searchWithGetSemantics(element, annotationType, annotationName,
					containerType, processor, new HashSet<AnnotatedElement>(), 0);
		}
		catch (Throwable ex) {
			AnnotationUtils.rethrowAnnotationConfigurationException(ex);
			throw new IllegalStateException("Failed to introspect annotations on " + element, ex);
		}
	}

    private static <T> T searchWithGetSemantics(AnnotatedElement element,
			Class<? extends Annotation> annotationType, String annotationName,
			Class<? extends Annotation> containerType, Processor<T> processor,
			Set<AnnotatedElement> visited, int metaDepth) {

		Assert.notNull(element, "AnnotatedElement must not be null");

		if (visited.add(element)) {
			try {
				// Start searching within locally declared annotations
				List<Annotation> declaredAnnotations = Arrays.asList(element.getDeclaredAnnotations());
                // 轉發給過載方法,進行實際的查詢操作
				T result = searchWithGetSemanticsInAnnotations(element, declaredAnnotations,
						annotationType, annotationName, containerType, processor, visited, metaDepth);
				if (result != null) {
					return result;
				}

				if (element instanceof Class) {  // otherwise getAnnotations does not return anything new
					List<Annotation> inheritedAnnotations = new ArrayList<Annotation>();
					for (Annotation annotation : element.getAnnotations()) {
						if (!declaredAnnotations.contains(annotation)) {
							inheritedAnnotations.add(annotation);
						}
					}

					// Continue searching within inherited annotations
					result = searchWithGetSemanticsInAnnotations(element, inheritedAnnotations,
							annotationType, annotationName, containerType, processor, visited, metaDepth);
					if (result != null) {
						return result;
					}
				}
			}
			catch (Throwable ex) {
				AnnotationUtils.handleIntrospectionFailure(element, ex);
			}
		}

		return null;
	}

    // 執行實際的註解屬性查詢功能
    private static <T> T searchWithGetSemanticsInAnnotations(AnnotatedElement element,
			List<Annotation> annotations, Class<? extends Annotation> annotationType,
			String annotationName, Class<? extends Annotation> containerType,
			Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth) {

		// Search in annotations
        // 遍歷註解列表
		for (Annotation annotation : annotations) {
			Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
            // 只處理非JDK內建的註解
			if (!AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) {
                // 滿足以下任意條件,需要呼叫processor.process(element, annotation, metaDepth)方法進行屬性值的查詢工作
                // 1. 如果當前迴圈的註解,為我們指定的註解型別
                // 2. 如果當前迴圈的註解,為我們指定的註解名稱
                // 3. 始終呼叫processor,即processor.alwaysProcesses()返回true
				if (currentAnnotationType == annotationType ||
						currentAnnotationType.getName().equals(annotationName) ||
						processor.alwaysProcesses()) {
                    // 查詢註解屬性值
					T result = processor.process(element, annotation, metaDepth);
					if (result != null) {
                        
						if (processor.aggregates() && metaDepth == 0) {
                            // 聚合查詢結果
							processor.getAggregatedResults().add(result);
						}
						else {
							return result;
						}
					}
				}
				// Repeatable annotations in container?
				else if (currentAnnotationType == containerType) {
					for (Annotation contained : getRawAnnotationsFromContainer(element, annotation)) {
						T result = processor.process(element, contained, metaDepth);
						if (result != null) {
							// No need to post-process since repeatable annotations within a
							// container cannot be composed annotations.
							processor.getAggregatedResults().add(result);
						}
					}
				}
			}
		}

		// Recursively search in meta-annotations
		for (Annotation annotation : annotations) {
			Class<? extends Annotation> currentAnnotationType = annotation.annotationType();
			if (!AnnotationUtils.isInJavaLangAnnotationPackage(currentAnnotationType)) {
				T result = searchWithGetSemantics(currentAnnotationType, annotationType,
						annotationName, containerType, processor, visited, metaDepth + 1);
				if (result != null) {
					processor.postProcess(element, annotation, result);
					if (processor.aggregates() && metaDepth == 0) {
						processor.getAggregatedResults().add(result);
					}
					else {
						return result;
					}
				}
			}
		}

		return null;
	}

}

private static class MergedAnnotationAttributesProcessor implements Processor<AnnotationAttributes> {

    @Override
    public AnnotationAttributes process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
        return AnnotationUtils.retrieveAnnotationAttributes(annotatedElement, annotation,
                this.classValuesAsString, this.nestedAnnotationsAsMap);
    }

}


public abstract class AnnotationUtils {

    // 將註解屬性值包裝為AnnotationAttributes,返回給上層呼叫
    static AnnotationAttributes retrieveAnnotationAttributes(Object annotatedElement, Annotation annotation,
			boolean classValuesAsString, boolean nestedAnnotationsAsMap) {

		Class<? extends Annotation> annotationType = annotation.annotationType();
		AnnotationAttributes attributes = new AnnotationAttributes(annotationType);

		for (Method method : getAttributeMethods(annotationType)) {
			try {
				Object attributeValue = method.invoke(annotation);
				Object defaultValue = method.getDefaultValue();
				if (defaultValue != null && ObjectUtils.nullSafeEquals(attributeValue, defaultValue)) {
					attributeValue = new DefaultValueHolder(defaultValue);
				}
				attributes.put(method.getName(),
						adaptValue(annotatedElement, attributeValue, classValuesAsString, nestedAnnotationsAsMap));
			}
			catch (Throwable ex) {
				if (ex instanceof InvocationTargetException) {
					Throwable targetException = ((InvocationTargetException) ex).getTargetException();
					rethrowAnnotationConfigurationException(targetException);
				}
				throw new IllegalStateException("Could not obtain annotation attribute value for " + method, ex);
			}
		}

		return attributes;
	}

}
複製程式碼

基於註解配置,註冊bean的原理

在spring的高版本中,官方建議開發者使用java code的配置方式。其原理主要是利用ConfigurationClassPostProcessor類來進行解析。執行的時機發生在容器啟動後,呼叫invokeBeanFactoryPostProcessors()方法這一步。

主流程

spring-IOC容器原始碼分析(二)BeanDefinition註冊流程

原始碼分析

public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
		PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {

    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		List<BeanDefinitionHolder> configCandidates = new ArrayList<BeanDefinitionHolder>();
		String[] candidateNames = registry.getBeanDefinitionNames();

        // 遍歷beanfactory中所有已註冊的bean
		for (String beanName : candidateNames) {
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            // 判斷是否為處理過的full配置類
			if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
                    // 判斷是否為處理過的lite配置類
					ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
            // 判斷是否為配置類(標註了@Configuration、@Component、@ComponentScan、@Import、@ImportResource)
            // 為full配置類時,為beanDef增加鍵為org.springframework.context.annotation.ConfigurationClassPostProcessor.configurationClass,值為full的attribute
            // 為lite配置類時,為beanDef增加鍵為org.springframework.context.annotation.ConfigurationClassPostProcessor.configurationClass,值為lite的attribute
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
			}
		}

		// Return immediately if no @Configuration classes were found
		if (configCandidates.isEmpty()) {
			return;
		}

		// Sort by previously determined @Order value, if applicable
        // 配置類可以按照順序載入
		Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() {
			@Override
			public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) {
				int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
				int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
				return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
			}
		});

		// Detect any custom bean name generation strategy supplied through the enclosing application context
		SingletonBeanRegistry sbr = null;
		if (registry instanceof SingletonBeanRegistry) {
			sbr = (SingletonBeanRegistry) registry;
			if (!this.localBeanNameGeneratorSet && sbr.containsSingleton(CONFIGURATION_BEAN_NAME_GENERATOR)) {
				BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
				this.componentScanBeanNameGenerator = generator;
				this.importBeanNameGenerator = generator;
			}
		}

		// Parse each @Configuration class
		ConfigurationClassParser parser = new ConfigurationClassParser(
				this.metadataReaderFactory, this.problemReporter, this.environment,
				this.resourceLoader, this.componentScanBeanNameGenerator, registry);

		Set<BeanDefinitionHolder> candidates = new LinkedHashSet<BeanDefinitionHolder>(configCandidates);
		Set<ConfigurationClass> alreadyParsed = new HashSet<ConfigurationClass>(configCandidates.size());
		do {
            // 解析配置類,完成這一步流程後,在其內部對各種配置資訊,包裝為一個ConfigurationClass的集合
            // 在載入bean的過程中,實際上也是對這個集合進行各種操作,如:從@Bean方法載入bean、@Import匯入配置等等
			parser.parse(candidates);
			parser.validate();

			Set<ConfigurationClass> configClasses = new LinkedHashSet<ConfigurationClass>(parser.getConfigurationClasses());
			configClasses.removeAll(alreadyParsed);

			// Read the model and create bean definitions based on its content
			if (this.reader == null) {
				this.reader = new ConfigurationClassBeanDefinitionReader(
						registry, this.sourceExtractor, this.resourceLoader, this.environment,
						this.importBeanNameGenerator, parser.getImportRegistry());
			}
            // 對ConfigurationClassParser持有的配置資訊集合進行bean的載入。
            // 至此,需要註冊到IOC容器的所有bean都已註冊完畢
			this.reader.loadBeanDefinitions(configClasses);
			alreadyParsed.addAll(configClasses);

			candidates.clear();
			if (registry.getBeanDefinitionCount() > candidateNames.length) {
				String[] newCandidateNames = registry.getBeanDefinitionNames();
				Set<String> oldCandidateNames = new HashSet<String>(Arrays.asList(candidateNames));
				Set<String> alreadyParsedClasses = new HashSet<String>();
				for (ConfigurationClass configurationClass : alreadyParsed) {
					alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
				}
				for (String candidateName : newCandidateNames) {
					if (!oldCandidateNames.contains(candidateName)) {
						BeanDefinition bd = registry.getBeanDefinition(candidateName);
						if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
								!alreadyParsedClasses.contains(bd.getBeanClassName())) {
							candidates.add(new BeanDefinitionHolder(bd, candidateName));
						}
					}
				}
				candidateNames = newCandidateNames;
			}
		}
		while (!candidates.isEmpty());

		// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
		if (sbr != null) {
			if (!sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
				sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
			}
		}

		if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
			((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
		}
	}

}
複製程式碼

相關文章