目录
代码块1:register(Class... componentClasses)
代码块2:AnnotatedBeanDefinitionReader.register(Class... componentClasses)
代码块7 AnnotationConfigUtils.attributesFor
代码块8 AnnotatedTypeMetadata.getAnnotationAttributes()
代码块9 TypeMappedAnnotations.get()
代码块10 TypeMappedAnnotations.scan()
代码块11 AnnotationsScanner.scan()
代码块12 AnnotationsScanner.process()
代码块13 AnnotationsScanner.processClass()
代码块14 AnnotationsScanner.processClassInheritedAnnotations()
代码块15 AnnotationsScanner.getDeclaredAnnotations()
接上一篇,使用同样的测试用例
代码块1:register(Class<?>... componentClasses)
public void register(Class<?>... componentClasses) {
Assert.notEmpty(componentClasses, "At least one component class must be specified");
this.reader.register(componentClasses);
}
代码块2:AnnotatedBeanDefinitionReader.register(Class<?>... componentClasses)
public void register(Class<?>... componentClasses) {
//遍历配置类,将配置类封装成RootBeanDefinition注册进beanDefinitionMap
for (Class<?> componentClass : componentClasses) {//@Configuration标注的类,或者说是AnnotationConfigApplicationContext(componentClass)
registerBean(componentClass);
}
}
代码块3:registerBean
public void registerBean(Class<?> beanClass) {
doRegisterBean(beanClass, null, null, null, null);
}
代码块4:doRegisterBean
主要处理@Conditional注解,为beanDefinition设置实例化supplier、设置scope、设置公共注解@Lazy、@Primary、@DependsOn、@Role、@Decription的value()值,设置proxyMode,并将beanDefinition放入beanDefinitionMap和beanDefinitionNames中
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
@Nullable BeanDefinitionCustomizer[] customizers) {
// 类,注解元数据,在创建此bd的时候会创建StandardAnnotationMetadata,其中会指定PackagesAnnotationFilter
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
// 根据@Condition注解确定某项是否需要跳过,即确定这个注册是否需要跳过
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
// 指定创建bean实例的回调,用于
abd.setInstanceSupplier(supplier);
// private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
//
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());// scopeName默认值为单例,如果设置了则为设置的值
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// 为abd设置公共定义注解的value()值作为abd相应字段的值
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,这个holder比BeanDefintion多了beanName和alias西段
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 放入beanDefinitionMap中,放入beanDefinitionNames中
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
代码块5 shouldSkip
/**根据@Conditional注释确定是否应跳过某个项目
* 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) {
// 如果注解元数据为null 或者 没有@Conditional注解,则返回false
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;
}
代码块6 resolveScopeMetadata
AnnotationScopeMetadataResolver.resolveScopeMetadata()
// 解析scope元数据
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();// 创建一个scope元数据,默认的,单例,且不使用代理
if (definition instanceof AnnotatedBeanDefinition) {// 如果是AnnotatedBeanDefinition的实例
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;// 转化为AnnotatedBeanDefinition
// 解析注解属性
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
annDef.getMetadata(), this.scopeAnnotationType);// 从metadata中获取scope解决类型名称为key的注解属性
// 如果属性数组不为空
if (attributes != null) {
metadata.setScopeName(attributes.getString("value"));
ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
if (proxyMode == ScopedProxyMode.DEFAULT) {
proxyMode = this.defaultProxyMode;
}
metadata.setScopedProxyMode(proxyMode);
}
}
return metadata;
}
代码块7 AnnotationConfigUtils.attributesFor
/**
* 解析metadata上的annotationClass注解的属性
* @param metadata注解类型元数据,一般在beanDefinition中获取之后传参过来
* @param annotationClass要从注解类型元数据中获取到的注解类
* @return
*/
@Nullable// 从metadata上获取与annotationClass相匹配的属性数组
static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annotationClass) {
return attributesFor(metadata, annotationClass.getName());
}
/**
* 解析metadata上的annotationClassName注解
* @param metadata注解类型元数据
* @param annotationClassName要从注解类型元数据中获取到的注解类型名称
* @return
*/
@Nullable// 获取metadata上与annotationClassName相匹配的注解属性map中的注解属性数组
static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annotationClassName) {
return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClassName, false));
}
代码块8 AnnotatedTypeMetadata.getAnnotationAttributes()
// 获取注解属性
// 1. 从this.annotations中获取与annotationName相匹配的注解,如果不存在则反回null
// 2. 如果能匹配到,则获取注解上的属性
@Nullable
default Map<String, Object> getAnnotationAttributes(String annotationName,
boolean classValuesAsString) {
//
// getAnnotations获取到TypeMapedAnnotations,这个在初始化abd,设置其metadata属性时就会赋值
MergedAnnotation<Annotation> annotation = getAnnotations().get(annotationName,
null, MergedAnnotationSelectors.firstDirectlyDeclared());// 注解类型名称,不推测,第一个直接声明的注解
// 如果相匹配的注解不存在,则返回null,MergedAnnotation如果不为null,则默认值为true
if (!annotation.isPresent()) {
return null;
}
// 否则,获取注解上的属性
return annotation.asAnnotationAttributes(Adapt.values(classValuesAsString, true));
}
代码块9 TypeMappedAnnotations.get()
// 获取目标元素的annotationType注解对象
// 扫描this上的annotations,获取与annotationType相匹配的注解
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
// 通过注解过滤器来匹配注解类型,没有通过,则返回空
if (this.annotationFilter.matches(annotationType)) {
return MergedAnnotation.missing();// MissingMergedAnnotation
}
// 扫描目标元素(类、方法、属性)
// 注解类型名称、注解处理器,在TypeMappedAnnotations(this对象)中扫描annotationType注解
MergedAnnotation<A> result = scan(annotationType,
new MergedAnnotationFinder<>(annotationType, predicate, selector));
return (result != null ? result : MergedAnnotation.missing());
}
代码块10 TypeMappedAnnotations.scan()
/**
* 扫描并处理this.element上的注解,看是否由于criteria相匹配的
* @param criteria 例如Scope注解名称
* @param processor 注解处理器
* @param <C>
* @param <R>
* @return
*/
@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);
}// 注解所在类element是在创建beanDefinition的时候赋值的,此时也为bd赋值了TypeMappedAnnotations属性
// 如果注解所在类不为空,且查询策略不为空,则使用注解扫描器,扫描注解名称在所在类上,使用this.查询策略,通过AnnotationProcessor进行扫描
if (this.element != null && this.searchStrategy != null) {
return AnnotationsScanner.scan(criteria, this.element, this.searchStrategy, processor);// this.element指注解所在类
}
return null;
}
代码块11 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 比如Scope
* @param source the source element to scan要扫描的源元素 比如com.mx.JavaConfig类
* @param searchStrategy the search strategy to use 比如INHERITED_ANNOTATIONS
* @param processor the processor that receives the annotations接收注释的处理器 比如MergedAnnotationFinder
* @return the result of {@link AnnotationsProcessor#finish(Object)}
*/
@Nullable// 扫描source的层次结构,并使用processor处理注解,看是否有与context相匹配的
static <C, R> R scan(C context, AnnotatedElement source, SearchStrategy searchStrategy,
AnnotationsProcessor<C, R> processor) {
// 实际扫描处理,使用注解处理器,在源上扫描注解context
R result = process(context, source, searchStrategy, processor);
return processor.finish(result);
}
代码块12 AnnotationsScanner.process()
// 实际扫描处理,根据strategy选择匹配方法,使用processor对source进行匹配,看是否有与context相匹配的注解
// 区分按类进行匹配处理,还是按照方法进行匹配处理,还是普通处理
@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);
}
代码块13 AnnotationsScanner.processClass()
/**
* 查找注解,使用processor在source上的注解进行匹配,看是否有与context相匹配的注解
* 匹配规则为:
* 注解过滤器不能匹配到真是的注解类型 && (需要匹配的注解类型为null 或 真实注解类型=需要匹配的注解类型 或 真实注解类型的名称=需要匹配的注解类型)
* @param context 注解名
* @param source 源:可能是类也可能是方法
* @param searchStrategy 查找策略
* @param processor 注解处理器
* @param <C>
* @param <R>
* @return
*/
@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:// 搜索四针与标记为@Inherited父类的注解
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:// 搜索自身、父类、接口、getEnclosingClass()的注解
return processClassHierarchy(context, source, processor, true, true);
}
throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
}
代码块14 AnnotationsScanner.processClassInheritedAnnotations()
// 搜索自身与标记为@Inherited父类的注解:看这些注解中是否有与context类型的注解相匹配的注解
@Nullable
private static <C, R> R processClassInheritedAnnotations(C context, Class<?> source,
SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
try {// 判断是否没有继承关系,即没有父类、接口、getEnclosingClass()的注解按照普通注解吹
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;
}
代码块15 AnnotationsScanner.processElement(C context, AnnotatedElement source, AnnotationsProcessor<C, R> processor)
// 处理元素,按照普通注解处理:获取sorce上声明的注解,使用处理器查找是否有与context类型的注解匹配的注解
@Nullable
private static <C, R> R processElement(C context, AnnotatedElement source,
AnnotationsProcessor<C, R> processor) {
try {
// 聚合处理,如果有了,直接返回(默认未实现)
// 否则,调用getDeclaredAnnotations获取注解来处理
// 处理第0个合成注解,因为处理器在创建的时候没有给处理器的result属性赋值,因此这里的result可能会返回null
R result = processor.doWithAggregate(context, 0);
// 如果注解处理器中得result属性不为null,则返回results的值,柔则,使用注解处理器处理注解
return (result != null ? result : processor.doWithAnnotations(// 如果合成注解为null,则调用注解处理器处理注解,参数为注解、合成注解索引、源、源上声明的注解(包含注解:注解方法的缓存)
context, 0, source, getDeclaredAnnotations(source, false)));// getDeclaredAnnotations是从source中使用反射获取注解
}
catch (Throwable ex) {
AnnotationUtils.handleIntrospectionFailure(source, ex);
}
return null;
}
代码块15 AnnotationsScanner.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;// 初始化allIgnored为true
for (int i = 0; i < annotations.length; i++) {
Annotation annotation = annotations[i];
if (isIgnorable(annotation.annotationType()) ||// 注解类型不匹配即不匹配spring或java.lang包下的注解
// || 获取注解类型中的属性方法在注解上不可安全访问
!AttributeMethods.forAnnotationType(annotation.annotationType()).isValid(annotation)) {
annotations[i] = null;// 则将此属性或元注解设置为null
}
else {
allIgnored = false;
}
}
// 如果所有的注解都不可用,则设置为{}否则返回可用的注解
annotations = (allIgnored ? NO_ANNOTATIONS : annotations);
if (source instanceof Class || source instanceof Member) {// 如果源是类实例,或者是Member实例
declaredAnnotationCache.put(source, annotations);// 将源和注解数组放入缓存
cached = true;
}
}
}
if (!defensive || annotations.length == 0 || !cached) {// 如果不defensive || 注解的长度为0 || 没有缓存
return annotations;// 缓存注解数组
}
return annotations.clone();// 如果缓存了,且有缓存,且可以获取注解,则返回注解数组的克隆
}