Spring 源码解析四:Bean 的结构装载、属性值解析、注解扫描
上一篇次要介绍了 Bean 的注册、解析、实例化,但留下一些点待解析:
ConstructorResolver.autowireConstructor
如何进行结构装载并实例化的CglibSubclassingInstantiationStrategy.instantiate
如何动静实例化 bean 的BeanDefinitionValueResolver.resolveValueIfNecessary
如何解析属性值的MergedAnnotations.from
如何扫描注解的
这一节,就来解析这几个点
1. ConstructorResolver.autowireConstructor
ConstructorResolver
的次要性能是在结构时载入依赖的 bean 和用 factory-method 实例化 bean,这里只讲第一个:在结构时载入依赖的 bean ConstructorResolver.autowireConstructor
class ConstructorResolver {
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
// 实例化一个封装对象
BeanWrapperImpl bw = new BeanWrapperImpl();
// 须要应用的构造方法
Constructor<?> constructorToUse = null;
// 须要应用的结构参数
Object[] argsToUse = null;
// 如果指定了参数,就应用指定的参数
if (explicitArgs != null) {argsToUse = explicitArgs;}
else {Object[] argsToResolve = null;
// 并发解决
synchronized (mbd.constructorArgumentLock) {
// 获取定义中已解析的构造方法
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
// 获取定义中已解析的参数,首先是 resolvedConstructorArguments,其次是 preparedConstructorArguments
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null) {argsToResolve = mbd.preparedConstructorArguments;}
}
}
if (argsToResolve != null) {
// 把参数解析成理论要用的数据,如 bean 拆卸、属性载入
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
}
}
// 如果没有指定的构造方法或参数
if (constructorToUse == null || argsToUse == null) {Constructor<?>[] candidates = chosenCtors;
if (candidates == null) {
// 如果传入的 chosenCtors 是空,则获取 beanClass 的构造方法
Class<?> beanClass = mbd.getBeanClass();
try {candidates = (mbd.isNonPublicAccessAllowed() ?
beanClass.getDeclaredConstructors() : beanClass.getConstructors());
}
catch (Throwable ex) {// ... 代码省略}
}
// 如果只有一个构造方法,并且没有指定 explicitArgs 和 constructorArgumentValues
if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {Constructor<?> uniqueCandidate = candidates[0];
// 如果构造方法没有参数须要拆卸,间接实例化返回
if (uniqueCandidate.getParameterCount() == 0) {synchronized (mbd.constructorArgumentLock) {
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
mbd.constructorArgumentsResolved = true;
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
// 实例化 bean
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
return bw;
}
}
// 有构造方法,且结构模式为 AUTOWIRE_CONSTRUCTOR,则须要主动拆卸 bean
boolean autowiring = (chosenCtors != null ||
mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
ConstructorArgumentValues resolvedValues = null;
// ... 代码省略
// 抉择一个参数数量、参数类型、参数程序与须要实例化参数对象最靠近的一个构造方法
// 这里的计算比较复杂,有趣味的敌人能够自行摸索一下
for (Constructor<?> candidate : candidates) {// ... 代码省略}
// ... 代码省略
}
// 实例化 bean
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}
// 实例化 bean,默认应用 CglibSubclassingInstantiationStrategy.instantiate 来实例化
private Object instantiate(String beanName, RootBeanDefinition mbd, Constructor<?> constructorToUse, Object[] argsToUse) {
try {InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
if (System.getSecurityManager() != null) {return AccessController.doPrivileged((PrivilegedAction<Object>) () ->
strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse),
this.beanFactory.getAccessControlContext());
}
else {return strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
}
}
catch (Throwable ex) {// ... 代码省略}
}
}
最终的实例化依然须要 CglibSubclassingInstantiationStrategy.instantiate
来实现
2. CglibSubclassingInstantiationStrategy.instantiate
CglibSubclassingInstantiationStrategy
的次要性能是应用 cglib 的形式实例化 bean
public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {}
咱们先来看看 SimpleInstantiationStrategy
public class SimpleInstantiationStrategy implements InstantiationStrategy {
// 用于调用 factory-method
private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<>();
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 没有办法须要重载
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
// 首先获取已解析的构造方法
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
// 没有已解析的构造方法,则用 beanClass 获取
final Class<?> clazz = bd.getBeanClass();
// 接口不能实例化
if (clazz.isInterface()) {throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged((PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
// 通过 Class 获取构造方法
constructorToUse = clazz.getDeclaredConstructor();}
// 设为已解析的构造方法
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {// 如果 Class 没有构造方法,报错}
}
}
// 调用 Constructor..newInstance 实例化
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// 有办法须要重载,则须要用 cglib 生成一个新的子类
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
// 办法注入实例化,留给子类实现
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
final Constructor<?> ctor, Object... args) {
// 没有办法须要重载
if (!bd.hasMethodOverrides()) {
// ... 代码省略
// 调用 Constructor.newInstance 实例化
return BeanUtils.instantiateClass(ctor, args);
}
else {
// 有办法须要重载,则须要用 cglib 生成一个新的子类
return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
}
}
// 办法注入实例化,留给子类实现
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName,
BeanFactory owner, @Nullable Constructor<?> ctor, Object... args) {throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
// 通过 factory-method 初始化
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Object factoryBean, final Method factoryMethod, Object... args) {
try {
// ... 代码省略
// 间接调用 Method.invoke 实例化
Object result = factoryMethod.invoke(factoryBean, args);
// 如果为 null,实例化一个 NullBean
if (result == null) {result = new NullBean();
}
return result;
}
catch (IllegalArgumentException ex) {// ... 代码省略}
catch (IllegalAccessException ex) {// ... 代码省略}
catch (InvocationTargetException ex) {// ... 代码省略}
}
}
咱们先来看看 CglibSubclassingInstantiationStrategy
public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {return instantiateWithMethodInjection(bd, beanName, owner, null);
}
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Constructor<?> ctor, Object... args) {
// 生成一个 CglibSubclassCreator 来实例化
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
}
}
CglibSubclassCreator
是 CglibSubclassingInstantiationStrategy
的外部类
private static class CglibSubclassCreator {
// 实例化一个构造函数
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
// 应用 cglib Enhancer 创立一个增强子类
Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
Object instance;
if (ctor == null) {
// 如果没有指定构造函数,调用 Constructor.newInstance 实例化
instance = BeanUtils.instantiateClass(subclass);
}
else {
try {
// 获取与 ctor 参数匹配的子类构造函数,再调用 Constructor.newInstance 实例化
Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
instance = enhancedSubclassConstructor.newInstance(args);
}
catch (Exception ex) {// ... 代码省略}
}
// ... 代码省略
return instance;
}
// 应用 cglib Enhancer 创立一个增强子类
private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(beanDefinition.getBeanClass());
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
if (this.owner instanceof ConfigurableBeanFactory) {ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
}
enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
enhancer.setCallbackTypes(CALLBACK_TYPES);
return enhancer.createClass();}
}
3. BeanDefinitionValueResolver.resolveValueIfNecessary
BeanDefinitionValueResolver
的次要性能是将配置的属性值装载到 bean 中
class BeanDefinitionValueResolver {public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
// 在运行时对其余 bean 的援用
if (value instanceof RuntimeBeanReference) {RuntimeBeanReference ref = (RuntimeBeanReference) value;
// 解析援用 bean
return resolveReference(argName, ref);
}
// 在运行时对其余 bean name 的援用
else if (value instanceof RuntimeBeanNameReference) {String refName = ((RuntimeBeanNameReference) value).getBeanName();
// 应用 doEvaluate 解析 bean 名字,执行 SpEL 表达式
refName = String.valueOf(doEvaluate(refName));
if (!this.beanFactory.containsBean(refName)) {// 没注册过 bean name,报错}
return refName;
}
// 蕴含别名的 bean 定义
else if (value instanceof BeanDefinitionHolder) {BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
// 解析外部 bean
return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
// bean 定义
else if (value instanceof BeanDefinition) {BeanDefinition bd = (BeanDefinition) value;
// 外部 bean 名字
String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
ObjectUtils.getIdentityHexString(bd);
// 解析外部 bean
return resolveInnerBean(argName, innerBeanName, bd);
}
// 注入依赖形容(类、办法、属性)
else if (value instanceof DependencyDescriptor) {Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
// 解析依赖
Object result = this.beanFactory.resolveDependency((DependencyDescriptor) value, this.beanName, autowiredBeanNames, this.typeConverter);
for (String autowiredBeanName : autowiredBeanNames) {if (this.beanFactory.containsBean(autowiredBeanName)) {
// 注册依赖
this.beanFactory.registerDependentBean(autowiredBeanName, this.beanName);
}
}
return result;
}
// ... 代码省略
// 是字符类型的值
else if (value instanceof TypedStringValue) {TypedStringValue typedStringValue = (TypedStringValue) value;
// 应用 evaluate 解析 bean 名字,执行 SpEL 表达式
Object valueObject = evaluate(typedStringValue);
try {
// 解析类型
Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
// 如果有类型,把 valueObject 转换成这个类型
if (resolvedTargetType != null) {return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
}
// 没有指定类型,则返回本来的
else {return valueObject;}
}
catch (Throwable ex) {// ... 代码省略}
}
// 如果是 NullBean,返回 null
else if (value instanceof NullBean) {return null;}
// 默认当成 SpEL 表达式解析了
else {return evaluate(value);
}
}
}
BeanDefinitionValueResolver.resolveReference
解析援用 bean
class BeanDefinitionValueResolver {private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
Object bean;
// 获取 bean 类型
Class<?> beanType = ref.getBeanType();
if (ref.isToParent()) {
// 指明从父 BeanFactory 中获取
BeanFactory parent = this.beanFactory.getParentBeanFactory();
if (beanType != null) {
// 如果有 beanType,间接通过类型获取 bean
bean = parent.getBean(beanType);
}
else {
// 应用 doEvaluate 解析 bean 名字,执行 SpEL 表达式,而后依据名字查找 bean
bean = parent.getBean(String.valueOf(doEvaluate(ref.getBeanName())));
}
}
else {
String resolvedName;
if (beanType != null) {
// 如果有 beanType,间接通过类型获取 bean
NamedBeanHolder<?> namedBean = this.beanFactory.resolveNamedBean(beanType);
bean = namedBean.getBeanInstance();
resolvedName = namedBean.getBeanName();}
else {
// 应用 doEvaluate 解析 bean 名字,执行 SpEL 表达式,而后依据名字查找 bean
resolvedName = String.valueOf(doEvaluate(ref.getBeanName()));
bean = this.beanFactory.getBean(resolvedName);
}
// 注册依赖
this.beanFactory.registerDependentBean(resolvedName, this.beanName);
}
// 如果是 NullBean,返回 null
if (bean instanceof NullBean) {bean = null;}
return bean;
}
catch (BeansException ex) {// ... 代码省略}
}
// 调用 beanFactory 来解析 bean 名字,执行 SpEL 表达式
private Object doEvaluate(String value) {return this.beanFactory.evaluateBeanDefinitionString(value, this.beanDefinition);
}
}
BeanDefinitionValueResolver.resolveInnerBean
解析外部 bean
class BeanDefinitionValueResolver {private Object resolveInnerBean(Object argName, String innerBeanName, BeanDefinition innerBd) {
RootBeanDefinition mbd = null;
try {
// 获取合并父 bean 定义的 bean 定义
mbd = this.beanFactory.getMergedBeanDefinition(innerBeanName, innerBd, this.beanDefinition);
String actualInnerBeanName = innerBeanName;
if (mbd.isSingleton()) {
// 如果同类型的 bean 被实例化屡次,则应用后缀 #1,#2... 来命名之后的 bean
actualInnerBeanName = adaptInnerBeanName(innerBeanName);
}
// 把新生成的名字注册到 beanFactory
this.beanFactory.registerContainedBean(actualInnerBeanName, this.beanName);
// 获取依赖
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {for (String dependsOnBean : dependsOn) {
// 注册依赖
this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName);
// 确保加载
this.beanFactory.getBean(dependsOnBean);
}
}
// 创立 bean
Object innerBean = this.beanFactory.createBean(actualInnerBeanName, mbd, null);
// 如果 bean 实例是 FactoryBean,则调用 factory-method 获取真正的 bean
if (innerBean instanceof FactoryBean) {boolean synthetic = mbd.isSynthetic();
innerBean = this.beanFactory.getObjectFromFactoryBean((FactoryBean<?>) innerBean, actualInnerBeanName, !synthetic);
}
// 如果是 NullBean,返回 null
if (innerBean instanceof NullBean) {innerBean = null;}
return innerBean;
}
catch (BeansException ex) {// ... 代码省略}
}
// 如果同类型的 bean 被实例化屡次,则应用后缀 #1,#2... 来命名之后的 bean
private String adaptInnerBeanName(String innerBeanName) {
String actualInnerBeanName = innerBeanName;
int counter = 0;
String prefix = innerBeanName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR;
while (this.beanFactory.isBeanNameInUse(actualInnerBeanName)) {
counter++;
actualInnerBeanName = prefix + counter;
}
return actualInnerBeanName;
}
}
4. MergedAnnotations.from
MergedAnnotations.from
的底层实现其实是 TypeMappedAnnotations.from
TypeMappedAnnotations
的次要性能就是搜寻、操作注解
final class TypeMappedAnnotations implements MergedAnnotations {
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
// 没有可用的注解,间接返回 NONE
if (AnnotationsScanner.isKnownEmpty(element, searchStrategy)) {return NONE;}
return new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter);
}
static MergedAnnotations from(@Nullable Object source, Annotation[] annotations,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
// 没有要查找的注解,间接返回 NONE
if (annotations.length == 0) {return NONE;}
return new TypeMappedAnnotations(source, annotations, repeatableContainers, annotationFilter);
}
}
final class TypeMappedAnnotations implements MergedAnnotations {
// 查看是否有 annotationType
@Override
public <A extends Annotation> boolean isPresent(Class<A> annotationType) {
// 过滤器没通过,返回 false
if (this.annotationFilter.matches(annotationType)) {return false;}
// 扫描指标元素(类、办法、属性)
return Boolean.TRUE.equals(scan(annotationType,
IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
}
// 查看是否有 annotationType
@Override
public boolean isPresent(String annotationType) {
// 过滤器没通过,返回 false
if (this.annotationFilter.matches(annotationType)) {return false;}
// 扫描指标元素(类、办法、属性)
return Boolean.TRUE.equals(scan(annotationType,
IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
}
// 获取指标元素的 annotationType 注解对象
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
// 过滤器没通过,返回空
if (this.annotationFilter.matches(annotationType)) {return MergedAnnotation.missing();
}
// 扫描指标元素(类、办法、属性)
MergedAnnotation<A> result = scan(annotationType,
new MergedAnnotationFinder<>(annotationType, predicate, selector));
return (result != null ? result : MergedAnnotation.missing());
}
// 获取指标元素的 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();
}
// 扫描指标元素(类、办法、属性)
MergedAnnotation<A> result = scan(annotationType,
new MergedAnnotationFinder<>(annotationType, predicate, selector));
return (result != null ? result : MergedAnnotation.missing());
}
// 扫描指标元素(类、办法、属性)
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;
}
}
TypeMappedAnnotations.scan
的底层实现是 AnnotationsScanner.scan
abstract class AnnotationsScanner {
// 扫描注解
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);
}
// 理论扫描解决
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);
}
}
4.1. 按类解决
abstract class AnnotationsScanner {
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);
// 搜寻本身与标记为 @Inherited 父类的注解
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);
// 搜寻本身、父类、接口、getEnclosingClass()的注解
case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
return processClassHierarchy(context, source, processor, true, true);
}
throw new IllegalStateException("Unsupported search strategy" + searchStrategy);
}
// 搜寻本身与标记为 @Inherited 父类的注解
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;
// source 对象还能够持续向父类上溯
// 非 Object,非 Ordered,非 "java." 结尾
while (source != null && source != Object.class && remaining > 0 &&
!hasPlainJavaAnnotationsOnly(source)) {
// 聚合解决,如果有了,间接返回(默认未实现)R result = processor.doWithAggregate(context, aggregateIndex);
if (result != null) {return result;}
// 获取所有 public 的注解
Annotation[] declaredAnnotations = getDeclaredAnnotations(source, true);
// ... 代码省略
// 处理器自定义解决
result = processor.doWithAnnotations(context, aggregateIndex, source, declaredAnnotations);
// 如果有了,返回
if (result != null) {return result;}
// 上溯父类,持续扫描
source = source.getSuperclass();
aggregateIndex++;
}
}
catch (Throwable ex) {// ... 代码省略}
return null;
}
// 搜寻本身、父类、接口、getEnclosingClass()的注解
private static <C, R> R processClassHierarchy(C context, int[] aggregateIndex, Class<?> source,
AnnotationsProcessor<C, R> processor, boolean includeInterfaces, boolean includeEnclosing) {
try {
// 聚合解决,如果有了,间接返回(默认未实现)R result = processor.doWithAggregate(context, aggregateIndex[0]);
if (result != null) {return result;}
// 如果是 Ordered 或 "java." 结尾,返回
if (hasPlainJavaAnnotationsOnly(source)) {return null;}
// 获取所有 public 的注解
Annotation[] annotations = getDeclaredAnnotations(source, false);
// 处理器自定义解决
result = processor.doWithAnnotations(context, aggregateIndex[0], source, annotations);
// 如果有了,返回
if (result != null) {return result;}
aggregateIndex[0]++;
// 如果包含接口,持续搜寻接口的
if (includeInterfaces) {for (Class<?> interfaceType : source.getInterfaces()) {
R interfacesResult = processClassHierarchy(context, aggregateIndex,
interfaceType, processor, true, includeEnclosing);
if (interfacesResult != null) {return interfacesResult;}
}
}
// 如果有父类,持续搜寻父类的
Class<?> superclass = source.getSuperclass();
if (superclass != Object.class && superclass != null) {
R superclassResult = processClassHierarchy(context, aggregateIndex,
superclass, processor, includeInterfaces, includeEnclosing);
if (superclassResult != null) {return superclassResult;}
}
// 如果包含 getEnclosingClass(),持续搜寻 getEnclosingClass()的
if (includeEnclosing) {
try {Class<?> enclosingClass = source.getEnclosingClass();
if (enclosingClass != null) {
R enclosingResult = processClassHierarchy(context, aggregateIndex,
enclosingClass, processor, includeInterfaces, true);
if (enclosingResult != null) {return enclosingResult;}
}
}
catch (Throwable ex) {// ... 代码省略}
}
}
catch (Throwable ex) {// ... 代码省略}
return null;
}
}
4.2. 按办法解决
abstract class AnnotationsScanner {
private static <C, R> R processMethod(C context, Method source,
SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {switch (searchStrategy) {
// 只搜寻本身的注解
case DIRECT:
// 搜寻本身与标记为 @Inherited 父类的注解
case INHERITED_ANNOTATIONS:
return processMethodInheritedAnnotations(context, source, processor);
// 搜寻本身与父类的注解
case SUPERCLASS:
return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
processor, source, false);
// 搜寻本身、父类、接口的注解
case TYPE_HIERARCHY:
// 搜寻本身、父类、接口、getEnclosingClass()的注解
case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
processor, source, true);
}
throw new IllegalStateException("Unsupported search strategy" + searchStrategy);
}
// 搜寻本身与标记为 @Inherited 父类的注解
private static <C, R> R processMethodInheritedAnnotations(C context, Method source,
AnnotationsProcessor<C, R> processor) {
try {
// 聚合解决,如果有了,间接返回(默认未实现)// 不然,用 processMethodAnnotations 解决
R result = processor.doWithAggregate(context, 0);
return (result != null ? result :
processMethodAnnotations(context, 0, source, processor));
}
catch (Throwable ex) {// ... 代码省略}
return null;
}
// 解决办法的注解
private static <C, R> R processMethodAnnotations(C context, int aggregateIndex, Method source,
AnnotationsProcessor<C, R> processor) {
// 获取所有 public 的注解
Annotation[] annotations = getDeclaredAnnotations(source, false);
// 处理器自定义解决
R result = processor.doWithAnnotations(context, aggregateIndex, source, annotations);
// 如果有了,返回
if (result != null) {return result;}
// ... 代码省略,桥接办法的解决
return null;
}
// 搜寻本身、父类、接口、getEnclosingClass()的注解
private static <C, R> R processMethodHierarchy(C context, int[] aggregateIndex,
Class<?> sourceClass, AnnotationsProcessor<C, R> processor, Method rootMethod,
boolean includeInterfaces) {
try {
// 聚合解决,如果有了,间接返回(默认未实现)R result = processor.doWithAggregate(context, aggregateIndex[0]);
if (result != null) {return result;}
// 如果是 Ordered 或 "java." 结尾,返回
if (hasPlainJavaAnnotationsOnly(sourceClass)) {return null;}
boolean calledProcessor = false;
// 如果 rootMethod 是 sourceClass 的,间接解决
if (sourceClass == rootMethod.getDeclaringClass()) {result = processMethodAnnotations(context, aggregateIndex[0],
rootMethod, processor);
calledProcessor = true;
if (result != null) {return result;}
}
else {
// 获取 sourceClass 的 public 办法
for (Method candidateMethod : getBaseTypeMethods(context, sourceClass)) {
// 如果办法不是 private,并且参数与 rootMethod 始终,间接解决
if (candidateMethod != null && isOverride(rootMethod, candidateMethod)) {result = processMethodAnnotations(context, aggregateIndex[0],
candidateMethod, processor);
calledProcessor = true;
if (result != null) {return result;}
}
}
}
// 如果 rootMethod 是 private,返回 null
if (Modifier.isPrivate(rootMethod.getModifiers())) {return null;}
// 如果包含接口,持续搜寻接口的
if (includeInterfaces) {for (Class<?> interfaceType : sourceClass.getInterfaces()) {
R interfacesResult = processMethodHierarchy(context, aggregateIndex,
interfaceType, processor, rootMethod, true);
if (interfacesResult != null) {return interfacesResult;}
}
}
// 如果有父类,持续搜寻父类的
Class<?> superclass = sourceClass.getSuperclass();
if (superclass != Object.class && superclass != null) {
R superclassResult = processMethodHierarchy(context, aggregateIndex,
superclass, processor, rootMethod, includeInterfaces);
if (superclassResult != null) {return superclassResult;}
}
}
catch (Throwable ex) {// ... 代码省略}
return null;
}
}
4.3 按一般解决
abstract class AnnotationsScanner {
private static <C, R> R processElement(C context, AnnotatedElement source,
AnnotationsProcessor<C, R> processor) {
try {
// 聚合解决,如果有了,间接返回(默认未实现)// 不然,调用 getDeclaredAnnotations 获取注解来解决
R result = processor.doWithAggregate(context, 0);
return (result != null ? result : processor.doWithAnnotations(context, 0, source, getDeclaredAnnotations(source, false)));
}
catch (Throwable ex) {// ... 代码省略}
return null;
}
}
后续
更多博客,查看 https://github.com/senntyou/blogs
作者:深予之 (@senntyou)
版权申明:自在转载 - 非商用 - 非衍生 - 放弃署名(创意共享 3.0 许可证)