Springboot漫游日志(38)

Springboot漫游日志(38)

遗留:【Binder】【logback日志】【加载properties或者yml】【解析环境变量key】【PathMatchingResourcePatternResolver】【AbstractBeanFactory】的【getBean(String name, Class requiredType)】方法

现在看:【AnnotatedBeanDefinitionReader】的【register】方法,135行
参数【SpringbootRoamApplication】的class对象。

/**
 * Register one or more component classes to be processed.
 * <p>Calls to {@code register} are idempotent; adding the same
 * component class more than once has no additional effect.
 * @param componentClasses one or more component classes,
 * e.g. {@link Configuration @Configuration} classes
 */
public void register(Class<?>... componentClasses) {
	for (Class<?> componentClass : componentClasses) {
		registerBean(componentClass);
	}
}
/**
 * Register a bean from the given bean class, deriving its metadata from
 * class-declared annotations.
 * @param beanClass the class of the bean
 */
public void registerBean(Class<?> beanClass) {
	doRegisterBean(beanClass, null, null, null, null);
}
/**
 * Register a bean from the given bean class, deriving its metadata from
 * class-declared annotations.
 * @param beanClass the class of the bean
 * @param name an explicit name for the bean
 * @param qualifiers specific qualifier annotations to consider, if any,
 * in addition to qualifiers at the bean class level
 * @param supplier a callback for creating an instance of the bean
 * (may be {@code null})
 * @param customizers one or more callbacks for customizing the factory's
 * {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
 * @since 5.0
 */
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
		@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
		@Nullable BeanDefinitionCustomizer[] customizers) {

	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}

	abd.setInstanceSupplier(supplier);
	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<? 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));
			}
		}
	}
	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);
}

注释:从给定的bean类中注册一个bean,并从类声明的批注中派生其元数据

这里的beanClass就是入口类【SpringbootRoamApplication】

一行一行看。

AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass); 

先看这个类的继承结构

在这里插入图片描述

三个构造方法

/**
 * Create a new AbstractBeanDefinition with default settings.
 */
protected AbstractBeanDefinition() {
	this(null, null);
}

/**
 * Create a new AbstractBeanDefinition with the given
 * constructor argument values and property values.
 */
protected AbstractBeanDefinition(@Nullable ConstructorArgumentValues cargs, @Nullable MutablePropertyValues pvs) {
	this.constructorArgumentValues = cargs;
	this.propertyValues = pvs;
}
/**
 * Create a new GenericBeanDefinition, to be configured through its bean
 * properties and configuration methods.
 * @see #setBeanClass
 * @see #setScope
 * @see #setConstructorArgumentValues
 * @see #setPropertyValues
 */
public GenericBeanDefinition() {
	super();
}
/**
 * Create a new AnnotatedGenericBeanDefinition for the given bean class.
 * @param beanClass the loaded bean class
 */
public AnnotatedGenericBeanDefinition(Class<?> beanClass) {
	setBeanClass(beanClass);
	this.metadata = AnnotationMetadata.introspect(beanClass);
}

AbstractBeanDefinition的属性【beanClass】被设置为【SpringbootRoamApplication】

/**
 * Factory method to create a new {@link AnnotationMetadata} instance
 * for the given class using standard reflection.
 * @param type the class to introspect
 * @return a new {@link AnnotationMetadata} instance
 * @since 5.2
 */
static AnnotationMetadata introspect(Class<?> type) {
	return StandardAnnotationMetadata.from(type);
}
static AnnotationMetadata from(Class<?> introspectedClass) {
	return new StandardAnnotationMetadata(introspectedClass, true);
}

到这里,实例化了一个对象。
在这里插入图片描述
结构简单。

/**
 * Create a new {@code StandardAnnotationMetadata} wrapper for the given Class.
 * @param introspectedClass the Class to introspect
 * @see #StandardAnnotationMetadata(Class, boolean)
 * @deprecated since 5.2 in favor of the factory method {@link AnnotationMetadata#introspect(Class)}
 */
@Deprecated
public StandardAnnotationMetadata(Class<?> introspectedClass) {
	this(introspectedClass, false);
}

