五 InitDestroyAnnotationBeanPostProcessor 类
1 属性
InitDestroyAnnotationBeanPostProcessor 类用于处理初始化与销毁注解;其中第一个属性为用于标识初始化方法与销毁方法注解类型的 initAnnotationType 与 destroyAnnotationType 属性、还有一个用于标识执行顺序的 order 属性,默认为最大值、用于缓存生命周期元数据的 lifecycleMetadataCache 及一个标识空生命周期元数据对象的 emptyLifecycleMetadata 属性;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private final transient LifecycleMetadata emptyLifecycleMetadata =
new LifecycleMetadata(Object.class, Collections.emptyList(), Collections.emptyList()) {
@Override
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
}
@Override
public void invokeInitMethods(Object target, String beanName) {
}
@Override
public void invokeDestroyMethods(Object target, String beanName) {
}
@Override
public boolean hasDestroyMethods() {
return false;
}
};
protected transient Log logger = LogFactory.getLog(getClass());
@Nullable
private Class<? extends Annotation> initAnnotationType;
@Nullable
private Class<? extends Annotation> destroyAnnotationType;
private int order = Ordered.LOWEST_PRECEDENCE;
@Nullable
private final transient Map<Class<?>, LifecycleMetadata> lifecycleMetadataCache = new ConcurrentHashMap<>(256);
public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
this.initAnnotationType = initAnnotationType;
}
public void setDestroyAnnotationType(Class<? extends Annotation> destroyAnnotationType) {
this.destroyAnnotationType = destroyAnnotationType;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
}
2 类方法
2.1 postProcessMergedBeanDefinition 方法
postProcessMergedBeanDefinition 方法在通过 findLifecycleMetadata 方法创建 LifecycleMetadata 对象后并使用 beanDefinition 执行其的 checkConfigMembers 方法向对象注册表中注册初始化与销毁方法;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
LifecycleMetadata metadata = findLifecycleMetadata(beanType);
metadata.checkConfigMembers(beanDefinition);
}
}
findLifecycleMetadata 方法在 lifecycleMetadataCache 缓存为 null 时直接执行 buildLifecycleMetadata 方法创建 LifecycleMetadata 对象并返回,否则首先尝试从该缓存中获取 clazz 对应的元数据,获取到时直接返回缓存对象,否则 buildLifecycleMetadata 方法创建 LifecycleMetadata 对象并保存到 lifecycleMetadataCache 缓存中同时返回;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
if (this.lifecycleMetadataCache == null) {
return buildLifecycleMetadata(clazz);
}
LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
if (metadata == null) {
synchronized (this.lifecycleMetadataCache) {
metadata = this.lifecycleMetadataCache.get(clazz);
if (metadata == null) {
metadata = buildLifecycleMetadata(clazz);
this.lifecycleMetadataCache.put(clazz, metadata);
}
return metadata;
}
}
return metadata;
}
}
buildLifecycleMetadata 方法在 clazz 参数没有使用 initAnnotationType 与 destroyAnnotationType 注解进行修饰时直接返回 emptyLifecycleMetadata 空生命周期元数据,然后寻找 clazz 参数及其所有父类中使用 initAnnotationType 与 destroyAnnotationType 注解修饰方法并使用 LifecycleElement 类对其进行封装,最后在查询完毕后,使用 clazz 、查询到的初始化方法与销毁方法封装对象数组创建 LifecycleMetadata 对象并返回;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(this.initAnnotationType, this.destroyAnnotationType))) {
return this.emptyLifecycleMetadata;
}
List<LifecycleElement> initMethods = new ArrayList<>();
List<LifecycleElement> destroyMethods = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final List<LifecycleElement> currInitMethods = new ArrayList<>();
final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
LifecycleElement element = new LifecycleElement(method);
currInitMethods.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
}
}
if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
currDestroyMethods.add(new LifecycleElement(method));
if (logger.isTraceEnabled()) {
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 LifecycleMetadata(clazz, initMethods, destroyMethods));
}
}
2.2 postProcessBeforeInitialization 方法
postProcessBeforeInitialization 方法首先通过 findLifecycleMetadata 查询 bean 参数对应的生命周期元数据并调用其 invokeInitMethods 方法执行初始化方法并在执行完成后返回 bean 参数;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
metadata.invokeInitMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
}
return bean;
}
}
2.3 postProcessAfterInitialization 方法
postProcessAfterInitialization 方法不执行任何逻辑直接返回 bean 参数;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
2.4 postProcessBeforeDestruction 方法
postProcessBeforeDestruction 方法首先通过 findLifecycleMetadata 查询 bean 参数对应的生命周期元数据并调用其 invokeDestroyMethods 方法执行销毁方法;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
metadata.invokeDestroyMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
String msg = "Destroy method on bean with name '" + beanName + "' threw an exception";
if (logger.isDebugEnabled()) {
logger.warn(msg, ex.getTargetException());
}
else {
logger.warn(msg + ": " + ex.getTargetException());
}
}
catch (Throwable ex) {
logger.warn("Failed to invoke destroy method on bean with name '" + beanName + "'", ex);
}
}
}
2.5 requiresDestruction 方法
requiresDestruction 方法获取 bean 参数对应的生命周期元数据并然后其使用拥有销毁方法;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
@Override
public boolean requiresDestruction(Object bean) {
return findLifecycleMetadata(bean.getClass()).hasDestroyMethods();
}
}
3 LifecycleElement 内部类
3.1 属性及构造方法
3.1.1 类属性
LifecycleElement 类用于封装方法对象,其拥有保存封装 Method 方法对象的 method 属性与方法名标识的 identifier 属性;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private static class LifecycleElement {
private final Method method;
private final String identifier;
public Method getMethod() {
return this.method;
}
public String getIdentifier() {
return this.identifier;
}
}
}
3.1.2 构造方法
LifecycleElement 类只有一个构造方法,其只有一个 Method 类型参数,在创建过程中首先对 method 参数的参数个数进行空验证,即不为空直接报错;验证通过后首先将 method 属性初始化为 method 参数值,随后在若 mothod 为私有方法时将 identifer 属性初始化为全限定类名 + 方法名,否则直接初始化为方法名;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private static class LifecycleElement {
public LifecycleElement(Method method) {
if (method.getParameterCount() != 0) {
throw new IllegalStateException("Lifecycle method annotation requires a no-arg method: " + method);
}
this.method = method;
this.identifier = (Modifier.isPrivate(method.getModifiers()) ?
ClassUtils.getQualifiedMethodName(method) : method.getName());
}
}
}
3.2 invoke 方法
invoke 方法直接执行 method 属性的 invoke 方法;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private static class LifecycleElement {
public void invoke(Object target) throws Throwable {
ReflectionUtils.makeAccessible(this.method);
this.method.invoke(target, (Object[]) null);
}
}
}
4 LifecycleMetadata 内部类
4.1 属性及构造方法
4.1.1 类属性
LifecycleMetadata 类用于封装类以向外提供对生命周期元数据的处理,其中 targerClass 属性保存的时封装的 Class 类型对象、initMethods 与 checkedInitMethods 属性分别保存所有初始化方法元数据封装集合与通过验证后的初始化方法元数据封装集合及保存所有销毁方法元数据封装集合与通过验证后的销毁方法元数据封装集合的 destroyMethods 与 checkedDestroyMethods 属性;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private class LifecycleMetadata {
private final Class<?> targetClass;
private final Collection<LifecycleElement> initMethods;
private final Collection<LifecycleElement> destroyMethods;
@Nullable
private volatile Set<LifecycleElement> checkedInitMethods;
@Nullable
private volatile Set<LifecycleElement> checkedDestroyMethods;
}
}
4.1.2 构造方法
LifecycleMetadata 类只有一个分别将 targetClass、initMethods 与 destroyMethods 属性初始化为对应的入参属性值;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private class LifecycleMetadata {
public LifecycleMetadata(Class<?> targetClass, Collection<LifecycleElement> initMethods,
Collection<LifecycleElement> destroyMethods) {
this.targetClass = targetClass;
this.initMethods = initMethods;
this.destroyMethods = destroyMethods;
}
}
}
4.2 类方法
4.2.1 checkConfigMembers 方法
checkConfigMembers 方法分别将 beanDefinition 中未注册 initMethods 与 destroyMethods 属性中的元素注册到该对象注册表并保存到 checkedInitMethods 与 checkedDestroyMethods 属性中;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private class LifecycleMetadata {
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set<LifecycleElement> checkedInitMethods = new LinkedHashSet<>(this.initMethods.size());
for (LifecycleElement element : this.initMethods) {
String methodIdentifier = element.getIdentifier();
if (!beanDefinition.isExternallyManagedInitMethod(methodIdentifier)) {
beanDefinition.registerExternallyManagedInitMethod(methodIdentifier);
checkedInitMethods.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Registered init method on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
Set<LifecycleElement> checkedDestroyMethods = new LinkedHashSet<>(this.destroyMethods.size());
for (LifecycleElement element : this.destroyMethods) {
String methodIdentifier = element.getIdentifier();
if (!beanDefinition.isExternallyManagedDestroyMethod(methodIdentifier)) {
beanDefinition.registerExternallyManagedDestroyMethod(methodIdentifier);
checkedDestroyMethods.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Registered destroy method on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
this.checkedInitMethods = checkedInitMethods;
this.checkedDestroyMethods = checkedDestroyMethods;
}
}
}
4.2.2 invokeInitMethods 方法
invokeInitMethods 方法在 checkedInitMethods 属性不为空依次执行所有元素,否则依次执行 initMethods 属性中的所有元素;
public class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
private class LifecycleMetadata {
public void invokeInitMethods(Object target, String beanName) throws Throwable {
Collection<LifecycleElement> checkedInitMethods = this.checkedInitMethods;
Collection<LifecycleElement> initMethodsToIterate =
(checkedInitMethods != null ? checkedInitMethods : this.initMethods);
if (!initMethodsToIterate.isEmpty()) {
for (LifecycleElement element : initMethodsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking init