美文网首页
聊聊DisposableBeanAdapter

聊聊DisposableBeanAdapter

作者: go4it | 来源:发表于2023-10-19 09:07 被阅读0次

本文主要研究一下DisposableBeanAdapter

DisposableBean

spring-beans/src/main/java/org/springframework/beans/factory/DisposableBean.java

public interface DisposableBean {

    /**
     * Invoked by the containing {@code BeanFactory} on destruction of a bean.
     * @throws Exception in case of shutdown errors. Exceptions will get logged
     * but not rethrown to allow other beans to release their resources as well.
     */
    void destroy() throws Exception;

}

DisposableBean定义了destroy方法

DisposableBeanAdapter

spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java

class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {

    private static final String CLOSE_METHOD_NAME = "close";

    private static final String SHUTDOWN_METHOD_NAME = "shutdown";

    private static final Log logger = LogFactory.getLog(DisposableBeanAdapter.class);


    private final Object bean;

    private final String beanName;

    private final boolean invokeDisposableBean;

    private final boolean nonPublicAccessAllowed;

    @Nullable
    private final AccessControlContext acc;

    @Nullable
    private String destroyMethodName;

    @Nullable
    private transient Method destroyMethod;

    @Nullable
    private final List<DestructionAwareBeanPostProcessor> beanPostProcessors;

    @Override
    public void run() {
        destroy();
    }

    @Override
    public void destroy() {
        if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
            for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
                processor.postProcessBeforeDestruction(this.bean, this.beanName);
            }
        }

        if (this.invokeDisposableBean) {
            if (logger.isTraceEnabled()) {
                logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'");
            }
            try {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                        ((DisposableBean) this.bean).destroy();
                        return null;
                    }, this.acc);
                }
                else {
                    ((DisposableBean) this.bean).destroy();
                }
            }
            catch (Throwable ex) {
                String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
                if (logger.isDebugEnabled()) {
                    logger.warn(msg, ex);
                }
                else {
                    logger.warn(msg + ": " + ex);
                }
            }
        }

        if (this.destroyMethod != null) {
            invokeCustomDestroyMethod(this.destroyMethod);
        }
        else if (this.destroyMethodName != null) {
            Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
            if (methodToInvoke != null) {
                invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
            }
        }
    }

    /**
     * Check whether the given bean has any kind of destroy method to call.
     * @param bean the bean instance
     * @param beanDefinition the corresponding bean definition
     */
    public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
        if (bean instanceof DisposableBean || bean instanceof AutoCloseable) {
            return true;
        }
        return inferDestroyMethodIfNecessary(bean, beanDefinition) != null;
    }

    /**
     * If the current value of the given beanDefinition's "destroyMethodName" property is
     * {@link AbstractBeanDefinition#INFER_METHOD}, then attempt to infer a destroy method.
     * Candidate methods are currently limited to public, no-arg methods named "close" or
     * "shutdown" (whether declared locally or inherited). The given BeanDefinition's
     * "destroyMethodName" is updated to be null if no such method is found, otherwise set
     * to the name of the inferred method. This constant serves as the default for the
     * {@code @Bean#destroyMethod} attribute and the value of the constant may also be
     * used in XML within the {@code <bean destroy-method="">} or {@code
     * <beans default-destroy-method="">} attributes.
     * <p>Also processes the {@link java.io.Closeable} and {@link java.lang.AutoCloseable}
     * interfaces, reflectively calling the "close" method on implementing beans as well.
     */
    @Nullable
    private static String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {
        String destroyMethodName = beanDefinition.resolvedDestroyMethodName;
        if (destroyMethodName == null) {
            destroyMethodName = beanDefinition.getDestroyMethodName();
            if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
                    (destroyMethodName == null && bean instanceof AutoCloseable)) {
                // Only perform destroy method inference or Closeable detection
                // in case of the bean not explicitly implementing DisposableBean
                destroyMethodName = null;
                if (!(bean instanceof DisposableBean)) {
                    try {
                        destroyMethodName = bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();
                    }
                    catch (NoSuchMethodException ex) {
                        try {
                            destroyMethodName = bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();
                        }
                        catch (NoSuchMethodException ex2) {
                            // no candidate destroy method found
                        }
                    }
                }
            }
            beanDefinition.resolvedDestroyMethodName = (destroyMethodName != null ? destroyMethodName : "");
        }
        return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null);
    }   
}   

DisposableBeanAdapter实现了DisposableBean、Runnable接口,其run方法执行的是destroy方法;其destroy方法会遍历DestructionAwareBeanPostProcessor挨个执行postProcessBeforeDestruction方法,对于invokeDisposableBean的则执行其destroy方法,对于destroyMethod不为null或者destroyMethodName不为null的则通过invokeCustomDestroyMethod执行