/**
 * Create a new {@link StandardAnnotationMetadata} wrapper for the given Class,
 * providing the option to return any nested annotations or annotation arrays in the
 * form of {@link org.springframework.core.annotation.AnnotationAttributes} instead
 * of actual {@link Annotation} instances.
 * @param introspectedClass the Class to introspect
 * @param nestedAnnotationsAsMap return nested annotations and annotation arrays as
 * {@link org.springframework.core.annotation.AnnotationAttributes} for compatibility
 * with ASM-based {@link AnnotationMetadata} implementations
 * @since 3.1.1
 * @deprecated since 5.2 in favor of the factory method {@link AnnotationMetadata#introspect(Class)}.
 * Use {@link MergedAnnotation#asMap(org.springframework.core.annotation.MergedAnnotation.Adapt...) MergedAnnotation.asMap}
 * from {@link #getAnnotations()} rather than {@link #getAnnotationAttributes(String)}
 * if {@code nestedAnnotationsAsMap} is {@code false}
 */
@Deprecated
public StandardAnnotationMetadata(Class<?> introspectedClass, boolean nestedAnnotationsAsMap) {
	super(introspectedClass);
	this.mergedAnnotations = MergedAnnotations.from(introspectedClass,
			SearchStrategy.INHERITED_ANNOTATIONS, RepeatableContainers.none());
	this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
}
/**
 * Create a new StandardClassMetadata wrapper for the given Class.
 * @param introspectedClass the Class to introspect
 * @deprecated since 5.2 in favor of {@link StandardAnnotationMetadata}
 */
@Deprecated
public StandardClassMetadata(Class<?> introspectedClass) {
	Assert.notNull(introspectedClass, "Class must not be null");
	this.introspectedClass = introspectedClass;
}

【SpringbootRoamApplication】赋值给了【introspectedClass】

接着往下看

/**
 * Create a new {@link MergedAnnotations} instance containing all
 * annotations and meta-annotations from the specified element and,
 * depending on the {@link SearchStrategy}, related inherited elements.
 * @param element the source element
 * @param searchStrategy the search strategy to use
 * @param repeatableContainers the repeatable containers that may be used by
 * the element annotations or the meta-annotations
 * @return a {@link MergedAnnotations} instance containing the merged
 * element annotations
 */
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
		RepeatableContainers repeatableContainers) {

	return from(element, searchStrategy, repeatableContainers, AnnotationFilter.PLAIN);
}

注释:创建一个新的{@link MergedAnnotations}实例,该实例包含指定元素的所有注释和元注释,并取决于{@link SearchStrategy},并包含相关的继承元素。

static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
			RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {

	Assert.notNull(repeatableContainers, "RepeatableContainers must not be null");
	Assert.notNull(annotationFilter, "AnnotationFilter must not be null");
	return TypeMappedAnnotations.from(element, searchStrategy, repeatableContainers, annotationFilter);
}
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
			RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
	if (AnnotationsScanner.isKnownEmpty(element, searchStrategy)) {
		return NONE;
	}
	return new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter);
}
private TypeMappedAnnotations(AnnotatedElement element, SearchStrategy searchStrategy,
			RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
	this.source = element;
	this.element = element;
	this.searchStrategy = searchStrategy;
	this.annotations = null;
	this.repeatableContainers = repeatableContainers;
	this.annotationFilter = annotationFilter;
}

一直到这里,也是实例化了一个类。

source是入口类class
element 和source一样
searchStrategy 值为【SearchStrategy.INHERITED_ANNOTATIONS】

【SearchStrategy.INHERITED_ANNOTATIONS】的注释为:查找所有直接声明的注释以及任何{@link Inherited @Inherited}超类注释。 该策略仅在与{@link Class}类型一起使用时才真正有用,因为所有其他{@linkplain AnnotatedElement带注释元素}都将忽略{@link Inherited @Inherited}注释。 此策略不搜索已实现的接口

annotations 是null
repeatableContainers 是【NoRepeatableContainers.INSTANCE】
annotationFilter 是【AnnotationFilter.PLAIN】

/**
 * {@link AnnotationFilter} that matches annotations in the
 * {@code java.lang} and {@code org.springframework.lang} packages
 * and their subpackages.
 * <p>This is the default filter in the {@link MergedAnnotations} model.
 */
AnnotationFilter PLAIN = packages("java.lang", "org.springframework.lang");

