美文网首页
spring(碎片001), @PostConstruct相关,

spring(碎片001), @PostConstruct相关,

作者: 黑铁大魔王 | 来源:发表于2020-08-04 14:59 被阅读0次

调查下面代码片段里的metadata里的initMethods是怎么被赋值的?

图01
上图01里的metadata里的initMethods列表属性里第一个元素的method是属性是
public void org.dhframework.Test4.pc1()
metadata这个属性的值是通过 private LifecycleMetadata findLifecycleMetadata(Class<?> clazz){ ... } 方法获取的,该方法如下图02
findLifecycleMetadata方法里有2个分支,都会走进buildLifecycleMetadata(clazz)方法里,那么来看private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) { ... }方法
还是下图02,initMethods其实就是将currInitMethods加入进来。那么只要看currInitMethods。currInitMethods是通过210行add(element)填充的,这里是个lamda表达式,需要先看看207行的调用是如何执行的。转到图03位置
图02

接上文,先看ReflectionUtils.doWithLocalMethods(targetClass, method -> { ... }方法调用,如图03,通过Method[] methods = getDeclaredMethods(clazz);拿到自定义方法,并且遍历做mc.doWith(method);
mc.doWith(method);就执行了lamda表达式里的内容,通过图02的208行判断if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType))
如果此处判断为true,就执行LifecycleElement element = new LifecycleElement(method); currInitMethods.add(element);将方法加入到currInitMethods集合。

图03
那么重点来了,如何判断呢?
首先,this.initAnnotationType != null一目了然
其次,method.isAnnotationPresent(this.initAnnotationType)是jdk代码,我目测了一段时间,觉得是判断当前方法的注释是否与参数里的注释一样。
从下面图04可以看到,method.declaredAnnotations集合里有PostConstruct注解
this.initAnnotationType=interface javax.annotation.PostConstruct
这样,上面的if判断就是ture了,所以currInitMethods集合里就会增加被@PostConstruct注解的pc1()方法。
图04

接下来的问题是this.initAnnotationType=interface javax.annotation.PostConstruct
initAnnotationType的值为何是PostConstruct
这个问题,请看spring(碎片002), @PostConstruct,为什么是PostConstruct
。谢谢阅读

相关文章

网友评论

      本文标题:spring(碎片001), @PostConstruct相关,

      本文链接:https://www.haomeiwen.com/subject/yshkrktx.html