它提供了hasDestroyMethod方法用于判断某个bean是否有destroy方法,如果是DisposableBean或者AutoCloseable类型则直接返回true,否则通过inferDestroyMethodIfNecessary方法判断,它目前会把public的无参的close或者shutdown方法(不论是自己定义的还是继承而来的)作为destroyMethod

registerDisposableBeanIfNecessary

spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java

    /**
     * Add the given bean to the list of disposable beans in this factory,
     * registering its DisposableBean interface and/or the given destroy method
     * to be called on factory shutdown (if applicable). Only applies to singletons.
     * @param beanName the name of the bean
     * @param bean the bean instance
     * @param mbd the bean definition for the bean
     * @see RootBeanDefinition#isSingleton
     * @see RootBeanDefinition#getDependsOn
     * @see #registerDisposableBean
     * @see #registerDependentBean
     */
    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
        if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
            if (mbd.isSingleton()) {
                // Register a DisposableBean implementation that performs all destruction
                // work for the given bean: DestructionAwareBeanPostProcessors,
                // DisposableBean interface, custom destroy method.
                registerDisposableBean(beanName, new DisposableBeanAdapter(
                        bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
            }
            else {
                // A bean with a custom scope...
                Scope scope = this.scopes.get(mbd.getScope());
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
                }
                scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(
                        bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
            }
        }
    }

    protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
        return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) ||
                (hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(
                        bean, getBeanPostProcessorCache().destructionAware))));
    }

AbstractBeanFactory的registerDisposableBeanIfNecessary方法会通过requiresDestruction判断是否需要销毁,是的话会执行registerDisposableBean或者registerDestructionCallback,这里通过DisposableBeanAdapter进行了包装

小结

DisposableBeanAdapter实现了DisposableBean、Runnable接口,它主要是执行DestructionAwareBeanPostProcessor的postProcessBeforeDestruction方法,对于invokeDisposableBean的则执行其destroy方法,对于destroyMethod不为null或者destroyMethodName不为null的则通过invokeCustomDestroyMethod执行。

DisposableBeanAdapter提供了hasDestroyMethod方法用于判断某个bean是否有destroy方法,如果是DisposableBean或者AutoCloseable类型则直接返回true,否则通过inferDestroyMethodIfNecessary方法判断,它目前会把public的无参的close或者shutdown方法(不论是自己定义的还是继承而来的)作为destroyMethod

值得注意的是自动推断的前提是beanDefinition.getDestroyMethodName()为AbstractBeanDefinition.INFER_METHOD或者是destroyMethodName为null但是bean是AutoCloseable类型,而且推断也只是找close、shutdown方法,如果没有实现DisposableBean接口,但是定义了destory方法,不会被认为是destroyMethod;@Bean注解的destroyMethod默认就是AbstractBeanDefinition.INFER_METHOD,如果是通过GenericApplicationContext.registerBean注册的,则默认destroyMethodName为空,需要自己设置,如果是通过registerBeanDefinition方法的,需要自己保证destroyMethodName为想要执行的销毁方法

相关文章

  • Spring源码解析(十三)-DisposableBeanAda

    Spring版本 5.2.5.RELEASE 源码解析 1. DisposableBeanAdapter 构造方法...

  • 聊聊…聊聊?

    世界不大,一座城市里,用高楼大厦圈出来的的圈子更小了… 心再大,也会被城市里喧嚣的汽笛压抑自己 不记得有多久没有好...

  • 聊聊聊

    今天主要的时间是和阿q过的,非常开心我们有了这么一次聊天! 我觉得自己不孤单了。我俩目前拥有的感情非常相似,是比较...

  • 无聊聊聊

  • 聊聊,聊聊选择

    今早梦到一杯豆浆15元,我给自己的孩子买了一杯50元的奶茶,对她感叹“在我们那个年代一杯奶茶才10元”孩子问我那么...

  • 聊聊,聊聊闲时

    有段时间着了迷一样的看伍迪艾伦电影,印象最深的就是电影开场他一张大脸挤满了屏幕,絮絮叨叨两分钟,正片开始。 后来得...

  • 37

    今晚不想你睡 想和你聊聊聊聊聊到天天天天天长地久

  • 那个我以为很酷的男生

    熄了 灯,朋友打电话来聊天,聊了好久好久… 聊聊过去,聊聊现在,聊聊未来,聊聊别人,也聊聊自己… 一晃我们过了二字...

  • 悠然自得——二舅家游记(下)

    我们一起聊聊工作,聊聊生活,聊聊城市,聊聊乡村,聊聊猪场,聊聊门前那条黑背。我不争气的扒在窗口,安安静静地看着它。...

  • 我一直不缺母爱20210106

    元旦,儿子放月假。 其实我儿子每次放假回家都会和我聊聊天,聊聊学校,聊聊老师,聊聊同学,聊聊他自己,没有着重点,都...

网友评论

      本文标题:聊聊DisposableBeanAdapter

      本文链接:https://www.haomeiwen.com/subject/yxhhidtx.html