看一样,回到【StandardAnnotationMetadata】的构造方法
属性【nestedAnnotationsAsMap 】被设置为true

然后【AnnotatedGenericBeanDefinition】实例化完毕。

回到【AnnotatedBeanDefinitionReader】的方法【doRegisterBean】253行。
读下一行。

if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
	return;
}

进入【shouldSkip】方法

/**
 * Determine if an item should be skipped based on {@code @Conditional} annotations.
 * The {@link ConfigurationPhase} will be deduced from the type of item (i.e. a
 * {@code @Configuration} class will be {@link ConfigurationPhase#PARSE_CONFIGURATION})
 * @param metadata the meta data
 * @return if the item should be skipped
 */
public boolean shouldSkip(AnnotatedTypeMetadata metadata) {
	return shouldSkip(metadata, null);
}

注释:
根据{@code @Conditional}注释确定是否应跳过某项。{@ link ConfigurationPhase}将根据该项的类型推论得出(即{@code @Configuration}类将是{@link ConfigurationPhase#PARSE_CONFIGURATION} )

/**
 * Determine if an item should be skipped based on {@code @Conditional} annotations.
 * @param metadata the meta data
 * @param phase the phase of the call
 * @return if the item should be skipped
 */
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
	if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
		return false;
	}

	if (phase == null) {
		if (metadata instanceof AnnotationMetadata &&
				ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
			return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
		}
		return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
	}

	List<Condition> conditions = new ArrayList<>();
	for (String[] conditionClasses : getConditionClasses(metadata)) {
		for (String conditionClass : conditionClasses) {
			Condition condition = getCondition(conditionClass, this.context.getClassLoader());
			conditions.add(condition);
		}
	}

	AnnotationAwareOrderComparator.sort(conditions);

	for (Condition condition : conditions) {
		ConfigurationPhase requiredPhase = null;
		if (condition instanceof ConfigurationCondition) {
			requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
		}
		if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
			return true;
		}
	}

	return false;
}

注释:根据{@code @Conditional}批注确定是否应跳过一项。

如果metadata是null或者注解中不包含【Conditional】注解,都不应该跳过。
phase参数是null,所以进入if条件
metadata是AnnotationMetadata 类型,所以看方法【ConfigurationClassUtils.isConfigurationCandidate】

/**
 * Check the given metadata for a configuration class candidate
 * (or nested component class declared within a configuration/component class).
 * @param metadata the metadata of the annotated class
 * @return {@code true} if the given class is to be registered for
 * configuration class processing; {@code false} otherwise
 */
public static boolean isConfigurationCandidate(AnnotationMetadata metadata) {
	// Do not consider an interface or an annotation...
	if (metadata.isInterface()) {
		return false;
	}

	// Any of the typical annotations found?
	for (String indicator : candidateIndicators) {
		if (metadata.isAnnotated(indicator)) {
			return true;
		}
	}

	// Finally, let's look for @Bean methods...
	try {
		return metadata.hasAnnotatedMethods(Bean.class.getName());
	}
	catch (Throwable ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("Failed to introspect @Bean methods on class [" + metadata.getClassName() + "]: " + ex);
		}
		return false;
	}
}

注释:
检查给定的元数据中是否有配置类候选对象(或在配置/组件类中声明的嵌套组件类)

一行一行看,这里的metadata是【StandardAnnotationMetadata】

第一个if的代码找到【StandardAnnotationMetadata】的父类【StandardClassMetadata】

@Override
public boolean isInterface() {
	return this.introspectedClass.isInterface();
}

这里的【introspectedClass】是【SpringbootRoamApplication】的类对象。
显然这里是false。
往下读

private static final Set<String> candidateIndicators = new HashSet<>(8);
static {
	candidateIndicators.add(Component.class.getName());
	candidateIndicators.add(ComponentScan.class.getName());
	candidateIndicators.add(Import.class.getName());
	candidateIndicators.add(ImportResource.class.getName());
}

属性【candidateIndicators】是一个集合,放的都是比较眼熟的spring注解。

/**
 * Determine whether the underlying element has an annotation or meta-annotation
 * of the given type defined.
 * <p>If this method returns {@code true}, then
 * {@link #getAnnotationAttributes} will return a non-null Map.
 * @param annotationName the fully qualified class name of the annotation
 * type to look for
 * @return whether a matching annotation is defined
 */
