调用起始位置
AbstractAutowireCapableBeanFactory#doCreateBean方法调用当前类下applyMergedBeanDefinitionPostProcessors方法
CommonAnnotationBeanPostProcessor类
添加PostConstruct和PreDestroy
实际是InitDestroyAnnotationBeanPostProcessor的方法
/**
* Specify the init annotation to check for, indicating initialization
* methods to call after configuration of a bean.
* <p>Any custom annotation can be used, since there are no required
* annotation attributes. There is no default, although a typical choice
* is the JSR-250 {@link javax.annotation.PostConstruct} annotation.
*/
public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
this.initAnnotationType = initAnnotationType;
}
/**
* Specify the destroy annotation to check for, indicating destruction
* methods to call when the context is shutting down.
* <p>Any custom annotation can be used, since there are no required
* annotation attributes. There is no default, although a typical choice
* is the JSR-250 {@link javax.annotation.PreDestroy} annotation.
*/
public void setDestroyAnnotationType(Class<? extends Annotation> destroyAnnotationType) {
this.destroyAnnotationType = destroyAnnotationType;
}
添加Resource
static方法赋值的属性字段在common类里
private static final Set<Class<? extends Annotation>> resourceAnnotationTypes = new LinkedHashSet<>(4);
调用CommonAnnotationBeanPostProcessor的postProcessMergedBeanDefinition
/**
* 构造生命周期元数据(解析带@PostConstruct和@PreDestroy注解的方法),当其构造完成后会将元数据缓存到lifecycleMetadataCache集合中并返回
* 此时就完成了相关方法(初始化方法和销毁方法)的扫描解析和缓存工作
*
* @param clazz
* @return
*/
private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(this.initAnnotationType, this.destroyAnnotationType))) {
return this.emptyLifecycleMetadata;
}
// 实例化后的回调方法(@PostConstruct)
List<LifecycleElement> initMethods = new ArrayList<>();
// 销毁前的回调方法(@PreDestroy)
List<LifecycleElement> destroyMethods = new ArrayList<>();
// 获取正在处理的目标类
Class<?> targetClass = clazz;
do {
// 保存每一轮循环搜索到的相关方法
final List<LifecycleElement> currInitMethods = new ArrayList<>();
final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
// 反射获取当前类中的所有方法并依次对其调用第二个参数的lambda表达式
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
// 当前方法的注解中包含initAnnotationType注解时(@PostConstruct)
if (this.initAnnotationType !=