@PostConstruct
initializeBean方法–> PostProcessor.postProcessBeforeInitialization–> InitDestroyAnnotationBeanPostProcessor.postProcessBeforeDestruction
被@PostConstruct注解的方法会在Bean初始化的时候被调用,如下图:
继承关系如下图:
所以到bean初始化时,会调用到InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization方法。
- InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization–>findLifecycleMetadata->buildLifecycleMetadata
- 通过method.isAnnotationPresent(this.initAnnotationType)判断是否有@PostConstruct,将其方法放入initMethods
private InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata buildLifecycleMetadata(Class<?> clazz) {
if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(this.initAnnotationType, this.destroyAnnotationType))) {
return this.emptyLifecycleMetadata;
} else {
List<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> initMethods = new ArrayList();
List<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> destroyMethods = new ArrayList();
Class targetClass = clazz;
do {
List<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> currInitMethods = new ArrayList();
List<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> currDestroyMethods = new ArrayList();
ReflectionUtils.doWithLocalMethods(targetClass, (method) -> {
if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
InitDestroyAnnotationBeanPostProcessor.LifecycleElement element = new InitDestroyAnnotationBeanPostProcessor.LifecycleElement(method);
currInitMethods.add(element);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
}
}
if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
currDestroyMethods.add(new InitDestroyAnnotationBeanPostProcessor.LifecycleElement(method));
if (this.logger.isTraceEnabled()) {
this.logger.trace("Found destroy method on class [" + clazz.getName() + "]: " + method);
}
}
});
initMethods.addAll(0, currInitMethods);
destroyMethods.addAll(currDestroyMethods);
targetClass = targetClass.getSuperclass();
} while(targetClass != null && targetClass != Object.class);
return initMethods.isEmpty() && destroyMethods.isEmpty() ? this.emptyLifecycleMetadata : new InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata(clazz, initMethods, destroyMethods);
}
}
- initAnnotationType在子类CommonAnnotationBeanPostProcessor的构造方法中被初始化
public CommonAnnotationBeanPostProcessor() {
this.setOrder(2147483644);
this.setInitAnnotationType(PostConstruct.class);
this.setDestroyAnnotationType(PreDestroy.class);
this.ignoreResourceType("javax.xml.ws.WebServiceContext");
if (jndiPresent) {
this.jndiFactory = new SimpleJndiBeanFactory();
}
}
- InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization–>metadata.invokeDestroyMethods(bean, beanName)。在该方法中会调用被@PostConstruct注解的方法,即第二步initMethods中的方法。