调查下面代码片段里的metadata里的initMethods是怎么被赋值的?
![](https://img.haomeiwen.com/i11732982/ae4c30cce2f26440.png)
上图01里的metadata里的initMethods列表属性里第一个元素的method是属性是
public void org.dhframework.Test4.pc1()
metadata这个属性的值是通过
private LifecycleMetadata findLifecycleMetadata(Class<?> clazz){ ... }
方法获取的,该方法如下图02findLifecycleMetadata
方法里有2个分支,都会走进buildLifecycleMetadata(clazz)
方法里,那么来看private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) { ... }
方法还是下图02,initMethods其实就是将currInitMethods加入进来。那么只要看currInitMethods。currInitMethods是通过210行add(element)填充的,这里是个lamda表达式,需要先看看207行的调用是如何执行的。转到图03位置
![](https://img.haomeiwen.com/i11732982/b4623ef981faeed3.png)
接上文,先看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集合。
![](https://img.haomeiwen.com/i11732982/23d6ccb03c69101b.png)
那么重点来了,如何判断呢?
首先,
this.initAnnotationType != null
一目了然其次,
method.isAnnotationPresent(this.initAnnotationType)
是jdk代码,我目测了一段时间,觉得是判断当前方法的注释是否与参数里的注释一样。从下面图04可以看到,
method.declaredAnnotations
集合里有PostConstruct注解this.initAnnotationType=interface javax.annotation.PostConstruct
这样,上面的if判断就是ture了,所以currInitMethods集合里就会增加被@PostConstruct注解的pc1()方法。
![](https://img.haomeiwen.com/i11732982/f1b1cac65c4f8496.png)
接下来的问题是this.initAnnotationType=interface javax.annotation.PostConstruct
initAnnotationType
的值为何是PostConstruct
。
这个问题,请看spring(碎片002), @PostConstruct,为什么是PostConstruct
。谢谢阅读
网友评论