default boolean isAnnotated(String annotationName) {
	return getAnnotations().isPresent(annotationName);
}

这是定义在接口里面的默认实现。getAnnotations是抽象方法。
找到【StandardAnnotationMetadata】的【getAnnotations】

@Override
public MergedAnnotations getAnnotations() {
	return this.mergedAnnotations;
}

mergedAnnotations在【StandardAnnotationMetadata】实例化的时候有定义,最终是一个【TypeMappedAnnotations】类。
【TypeMappedAnnotations】里面参数是String的【isPresent】方法如下:

@Override
public boolean isPresent(String annotationType) {
	if (this.annotationFilter.matches(annotationType)) {
		return false;
	}
	return Boolean.TRUE.equals(scan(annotationType,
			IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
}

annotationFilter的值也找到,是这个。

/**
 * {@link AnnotationFilter} that matches annotations in the
 * {@code java.lang} and {@code org.springframework.lang} packages
 * and their subpackages.
 * <p>This is the default filter in the {@link MergedAnnotations} model.
 */
AnnotationFilter PLAIN = packages("java.lang", "org.springframework.lang");
/**
 * Create a new {@link AnnotationFilter} that matches annotations in the
 * specified packages.
 * @param packages the annotation packages that should match
 * @return a new {@link AnnotationFilter} instance
 */
static AnnotationFilter packages(String... packages) {
	return new PackagesAnnotationFilter(packages);
}
private final String[] prefixes;
private final int hashCode;
PackagesAnnotationFilter(String... packages) {
	Assert.notNull(packages, "Packages array must not be null");
	this.prefixes = new String[packages.length];
	for (int i = 0; i < packages.length; i++) {
		String pkg = packages[i];
		Assert.hasText(pkg, "Packages array must not have empty elements");
		this.prefixes[i] = pkg + ".";
	}
	Arrays.sort(this.prefixes);
	this.hashCode = Arrays.hashCode(this.prefixes);
}

PackagesAnnotationFilter的matches方法如下:

@Override
public boolean matches(String annotationType) {
	for (String prefix : this.prefixes) {
		if (annotationType.startsWith(prefix)) {
			return true;
		}
	}
	return false;
}

如果以这些包前缀开头返回true,否则返回false。
所以【TypeMappedAnnotations】的isPresent方法,跳过if,走到return。

return Boolean.TRUE.equals(scan(annotationType,
			IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));

看【IsPresent.get】

static IsPresent get(RepeatableContainers repeatableContainers,
				AnnotationFilter annotationFilter, boolean directOnly) {
	// Use a single shared instance for common combinations
	if (annotationFilter == AnnotationFilter.PLAIN) {
		if (repeatableContainers == RepeatableContainers.none()) {
			return SHARED[directOnly ? 0 : 1];
		}
		if (repeatableContainers == RepeatableContainers.standardRepeatables()) {
			return SHARED[directOnly ? 2 : 3];
		}
	}
	return new IsPresent(repeatableContainers, annotationFilter, directOnly);
}

repeatableContainers是【NoRepeatableContainers.INSTANCE】
annotationFilter是【AnnotationFilter.PLAIN】
directOnly是false
所以返回【return SHARED[1]】

SHARED[1] = new IsPresent(RepeatableContainers.none(), AnnotationFilter.PLAIN, false);

private final RepeatableContainers repeatableContainers;
private final AnnotationFilter annotationFilter;
private final boolean directOnly;
private IsPresent(RepeatableContainers repeatableContainers,
		AnnotationFilter annotationFilter, boolean directOnly) {
	this.repeatableContainers = repeatableContainers;
	this.annotationFilter = annotationFilter;
	this.directOnly = directOnly;
}

接着看scan方法

@Nullable
private <C, R> R scan(C criteria, AnnotationsProcessor<C, R> processor) {
	if (this.annotations != null) {
		R result = processor.doWithAnnotations(criteria, 0, this.source, this.annotations);
		return processor.finish(result);
	}
	if (this.element != null && this.searchStrategy != null) {
		return AnnotationsScanner.scan(criteria, this.element, this.searchStrategy, processor);
	}
	return null;
}

this.annotations 是null
element 是【SpringbootRoamApplication】
searchStrategy 是【SearchStrategy.INHERITED_ANNOTATIONS】
所以返回第二个if的内容。
进入【AnnotationsScanner】的【scan】方法。

/**
 * Scan the hierarchy of the specified element for relevant annotations and
 * call the processor as required.
 * @param context an optional context object that will be passed back to the
 * processor
 * @param source the source element to scan
 * @param searchStrategy the search strategy to use
 * @param processor the processor that receives the annotations
 * @return the result of {@link AnnotationsProcessor#finish(Object)}
 */
@Nullable
static <C, R> R scan(C context, AnnotatedElement source, SearchStrategy searchStrategy,
		AnnotationsProcessor<C, R> processor) {

	R result = process(context, source, searchStrategy, processor);
	return processor.finish(result);
}

context是criteria,是注解名称,有四个值。
source是element,是【SpringbootRoamApplication】
searchStrategy是【SearchStrategy.INHERITED_ANNOTATIONS】
processor是【IsPresent】
【IsPresent】的签名是:

private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> 

C是Object,R是Boolean。

注释:扫描指定元素的层次结构以获得相关注释,并根据需要调用处理器

@Nullable
private static <C, R> R process(C context, AnnotatedElement source,
		SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {

	if (source instanceof Class) {
		return processClass(context, (Class<?>) source, searchStrategy, processor);
	}
	if (source instanceof Method) {
		return processMethod(context, (Method) source, searchStrategy, processor);
	}
	return processElement(context, source, processor);
}

source 是class,所以进第一个if

@Nullable
private static <C, R> R processClass(C context, Class<?> source,
		SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
	switch (searchStrategy) {
		case DIRECT:
			return processElement(context, source, processor);
		case INHERITED_ANNOTATIONS:
			return processClassInheritedAnnotations(context, source, searchStrategy, processor);
		case SUPERCLASS:
			return processClassHierarchy(context, source, processor, false, false);
		case TYPE_HIERARCHY:
			return processClassHierarchy(context, source, processor, true, false);
		case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
			return processClassHierarchy(context, source, processor, true, true);
	}
	throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
}

searchStrategy是【SearchStrategy.INHERITED_ANNOTATIONS】
进入【processClassInheritedAnnotations】

@Nullable
private static <C, R> R processClassInheritedAnnotations(C context, Class<?> source,
		SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {

	try {
		if (isWithoutHierarchy(source, searchStrategy)) {
			return processElement(context, source, processor);
		}
		Annotation[] relevant = null;
		int remaining = Integer.MAX_VALUE;
		int aggregateIndex = 0;
		Class<?> root = source;
		while (source != null && source != Object.class && remaining > 0 &&
				!hasPlainJavaAnnotationsOnly(source)) {
			R result = processor.doWithAggregate(context, aggregateIndex);
			if (result != null) {
				return result;
			}
			Annotation[] declaredAnnotations = getDeclaredAnnotations(source, true);
			if (relevant == null && declaredAnnotations.length > 0) {
				relevant = root.getAnnotations();
				remaining = relevant.length;
			}
			for (int i = 0; i < declaredAnnotations.length; i++) {
				if (declaredAnnotations[i] != null) {
					boolean isRelevant = false;
					for (int relevantIndex = 0; relevantIndex < relevant.length; relevantIndex++) {
						if (relevant[relevantIndex] != null &&
								declaredAnnotations[i].annotationType() == relevant[relevantIndex].annotationType()) {
							isRelevant = true;
							relevant[relevantIndex] = null;
							remaining--;
							break;
						}
					}
					if (!isRelevant) {
						declaredAnnotations[i] = null;
					}
				}
			}
			result = processor.doWithAnnotations(context, aggregateIndex, source, declaredAnnotations);
			if (result != null) {
				return result;
			}
			source = source.getSuperclass();
			aggregateIndex++;
		}
	}
	catch (Throwable ex) {
		AnnotationUtils.handleIntrospectionFailure(source, ex);
	}
	return null;
}

这方法没完没了了都,看之。

private static boolean isWithoutHierarchy(AnnotatedElement source, SearchStrategy searchStrategy) {
	if (source == Object.class) {
		return true;
	}
	if (source instanceof Class) {
		Class<?> sourceClass = (Class<?>) source;
		boolean noSuperTypes = (sourceClass.getSuperclass() == Object.class &&
				sourceClass.getInterfaces().length == 0);
		return (searchStrategy == SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES ? noSuperTypes &&
				sourceClass.getEnclosingClass() == null : noSuperTypes);
	}
	if (source instanceof Method) {
		Method sourceMethod = (Method) source;
		return (Modifier.isPrivate(sourceMethod.getModifiers()) ||
				isWithoutHierarchy(sourceMethod.getDeclaringClass(), searchStrategy));
	}
	return true;
}

source是Class
判断是否有父类
【searchStrategy == SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES】是false
所以返回【noSuperTypes】,true。没有父类。

进入【processElement】方法

@Nullable
private static <C, R> R processElement(C context, AnnotatedElement source,
		AnnotationsProcessor<C, R> processor) {
	try {
		R result = processor.doWithAggregate(context, 0);
		return (result != null ? result : processor.doWithAnnotations(
			context, 0, source, getDeclaredAnnotations(source, false)));
	}
	catch (Throwable ex) {
		AnnotationUtils.handleIntrospectionFailure(source, ex);
	}
	return null;
}

又得返回processor的【doWithAggregate】方法瞅瞅。

/**
 * Called when an aggregate is about to be processed. This method may return
 * a {@code non-null} result to short-circuit any further processing.
 * @param context the context information relevant to the processor
 * @param aggregateIndex the aggregate index about to be processed
 * @return a {@code non-null} result if no further processing is required
 */
@Nullable
default R doWithAggregate(C context, int aggregateIndex) {
	return null;
}

processor是【IsPresent】但是没有实现【doWithAggregate】的两个参数方法。
doWithAggregate两个参数的方法在接口中定义。
注释:
在将要处理聚合时调用。 此方法可能返回{@code non-null}结果,以使任何进一步的处理短路

接着看

return (result != null ? result : processor.doWithAnnotations(
			context, 0, source, getDeclaredAnnotations(source, false)));

换成四个参数的【doWithAnnotations】方法。
先看一下【getDeclaredAnnotations】

static Annotation[] getDeclaredAnnotations(AnnotatedElement source, boolean defensive) {
	boolean cached = false;
	Annotation[] annotations = declaredAnnotationCache.get(source);
	if (annotations != null) {
		cached = true;
	}
	else {
		annotations = source.getDeclaredAnnotations();
		if (annotations.length != 0) {
			boolean allIgnored = true;
			for (int i = 0; i < annotations.length; i++) {
				Annotation annotation = annotations[i];
				if (isIgnorable(annotation.annotationType()) ||
						!AttributeMethods.forAnnotationType(annotation.annotationType()).isValid(annotation)) {
					annotations[i] = null;
				}
				else {
					allIgnored = false;
				}
			}
			annotations = (allIgnored ? NO_ANNOTATIONS : annotations);
			if (source instanceof Class || source instanceof Member) {
				declaredAnnotationCache.put(source, annotations);
				cached = true;
			}
		}
	}
	if (!defensive || annotations.length == 0 || !cached) {
		return annotations;
	}
	return annotations.clone();
}

declaredAnnotationCache是一个map集合

private static final Map<AnnotatedElement, Annotation[]> declaredAnnotationCache =
			new ConcurrentReferenceHashMap<>(256);

接着看

private static boolean isIgnorable(Class<?> annotationType) {
	return AnnotationFilter.PLAIN.matches(annotationType);
}

是false

!AttributeMethods.forAnnotationType(annotation.annotationType()).isValid(annotation)

看这一句。
标记之,下次接着看。【AttributeMethods】的【forAnnotationType】方法,248行。


遗留:【Binder】【logback日志】【加载properties或者yml】【解析环境变量key】【PathMatchingResourcePatternResolver】【AbstractBeanFactory】的【getBean(String name, Class requiredType)】方法

现在看:【AnnotatedBeanDefinitionReader】的【register】方法,135行
参数【SpringbootRoamApplication】的class对象。

下次看:
【AttributeMethods】的【forAnnotationType】方法,248行。
参数是:注解的类型,比如【SpringBootApplication】的注解类型。

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页