diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java index 4b7dd8be5ab1..633c26dd5ac9 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java @@ -176,12 +176,12 @@ public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, C beanDefinition.resolveDestroyMethodIfNecessary(); LifecycleMetadata metadata = findLifecycleMetadata(beanDefinition, registeredBean.getBeanClass()); if (!CollectionUtils.isEmpty(metadata.initMethods)) { - String[] initMethodNames = safeMerge(beanDefinition.getInitMethodNames(), metadata.initMethods); - beanDefinition.setInitMethodNames(initMethodNames); + beanDefinition.setAotInitMethodNames(mergeMethodNames(beanDefinition.getAotInitMethodNames(), + metadata.initMethods)); } if (!CollectionUtils.isEmpty(metadata.destroyMethods)) { - String[] destroyMethodNames = safeMerge(beanDefinition.getDestroyMethodNames(), metadata.destroyMethods); - beanDefinition.setDestroyMethodNames(destroyMethodNames); + beanDefinition.setAotDestroyMethodNames(mergeMethodNames(beanDefinition.getAotDestroyMethodNames(), + metadata.destroyMethods)); } return null; } @@ -192,11 +192,9 @@ private LifecycleMetadata findLifecycleMetadata(RootBeanDefinition beanDefinitio return metadata; } - private static String[] safeMerge(String @Nullable [] existingNames, Collection detectedMethods) { - Stream detectedNames = detectedMethods.stream().map(LifecycleMethod::getIdentifier); - Stream mergedNames = (existingNames != null ? - Stream.concat(detectedNames, Stream.of(existingNames)) : detectedNames); - return mergedNames.distinct().toArray(String[]::new); + private static String[] mergeMethodNames(List existingNames, Collection detectedMethods) { + return Stream.concat(detectedMethods.stream().map(LifecycleMethod::getIdentifier), existingNames.stream()) + .toArray(String[]::new); } @Override diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGenerator.java b/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGenerator.java index d019e7eb5453..ccf877ab337f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGenerator.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGenerator.java @@ -124,10 +124,16 @@ CodeBlock generateCode(RootBeanDefinition beanDefinition) { "$L.setSynthetic($L)"); addStatementForValue(code, beanDefinition, BeanDefinition::getRole, this::hasRole, "$L.setRole($L)", this::toRole); + // For Publisher-based destroy methods + this.hints.reflection().registerType(TypeReference.of("org.reactivestreams.Publisher")); addInitDestroyMethods(code, beanDefinition, beanDefinition.getInitMethodNames(), "$L.setInitMethodNames($L)"); addInitDestroyMethods(code, beanDefinition, beanDefinition.getDestroyMethodNames(), "$L.setDestroyMethodNames($L)"); + addInitDestroyMethods(code, beanDefinition, beanDefinition.getAotInitMethodNames().toArray(String[]::new), + "$L.setAotInitMethodNames($L)"); + addInitDestroyMethods(code, beanDefinition, beanDefinition.getAotDestroyMethodNames().toArray(String[]::new), + "$L.setAotDestroyMethodNames($L)"); if (beanDefinition.getFactoryBeanName() != null) { addStatementForValue(code, beanDefinition, BeanDefinition::getFactoryBeanName, "$L.setFactoryBeanName(\"$L\")"); @@ -143,8 +149,6 @@ CodeBlock generateCode(RootBeanDefinition beanDefinition) { private void addInitDestroyMethods(Builder code, AbstractBeanDefinition beanDefinition, String @Nullable [] methodNames, String format) { - // For Publisher-based destroy methods - this.hints.reflection().registerType(TypeReference.of("org.reactivestreams.Publisher")); if (!ObjectUtils.isEmpty(methodNames)) { Class beanType = ClassUtils.getUserClass(beanDefinition.getResolvableType().toClass()); Arrays.stream(methodNames).forEach(methodName -> addInitDestroyHint(beanType, methodName)); diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index 940a8d697c18..a0d158ba9d5e 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -1857,27 +1857,54 @@ protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBea throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean); - if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) { - if (logger.isTraceEnabled()) { - logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); + boolean invokeInitializingBean = (isInitializingBean && + (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))); + if (mbd != null && bean.getClass() != NullBean.class) { + for (String initMethodName : mbd.getAotInitMethodNames()) { + if (invokeInitializingBean && "afterPropertiesSet".equals(initMethodName)) { + invokeAfterPropertiesSet(beanName, (InitializingBean) bean); + invokeInitializingBean = false; + } + else { + invokeCustomInitMethodIfNecessary(beanName, bean, mbd, initMethodName, isInitializingBean); + } } - ((InitializingBean) bean).afterPropertiesSet(); + } + if (invokeInitializingBean) { + invokeAfterPropertiesSet(beanName, (InitializingBean) bean); } if (mbd != null && bean.getClass() != NullBean.class) { + List annotatedNames = mbd.getAotInitMethodNames(); String[] initMethodNames = mbd.getInitMethodNames(); + if (!annotatedNames.isEmpty()) { + initMethodNames = RootBeanDefinition.mergeAotMethodNames(annotatedNames, initMethodNames); + } if (initMethodNames != null) { - for (String initMethodName : initMethodNames) { - if (StringUtils.hasLength(initMethodName) && - !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && - !mbd.hasAnyExternallyManagedInitMethod(initMethodName)) { - invokeCustomInitMethod(beanName, bean, mbd, initMethodName); - } + for (int index = annotatedNames.size(); index < initMethodNames.length; index++) { + invokeCustomInitMethodIfNecessary(beanName, bean, mbd, initMethodNames[index], isInitializingBean); } } } } + private void invokeAfterPropertiesSet(String beanName, InitializingBean bean) throws Exception { + if (logger.isTraceEnabled()) { + logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); + } + bean.afterPropertiesSet(); + } + + private void invokeCustomInitMethodIfNecessary(String beanName, Object bean, RootBeanDefinition mbd, + String initMethodName, boolean isInitializingBean) throws Throwable { + + if (StringUtils.hasLength(initMethodName) && + !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && + !mbd.hasAnyExternallyManagedInitMethod(initMethodName)) { + invokeCustomInitMethod(beanName, bean, mbd, initMethodName); + } + } + /** * Invoke the specified custom init method on the given bean. *

Called by {@link #invokeInitMethods(String, Object, RootBeanDefinition)}. diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java index 4f7319e0f16c..a684e28f378d 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java @@ -9,6 +9,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -77,6 +78,10 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { private final boolean invokeDisposableBean; + private final String @Nullable [] aotDestroyMethodNames; + + private transient @Nullable Method @Nullable [] aotDestroyMethods; + private boolean invokeAutoCloseable; private String @Nullable [] destroyMethodNames; @@ -101,44 +106,38 @@ public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition be this.bean = bean; this.beanName = beanName; this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed(); - this.invokeDisposableBean = (bean instanceof DisposableBean && + boolean disposableBean = (bean instanceof DisposableBean && !beanDefinition.hasAnyExternallyManagedDestroyMethod(DESTROY_METHOD_NAME)); - String[] destroyMethodNames = inferDestroyMethodsIfNecessary(bean.getClass(), beanDefinition); + List annotatedNames = beanDefinition.getAotDestroyMethodNames(); + this.invokeDisposableBean = disposableBean && !annotatedNames.contains(DESTROY_METHOD_NAME); + this.aotDestroyMethodNames = (annotatedNames.isEmpty() ? null : + annotatedNames.stream() + .filter(name -> !beanDefinition.isExternallyManagedDestroyMethod(name)) + .toArray(String[]::new)); + if (this.aotDestroyMethodNames != null) { + this.aotDestroyMethods = new Method[this.aotDestroyMethodNames.length]; + for (int i = 0; i < this.aotDestroyMethodNames.length; i++) { + String methodName = this.aotDestroyMethodNames[i]; + if (!isDisposableBeanMethod(methodName) && !isAutoCloseableMethod(methodName)) { + this.aotDestroyMethods[i] = resolveDestroyMethod(methodName, beanDefinition); + } + } + } + + String[] destroyMethodNames = (annotatedNames.isEmpty() ? + inferDestroyMethodsIfNecessary(bean.getClass(), beanDefinition) : + RootBeanDefinition.mergeAotMethodNames(annotatedNames, beanDefinition.getDestroyMethodNames())); if (!ObjectUtils.isEmpty(destroyMethodNames) && - !(this.invokeDisposableBean && DESTROY_METHOD_NAME.equals(destroyMethodNames[0])) && + !(disposableBean && DESTROY_METHOD_NAME.equals(destroyMethodNames[0])) && !beanDefinition.hasAnyExternallyManagedDestroyMethod(destroyMethodNames[0])) { - this.invokeAutoCloseable = - (bean instanceof AutoCloseable && CLOSE_METHOD_NAME.equals(destroyMethodNames[0])); - if (!this.invokeAutoCloseable) { - this.destroyMethodNames = destroyMethodNames; - List destroyMethods = new ArrayList<>(destroyMethodNames.length); - for (String destroyMethodName : destroyMethodNames) { - Method destroyMethod = determineDestroyMethod(destroyMethodName); - if (destroyMethod == null) { - if (beanDefinition.isEnforceDestroyMethod()) { - throw new BeanDefinitionValidationException("Could not find a destroy method named '" + - destroyMethodName + "' on bean with name '" + beanName + "'"); - } - } - else { - if (destroyMethod.getParameterCount() > 0) { - Class[] paramTypes = destroyMethod.getParameterTypes(); - if (paramTypes.length > 1) { - throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + - beanName + "' has more than one parameter - not supported as destroy method"); - } - else if (paramTypes.length == 1 && boolean.class != paramTypes[0]) { - throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + - beanName + "' has a non-boolean parameter - not supported as destroy method"); - } - } - destroyMethod = ClassUtils.getPubliclyAccessibleMethodIfPossible(destroyMethod, bean.getClass()); - destroyMethods.add(destroyMethod); - } - } - this.destroyMethods = destroyMethods.toArray(Method[]::new); + boolean close = (bean instanceof AutoCloseable && CLOSE_METHOD_NAME.equals(destroyMethodNames[0])); + this.invokeAutoCloseable = (close && annotatedNames.isEmpty()); + if (!close && destroyMethodNames.length > annotatedNames.size()) { + this.destroyMethodNames = Arrays.copyOfRange(destroyMethodNames, + annotatedNames.size(), destroyMethodNames.length); + this.destroyMethods = determineDestroyMethods(this.destroyMethodNames, beanDefinition); } } @@ -157,6 +156,7 @@ public DisposableBeanAdapter(Object bean, List postProcessors) { this.bean = bean; @@ -172,6 +173,7 @@ private DisposableBeanAdapter(Object bean, String beanName, boolean nonPublicAcc this.nonPublicAccessAllowed = nonPublicAccessAllowed; this.invokeDisposableBean = invokeDisposableBean; this.invokeAutoCloseable = invokeAutoCloseable; + this.aotDestroyMethodNames = aotDestroyMethodNames; this.destroyMethodNames = destroyMethodNames; this.beanPostProcessors = postProcessors; } @@ -190,63 +192,152 @@ public void destroy() { } } + invokeAotDestroyMethods(); + if (this.invokeDisposableBean) { - if (logger.isTraceEnabled()) { - logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'"); - } - try { - ((DisposableBean) this.bean).destroy(); - } - catch (Throwable ex) { - if (logger.isWarnEnabled()) { - String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'"; - if (logger.isDebugEnabled()) { - // Log at warn level like below but add the exception stacktrace only with debug level - logger.warn(msg, ex); + invokeDisposableBean(); + } + + if (this.invokeAutoCloseable) { + invokeClose(); + } + invokeDestroyMethods(this.destroyMethods, this.destroyMethodNames); + } + + private void invokeAotDestroyMethods() { + if (this.aotDestroyMethodNames != null) { + for (int i = 0; i < this.aotDestroyMethodNames.length; i++) { + String methodName = this.aotDestroyMethodNames[i]; + if (isDisposableBeanMethod(methodName)) { + if (!invokeDisposableBean()) { + break; } - else { - logger.warn(msg + ": " + ex); + } + else if (isAutoCloseableMethod(methodName)) { + if (!invokeClose()) { + break; + } + } + else if (this.aotDestroyMethods == null) { + invokeCustomDestroyMethodIfPresent(methodName); + } + else { + Method method = this.aotDestroyMethods[i]; + if (method != null) { + invokeCustomDestroyMethod(method); } } } } + } - if (this.invokeAutoCloseable) { - if (logger.isTraceEnabled()) { - logger.trace("Invoking close() on bean with name '" + this.beanName + "'"); - } - try { - ((AutoCloseable) this.bean).close(); + private boolean isDisposableBeanMethod(String methodName) { + return (DESTROY_METHOD_NAME.equals(methodName) && this.bean instanceof DisposableBean); + } + + private boolean isAutoCloseableMethod(String methodName) { + return (CLOSE_METHOD_NAME.equals(methodName) && this.bean instanceof AutoCloseable); + } + + private boolean invokeDisposableBean() { + if (logger.isTraceEnabled()) { + logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'"); + } + try { + ((DisposableBean) this.bean).destroy(); + return true; + } + catch (Throwable ex) { + if (logger.isWarnEnabled()) { + String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'"; + if (logger.isDebugEnabled()) { + // Log at warn level like below but add the exception stacktrace only with debug level + logger.warn(msg, ex); + } + else { + logger.warn(msg + ": " + ex); + } } - catch (Throwable ex) { - if (logger.isWarnEnabled()) { - String msg = "Invocation of close method failed on bean with name '" + this.beanName + "'"; - if (logger.isDebugEnabled()) { - // Log at warn level like below but add the exception stacktrace only with debug level - logger.warn(msg, ex); - } - else { - logger.warn(msg + ": " + ex); - } + return false; + } + } + + private boolean invokeClose() { + if (logger.isTraceEnabled()) { + logger.trace("Invoking close() on bean with name '" + this.beanName + "'"); + } + try { + ((AutoCloseable) this.bean).close(); + return true; + } + catch (Throwable ex) { + if (logger.isWarnEnabled()) { + String msg = "Invocation of close method failed on bean with name '" + this.beanName + "'"; + if (logger.isDebugEnabled()) { + // Log the exception stacktrace only with debug level + logger.warn(msg, ex); } + else { + logger.warn(msg + ": " + ex); + } + } + return false; + } + } + + private Method[] determineDestroyMethods(String[] methodNames, RootBeanDefinition beanDefinition) { + List methods = new ArrayList<>(methodNames.length); + for (String methodName : methodNames) { + Method method = resolveDestroyMethod(methodName, beanDefinition); + if (method != null) { + methods.add(method); + } + } + return methods.toArray(Method[]::new); + } + + private @Nullable Method resolveDestroyMethod(String methodName, RootBeanDefinition beanDefinition) { + Method method = determineDestroyMethod(methodName); + if (method == null) { + if (beanDefinition.isEnforceDestroyMethod()) { + throw new BeanDefinitionValidationException("Could not find a destroy method named '" + + methodName + "' on bean with name '" + this.beanName + "'"); } + return null; } - else if (this.destroyMethods != null) { - for (Method destroyMethod : this.destroyMethods) { + + Class[] parameterTypes = method.getParameterTypes(); + if (parameterTypes.length > 1) { + throw new BeanDefinitionValidationException("Method '" + methodName + "' of bean '" + + this.beanName + "' has more than one parameter - not supported as destroy method"); + } + if (parameterTypes.length == 1 && boolean.class != parameterTypes[0]) { + throw new BeanDefinitionValidationException("Method '" + methodName + "' of bean '" + + this.beanName + "' has a non-boolean parameter - not supported as destroy method"); + } + return ClassUtils.getPubliclyAccessibleMethodIfPossible(method, this.bean.getClass()); + } + + private void invokeDestroyMethods(Method @Nullable [] methods, String @Nullable [] methodNames) { + if (methods != null) { + for (Method destroyMethod : methods) { invokeCustomDestroyMethod(destroyMethod); } } - else if (this.destroyMethodNames != null) { - for (String destroyMethodName : this.destroyMethodNames) { - Method destroyMethod = determineDestroyMethod(destroyMethodName); - if (destroyMethod != null) { - destroyMethod = ClassUtils.getPubliclyAccessibleMethodIfPossible(destroyMethod, this.bean.getClass()); - invokeCustomDestroyMethod(destroyMethod); - } + else if (methodNames != null) { + for (String methodName : methodNames) { + invokeCustomDestroyMethodIfPresent(methodName); } } } + private void invokeCustomDestroyMethodIfPresent(String methodName) { + Method method = determineDestroyMethod(methodName); + if (method != null) { + invokeCustomDestroyMethod(ClassUtils.getPubliclyAccessibleMethodIfPossible(method, this.bean.getClass())); + } + } + private @Nullable Method determineDestroyMethod(String destroyMethodName) { try { @@ -365,7 +456,8 @@ protected Object writeReplace() { } return new DisposableBeanAdapter( this.bean, this.beanName, this.nonPublicAccessAllowed, this.invokeDisposableBean, - this.invokeAutoCloseable, this.destroyMethodNames, serializablePostProcessors); + this.invokeAutoCloseable, this.aotDestroyMethodNames, this.destroyMethodNames, + serializablePostProcessors); } @@ -376,6 +468,7 @@ protected Object writeReplace() { */ public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) { return (bean instanceof DisposableBean || + !beanDefinition.getAotDestroyMethodNames().isEmpty() || inferDestroyMethodsIfNecessary(bean.getClass(), beanDefinition) != null); } @@ -398,10 +491,22 @@ public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefin if (destroyMethodNames != null && destroyMethodNames.length > 1) { return destroyMethodNames; } + return inferDestroyMethodIfNecessary(target, beanDefinition, null); + } + + static String @Nullable [] inferAotDestroyMethodsIfNecessary(Class target, RootBeanDefinition beanDefinition, + String[] destroyMethodNames) { + + return (destroyMethodNames.length > 1 ? destroyMethodNames : + inferDestroyMethodIfNecessary(target, beanDefinition, destroyMethodNames[0])); + } + + private static String @Nullable [] inferDestroyMethodIfNecessary(Class target, RootBeanDefinition beanDefinition, + @Nullable String annotatedMethodName) { String destroyMethodName = beanDefinition.resolvedDestroyMethodName; if (destroyMethodName == null) { - destroyMethodName = beanDefinition.getDestroyMethodName(); + destroyMethodName = (annotatedMethodName != null ? annotatedMethodName : beanDefinition.getDestroyMethodName()); boolean autoCloseable = AutoCloseable.class.isAssignableFrom(target); boolean executorService = ExecutorService.class.isAssignableFrom(target); if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) || diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java index 0a164dba9af6..7308377cae5c 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java @@ -10,10 +10,13 @@ import java.lang.reflect.Executable; import java.lang.reflect.Member; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; +import java.util.List; import java.util.Set; import java.util.function.Supplier; +import java.util.stream.Stream; import org.jspecify.annotations.Nullable; @@ -110,6 +113,10 @@ public class RootBeanDefinition extends AbstractBeanDefinition { private @Nullable Set externallyManagedDestroyMethods; + private List aotInitMethodNames = List.of(); + + private List aotDestroyMethodNames = List.of(); + /** * Create a new RootBeanDefinition, to be configured through its bean @@ -239,6 +246,8 @@ public RootBeanDefinition(RootBeanDefinition original) { this.isFactoryMethodUnique = original.isFactoryMethodUnique; this.targetType = original.targetType; this.factoryMethodToIntrospect = original.factoryMethodToIntrospect; + this.aotInitMethodNames = original.aotInitMethodNames; + this.aotDestroyMethodNames = original.aotDestroyMethodNames; } /** @@ -542,13 +551,44 @@ public Set getExternallyManagedInitMethods() { } } + /** + * Set the annotated initializer methods discovered during AOT processing. + *

Eligible methods are invoked before any remaining initializer callbacks. + * @param methodNames the method names in invocation order + * @since 7.1 + */ + public void setAotInitMethodNames(String... methodNames) { + this.aotInitMethodNames = List.copyOf(new LinkedHashSet<>(List.of(methodNames))); + } + + /** + * Return the annotated initializer method names discovered during AOT processing. + * @since 7.1 + */ + public List getAotInitMethodNames() { + return this.aotInitMethodNames; + } + /** * Resolve the inferred destroy method if necessary. * @since 6.0 */ public void resolveDestroyMethodIfNecessary() { - setDestroyMethodNames(DisposableBeanAdapter - .inferDestroyMethodsIfNecessary(getResolvableType().toClass(), this)); + Class beanClass = getResolvableType().toClass(); + String[] destroyMethodNames; + if (!this.aotDestroyMethodNames.isEmpty()) { + // Include any methods discovered by earlier AOT processors when resolving the destroy method. + String[] mergedNames = mergeAotMethodNames(this.aotDestroyMethodNames, getDestroyMethodNames()); + destroyMethodNames = DisposableBeanAdapter.inferAotDestroyMethodsIfNecessary(beanClass, this, mergedNames); + if (Arrays.equals(mergedNames, destroyMethodNames)) { + return; + } + this.aotDestroyMethodNames = List.of(); + } + else { + destroyMethodNames = DisposableBeanAdapter.inferDestroyMethodsIfNecessary(beanClass, this); + } + setDestroyMethodNames(destroyMethodNames); } /** @@ -632,6 +672,32 @@ public Set getExternallyManagedDestroyMethods() { } } + /** + * Set the annotated destroy methods discovered during AOT processing. + *

Eligible methods are invoked before any remaining destroy callbacks. + * @param methodNames the method names in invocation order + * @since 7.1 + */ + public void setAotDestroyMethodNames(String... methodNames) { + this.aotDestroyMethodNames = List.copyOf(new LinkedHashSet<>(List.of(methodNames))); + } + + /** + * Return the annotated destroy method names discovered during AOT processing. + * @since 7.1 + */ + public List getAotDestroyMethodNames() { + return this.aotDestroyMethodNames; + } + + // Reconstruct the annotated prefix of the AOT candidate list and deduplicate exact identifiers. + static String[] mergeAotMethodNames(List annotatedNames, String @Nullable [] configuredNames) { + if (configuredNames == null || (configuredNames.length == 1 && "".equals(configuredNames[0]))) { + return annotatedNames.toArray(String[]::new); + } + return Stream.concat(annotatedNames.stream(), Arrays.stream(configuredNames)).distinct().toArray(String[]::new); + } + @Override public RootBeanDefinition cloneBeanDefinition() { diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessorTests.java index f871c272c147..ab67b8f25232 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessorTests.java @@ -41,6 +41,8 @@ void processAheadOfTimeWhenNoCallbackDoesNotMutateRootBeanDefinition() { RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(); assertThat(mergedBeanDefinition.getInitMethodNames()).isNull(); assertThat(mergedBeanDefinition.getDestroyMethodNames()).isNull(); + assertThat(mergedBeanDefinition.getAotInitMethodNames()).isEmpty(); + assertThat(mergedBeanDefinition.getAotDestroyMethodNames()).isEmpty(); } @Test @@ -48,30 +50,33 @@ void processAheadOfTimeWhenHasInitDestroyAnnotationsAddsMethodNames() { RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyBean.class); processAheadOfTime(beanDefinition); RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(); - assertThat(mergedBeanDefinition.getInitMethodNames()).containsExactly("initMethod"); - assertThat(mergedBeanDefinition.getDestroyMethodNames()).containsExactly("destroyMethod"); + assertThat(mergedBeanDefinition.getAotInitMethodNames()).containsExactly("initMethod"); + assertThat(mergedBeanDefinition.getAotDestroyMethodNames()).containsExactly("destroyMethod"); } @Test - void processAheadOfTimeWhenHasInitDestroyAnnotationsAndCustomDefinedMethodNamesAddsMethodNames() { + void processAheadOfTimeKeepsAnnotatedAndConfiguredMethodsSeparate() { RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyBean.class); beanDefinition.setInitMethodName("customInitMethod"); beanDefinition.setDestroyMethodNames("customDestroyMethod"); processAheadOfTime(beanDefinition); RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(); - assertThat(mergedBeanDefinition.getInitMethodNames()).containsExactly("initMethod", "customInitMethod"); - assertThat(mergedBeanDefinition.getDestroyMethodNames()).containsExactly("destroyMethod", "customDestroyMethod"); + assertThat(mergedBeanDefinition.getAotInitMethodNames()).containsExactly("initMethod"); + assertThat(mergedBeanDefinition.getAotDestroyMethodNames()).containsExactly("destroyMethod"); + assertThat(mergedBeanDefinition.getInitMethodNames()).containsExactly("customInitMethod"); + assertThat(mergedBeanDefinition.getDestroyMethodNames()).containsExactly("customDestroyMethod"); } @Test - void processAheadOfTimeWhenHasInitDestroyAnnotationsAndOverlappingCustomDefinedMethodNamesFiltersDuplicates() { + void processAheadOfTimeTwiceAddsEachAnnotatedMethodOnce() { RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyBean.class); - beanDefinition.setInitMethodName("initMethod"); - beanDefinition.setDestroyMethodNames("destroyMethod"); - processAheadOfTime(beanDefinition); + RegisteredBean registeredBean = registerBean(beanDefinition); + InitDestroyAnnotationBeanPostProcessor processor = createAotBeanPostProcessor(); + processor.processAheadOfTime(registeredBean); + processor.processAheadOfTime(registeredBean); RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(); - assertThat(mergedBeanDefinition.getInitMethodNames()).containsExactly("initMethod"); - assertThat(mergedBeanDefinition.getDestroyMethodNames()).containsExactly("destroyMethod"); + assertThat(mergedBeanDefinition.getAotInitMethodNames()).containsExactly("initMethod"); + assertThat(mergedBeanDefinition.getAotDestroyMethodNames()).containsExactly("destroyMethod"); } @Test @@ -99,8 +104,8 @@ void processAheadOfTimeWhenHasMultipleInitDestroyAnnotationsAddsAllMethodNames() RootBeanDefinition beanDefinition = new RootBeanDefinition(MultiInitDestroyBean.class); processAheadOfTime(beanDefinition); RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(); - assertThat(mergedBeanDefinition.getInitMethodNames()).containsExactly("initMethod", "anotherInitMethod"); - assertThat(mergedBeanDefinition.getDestroyMethodNames()).containsExactly("anotherDestroyMethod", "destroyMethod"); + assertThat(mergedBeanDefinition.getAotInitMethodNames()).containsExactly("initMethod", "anotherInitMethod"); + assertThat(mergedBeanDefinition.getAotDestroyMethodNames()).containsExactly("anotherDestroyMethod", "destroyMethod"); } @Test @@ -117,18 +122,16 @@ void processAheadOfTimeWithMultipleLevelsOfPublicAndPrivateInitAndDestroyMethods processAheadOfTime(beanDefinition); RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(); assertSoftly(softly -> { - softly.assertThat(mergedBeanDefinition.getInitMethodNames()).containsExactly( + softly.assertThat(mergedBeanDefinition.getAotInitMethodNames()).containsExactly( CustomAnnotatedPrivateInitDestroyBean.class.getName() + ".privateInit", // fully-qualified private method - CustomAnnotatedPrivateSameNameInitDestroyBean.class.getName() + ".privateInit", // fully-qualified private method - "afterPropertiesSet", - "customInit" + CustomAnnotatedPrivateSameNameInitDestroyBean.class.getName() + ".privateInit" // fully-qualified private method ); - softly.assertThat(mergedBeanDefinition.getDestroyMethodNames()).containsExactly( + softly.assertThat(mergedBeanDefinition.getAotDestroyMethodNames()).containsExactly( CustomAnnotatedPrivateSameNameInitDestroyBean.class.getName() + ".privateDestroy", // fully-qualified private method - CustomAnnotatedPrivateInitDestroyBean.class.getName() + ".privateDestroy", // fully-qualified private method - "destroy", - "customDestroy" + CustomAnnotatedPrivateInitDestroyBean.class.getName() + ".privateDestroy" // fully-qualified private method ); + softly.assertThat(mergedBeanDefinition.getInitMethodNames()).containsExactly("afterPropertiesSet", "customInit"); + softly.assertThat(mergedBeanDefinition.getDestroyMethodNames()).containsExactly("destroy", "customDestroy"); }); } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java index 2c1255be590b..b39c01641b92 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java @@ -905,14 +905,16 @@ private void generateApplyBeanRegistrarsMethod(MethodSpec.Builder method, Genera reflectionHints.registerConstructor(constructor, ExecutableMode.INVOKE); } } - if (!ObjectUtils.isEmpty(rootBeanDefinition.getInitMethodNames())) { - method.addCode(generateInitDestroyMethods(name, rootBeanDefinition, - rootBeanDefinition.getInitMethodNames(), "setInitMethodNames", reflectionHints)); - } - if (!ObjectUtils.isEmpty(rootBeanDefinition.getDestroyMethodNames())) { - method.addCode(generateInitDestroyMethods(name, rootBeanDefinition, - rootBeanDefinition.getDestroyMethodNames(), "setDestroyMethodNames", reflectionHints)); - } + method.addCode(generateInitDestroyMethods(name, rootBeanDefinition, + rootBeanDefinition.getInitMethodNames(), "setInitMethodNames", reflectionHints)); + method.addCode(generateInitDestroyMethods(name, rootBeanDefinition, + rootBeanDefinition.getDestroyMethodNames(), "setDestroyMethodNames", reflectionHints)); + method.addCode(generateInitDestroyMethods(name, rootBeanDefinition, + rootBeanDefinition.getAotInitMethodNames().toArray(String[]::new), + "setAotInitMethodNames", reflectionHints)); + method.addCode(generateInitDestroyMethods(name, rootBeanDefinition, + rootBeanDefinition.getAotDestroyMethodNames().toArray(String[]::new), + "setAotDestroyMethodNames", reflectionHints)); checkUnsupportedFeatures(rootBeanDefinition); } } @@ -1013,10 +1015,13 @@ private boolean isVisible(Constructor ctor, ClassName className) { ctor.getDeclaringClass().getPackageName().equals(className.packageName()))); } - private CodeBlock generateInitDestroyMethods(String beanName, AbstractBeanDefinition beanDefinition, - String[] methodNames, String method, ReflectionHints reflectionHints) { + private CodeBlock generateInitDestroyMethods(String beanName, RootBeanDefinition beanDefinition, + String @Nullable [] methodNames, String method, ReflectionHints reflectionHints) { Builder code = CodeBlock.builder(); + if (ObjectUtils.isEmpty(methodNames)) { + return code.build(); + } // For Publisher-based destroy methods reflectionHints.registerType(TypeReference.of("org.reactivestreams.Publisher")); Class beanType = ClassUtils.getUserClass(beanDefinition.getResolvableType().toClass()); @@ -1026,7 +1031,7 @@ private CodeBlock generateInitDestroyMethods(String beanName, AbstractBeanDefini .collect(CodeBlock.joining(", ")); code.addStatement("$L.add($S, $L -> (($T)$L).$L($L))", CUSTOMIZER_MAP_VARIABLE, beanName, "bd", - AbstractBeanDefinition.class, "bd", method, arguments); + RootBeanDefinition.class, "bd", method, arguments); return code.build(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorAotContributionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorAotContributionTests.java index 7cbad07c04ce..8653ee9af265 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorAotContributionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorAotContributionTests.java @@ -15,6 +15,7 @@ import javax.lang.model.element.Modifier; import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import org.assertj.core.api.InstanceOfAssertFactories; import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Nested; @@ -30,6 +31,7 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanRegistrar; import org.springframework.beans.factory.BeanRegistry; +import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution; @@ -490,21 +492,24 @@ void applyToWhenHasInstanceSupplier() { } @Test - void applyToWhenHasPostConstructAnnotationPostProcessed() { + void applyToWhenHasLifecycleAnnotationsInvokesThemBeforeInterfaceCallbacks() { BeanFactoryInitializationAotContribution contribution = getContribution(CommonAnnotationBeanPostProcessor.class, PostConstructConfiguration.class); assertThat(contribution).isNotNull(); contribution.applyTo(generationContext, beanFactoryInitializationCode); compile((initializer, compiled) -> { - GenericApplicationContext freshContext = new GenericApplicationContext(); - initializer.accept(freshContext); - freshContext.refresh(); - Init init = freshContext.getBean(Init.class); - assertThat(init).isNotNull(); - assertThat(init.initialized).isTrue(); + Init bean; + try (GenericApplicationContext freshContext = new GenericApplicationContext()) { + initializer.accept(freshContext); + freshContext.refresh(); + bean = freshContext.getBean(Init.class); + assertThat(bean.callbacks).containsExactly("postConstruct", "afterPropertiesSet"); + } + assertThat(bean.callbacks).containsExactly("postConstruct", "afterPropertiesSet", "preDestroy", "destroy"); assertThat(RuntimeHintsPredicates.reflection().onMethodInvocation(Init.class, "postConstruct")) .accepts(generationContext.getRuntimeHints()); - freshContext.close(); + assertThat(RuntimeHintsPredicates.reflection().onMethodInvocation(Init.class, "preDestroy")) + .accepts(generationContext.getRuntimeHints()); }); } @@ -678,13 +683,28 @@ public void setImportMetadata(AnnotationMetadata importMetadata) { static class Foo { } - static class Init { + static class Init implements InitializingBean, DisposableBean { - boolean initialized = false; + final List callbacks = new ArrayList<>(); @PostConstruct void postConstruct() { - initialized = true; + this.callbacks.add("postConstruct"); + } + + @Override + public void afterPropertiesSet() { + this.callbacks.add("afterPropertiesSet"); + } + + @PreDestroy + void preDestroy() { + this.callbacks.add("preDestroy"); + } + + @Override + public void destroy() { + this.callbacks.add("destroy"); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/InitDestroyMethodLifecycleTests.java b/spring-context/src/test/java/org/springframework/context/annotation/InitDestroyMethodLifecycleTests.java index c39b38eeca50..6d987dbad55a 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/InitDestroyMethodLifecycleTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/InitDestroyMethodLifecycleTests.java @@ -16,7 +16,9 @@ import org.springframework.aot.test.generate.TestGenerationContext; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.annotation.lifecyclemethods.InitDestroyBean; @@ -174,17 +176,17 @@ void jakartaAnnotationsWithCustomSameMethodNamesWithAotProcessingAndAotRuntime() CustomAnnotatedPrivateSameNameInitDestroyBean bean = aotApplicationContext.getBean("lifecycleTestBean", beanClass); assertThat(bean.initMethods).as("init-methods").containsExactly( - "afterPropertiesSet", "@PostConstruct.privateCustomInit1", "@PostConstruct.sameNameCustomInit1", + "afterPropertiesSet", "customInit" ); aotApplicationContext.close(); assertThat(bean.destroyMethods).as("destroy-methods").containsExactly( - "destroy", "@PreDestroy.sameNameCustomDestroy1", "@PreDestroy.privateCustomDestroy1", + "destroy", "customDestroy" ); }); @@ -209,17 +211,17 @@ void jakartaAnnotationsWithPackagePrivateInitDestroyMethodsWithAotProcessingAndA SubPackagePrivateInitDestroyBean bean = aotApplicationContext.getBean("lifecycleTestBean", beanClass); assertThat(bean.initMethods).as("init-methods").containsExactly( - "InitializingBean.afterPropertiesSet", "PackagePrivateInitDestroyBean.postConstruct", "SubPackagePrivateInitDestroyBean.postConstruct", + "InitializingBean.afterPropertiesSet", "initMethod" ); aotApplicationContext.close(); assertThat(bean.destroyMethods).as("destroy-methods").containsExactly( - "DisposableBean.destroy", "SubPackagePrivateInitDestroyBean.preDestroy", "PackagePrivateInitDestroyBean.preDestroy", + "DisposableBean.destroy", "destroyMethod" ); }); @@ -235,6 +237,166 @@ void allLifecycleMechanismsAtOnce() { assertThat(bean.destroyMethods).as("destroy-methods").containsExactly("destroy"); } + @Test + @CompileWithForkedClassLoader + void annotatedInterfaceCallbacksAreInvokedOnceDuringAotRuntime() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory); + RootBeanDefinition beanDefinition = new RootBeanDefinition(CustomAnnotatedInitDestroyWithShadowedMethodsBean.class); + beanDefinition.setInitMethodNames("afterPropertiesSet", "customInit"); + beanDefinition.setDestroyMethodNames("destroy", "customDestroy"); + beanFactory.registerBeanDefinition("lifecycleTestBean", beanDefinition); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + CustomAnnotatedInitDestroyWithShadowedMethodsBean bean; + try (GenericApplicationContext aotContext = createApplicationContext(initializer)) { + bean = aotContext.getBean(CustomAnnotatedInitDestroyWithShadowedMethodsBean.class); + assertThat(bean.initMethods).containsExactly("@PostConstruct.afterPropertiesSet", "customInit"); + } + assertThat(bean.destroyMethods).containsExactly("@PreDestroy.destroy"); + }); + } + + @Test + @CompileWithForkedClassLoader + void inheritedPreDestroyCallbacksRunOnceInAnnotationOrderDuringAotRuntime() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(applicationContext.getDefaultListableBeanFactory()); + applicationContext.registerBean(AnnotatedDestroyFirstBean.class); + applicationContext.registerBean(AnnotatedDestroyLastBean.class); + applicationContext.registerBean(AnnotatedCloseBeforeDestroyBean.class); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + AnnotatedDestroyFirstBean first; + AnnotatedDestroyLastBean last; + AnnotatedCloseBeforeDestroyBean closeBeforeDestroy; + try (GenericApplicationContext aotContext = createApplicationContext(initializer)) { + first = aotContext.getBean(AnnotatedDestroyFirstBean.class); + last = aotContext.getBean(AnnotatedDestroyLastBean.class); + closeBeforeDestroy = aotContext.getBean(AnnotatedCloseBeforeDestroyBean.class); + } + assertThat(first.calls).containsExactly("destroy", "preDestroy"); + assertThat(last.calls).containsExactly("preDestroy", "destroy"); + assertThat(closeBeforeDestroy.calls).containsExactly("close", "destroy"); + }); + } + + @Test + @CompileWithForkedClassLoader + void annotatedCloseFailureSkipsRemainingAnnotationsDuringAotRuntime() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory); + RootBeanDefinition beanDefinition = new RootBeanDefinition(FailingAnnotatedCloseBean.class); + beanDefinition.setDestroyMethodName("finish"); + beanFactory.registerBeanDefinition("lifecycleTestBean", beanDefinition); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + FailingAnnotatedCloseBean bean; + try (GenericApplicationContext aotContext = createApplicationContext(initializer)) { + bean = aotContext.getBean(FailingAnnotatedCloseBean.class); + } + assertThat(bean.calls).containsExactly("beforeClose", "close", "destroy", "finish"); + }); + } + + @Test + @CompileWithForkedClassLoader + void runtimePostProcessorDoesNotDuplicateGeneratedDestroyCallback() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(applicationContext.getDefaultListableBeanFactory()); + applicationContext.registerBean(PreDestroyBase.class); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + PreDestroyBase bean; + try (GenericApplicationContext aotContext = new GenericApplicationContext()) { + initializer.initialize(aotContext); + aotContext.getBeanFactory().addBeanPostProcessor(new RuntimeDestroyPostProcessor()); + aotContext.refresh(); + bean = aotContext.getBean(PreDestroyBase.class); + } + assertThat(bean.calls).containsExactly("preDestroy"); + }); + } + + @Test + @CompileWithForkedClassLoader + void annotatedCloseIsInvokedBeforeDestroyAndSuppressesRemainingConfiguredMethods() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory); + RootBeanDefinition beanDefinition = new RootBeanDefinition(AnnotatedCloseWithDestroyBean.class); + beanDefinition.setDestroyMethodNames("close", "customDestroy"); + beanFactory.registerBeanDefinition("lifecycleTestBean", beanDefinition); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + AnnotatedCloseWithDestroyBean bean; + try (GenericApplicationContext aotContext = createApplicationContext(initializer)) { + bean = aotContext.getBean(AnnotatedCloseWithDestroyBean.class); + } + assertThat(bean.destroyMethods).containsExactly("close", "destroy"); + }); + } + + @Test + @CompileWithForkedClassLoader + void privateAnnotatedMethodsRemainDistinctFromSameNamedCallbacksDuringAotRuntime() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory); + RootBeanDefinition beanDefinition = new RootBeanDefinition(SameNamedCallbacksBean.class); + beanDefinition.setDestroyMethodName("customDestroy"); + beanFactory.registerBeanDefinition("lifecycleTestBean", beanDefinition); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + SameNamedCallbacksBean bean; + try (GenericApplicationContext aotContext = createApplicationContext(initializer)) { + bean = aotContext.getBean(SameNamedCallbacksBean.class); + assertThat(bean.initMethods).containsExactly("annotated afterPropertiesSet", "afterPropertiesSet"); + } + assertThat(bean.destroyMethods).containsExactly("annotated customDestroy", "customDestroy"); + }); + } + + @Test + @CompileWithForkedClassLoader + void interfaceCallbacksOnFactoryMethodResultRetainTheirOrderDuringAotRuntime() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(applicationContext.getDefaultListableBeanFactory()); + applicationContext.registerBean(FactoryLifecycleConfiguration.class); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + PackagePrivateInitDestroyBean bean; + try (GenericApplicationContext aotContext = createApplicationContext(initializer)) { + bean = aotContext.getBean(PackagePrivateInitDestroyBean.class); + assertThat(bean.initMethods).containsExactly( + "PackagePrivateInitDestroyBean.postConstruct", "afterPropertiesSet", "initMethod"); + } + assertThat(bean.destroyMethods).containsExactly( + "PackagePrivateInitDestroyBean.preDestroy", "destroy", "destroyMethod"); + }); + } + + @Test + @CompileWithForkedClassLoader + void annotatedDestroyMethodRespectsDisabledInferenceDuringAotRuntime() { + GenericApplicationContext applicationContext = new GenericApplicationContext(); + DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory(); + AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory); + RootBeanDefinition beanDefinition = new RootBeanDefinition(AnnotatedCloseableBean.class); + beanDefinition.setDestroyMethodName(""); + beanFactory.registerBeanDefinition("lifecycleTestBean", beanDefinition); + + testCompiledResult(applicationContext, (initializer, compiled) -> { + AnnotatedCloseableBean bean; + try (GenericApplicationContext aotContext = createApplicationContext(initializer)) { + bean = aotContext.getBean(AnnotatedCloseableBean.class); + } + assertThat(bean.destroyMethods).containsExactly("preDestroy"); + }); + } + private static DefaultListableBeanFactory createBeanFactoryAndRegisterBean(Class beanClass, String initMethodName, String destroyMethodName) { @@ -425,4 +587,196 @@ void preDestroy() { } } + + @Configuration(proxyBeanMethods = false) + static class FactoryLifecycleConfiguration { + + @Bean(initMethod = "initMethod", destroyMethod = "destroyMethod") + PackagePrivateInitDestroyBean lifecycleTestBean() { + return new FactoryLifecycleBean(); + } + } + + + static class FactoryLifecycleBean extends PackagePrivateInitDestroyBean implements InitializingBean, DisposableBean { + + @Override + public void afterPropertiesSet() { + this.initMethods.add("afterPropertiesSet"); + } + + @Override + public void destroy() { + this.destroyMethods.add("destroy"); + } + } + + + static class PreDestroyBase { + + final List calls = new ArrayList<>(); + + @PreDestroy + void preDestroy() { + this.calls.add("preDestroy"); + } + } + + + static class RuntimeDestroyPostProcessor + implements MergedBeanDefinitionPostProcessor, DestructionAwareBeanPostProcessor { + + @Override + public void postProcessMergedBeanDefinition(RootBeanDefinition definition, Class type, String name) { + if (PreDestroyBase.class.isAssignableFrom(type)) { + definition.registerExternallyManagedDestroyMethod("preDestroy"); + } + } + + @Override + public boolean requiresDestruction(Object bean) { + return bean instanceof PreDestroyBase; + } + + @Override + public void postProcessBeforeDestruction(Object bean, String name) { + ((PreDestroyBase) bean).preDestroy(); + } + } + + + + static class AnnotatedDestroyFirstBean extends PreDestroyBase implements DisposableBean { + + @Override + @PreDestroy + public void destroy() { + this.calls.add("destroy"); + } + } + + + static class DestroyBase implements DisposableBean { + + final List calls = new ArrayList<>(); + + @Override + @PreDestroy + public void destroy() { + this.calls.add("destroy"); + } + } + + + static class AnnotatedDestroyLastBean extends DestroyBase { + + @PreDestroy + void preDestroy() { + this.calls.add("preDestroy"); + } + } + + + + static class AnnotatedCloseBeforeDestroyBean extends DestroyBase implements AutoCloseable { + + @Override + @PreDestroy + public void close() { + this.calls.add("close"); + } + } + + + static class FailingAnnotatedCloseBase extends PreDestroyBase implements AutoCloseable { + + @Override + @PreDestroy + public void close() { + this.calls.add("close"); + throw new IllegalStateException("Close failed"); + } + } + + + static class FailingAnnotatedCloseBean extends FailingAnnotatedCloseBase implements DisposableBean { + + @PreDestroy + void beforeClose() { + this.calls.add("beforeClose"); + } + + @Override + public void destroy() { + this.calls.add("destroy"); + } + + void finish() { + this.calls.add("finish"); + } + } + + + + static class AnnotatedCloseableBean implements AutoCloseable { + + final List destroyMethods = new ArrayList<>(); + + @PreDestroy + void preDestroy() { + this.destroyMethods.add("preDestroy"); + } + + @Override + public void close() { + this.destroyMethods.add("close"); + } + } + + + static class AnnotatedCloseWithDestroyBean extends CustomInitDestroyBean implements AutoCloseable, DisposableBean { + + @PreDestroy + @Override + public void close() { + this.destroyMethods.add("close"); + } + + @Override + public void destroy() { + this.destroyMethods.add("destroy"); + } + } + + + static class PrivateAnnotatedCallbacksBean { + + final List initMethods = new ArrayList<>(); + + final List destroyMethods = new ArrayList<>(); + + @PostConstruct + private void afterPropertiesSet() { + this.initMethods.add("annotated afterPropertiesSet"); + } + + @PreDestroy + private void customDestroy() { + this.destroyMethods.add("annotated customDestroy"); + } + } + + + static class SameNamedCallbacksBean extends PrivateAnnotatedCallbacksBean implements InitializingBean { + + @Override + public void afterPropertiesSet() { + this.initMethods.add("afterPropertiesSet"); + } + + public void customDestroy() { + this.destroyMethods.add("customDestroy"); + } + } + }