• 聊聊DisposableBeanAdapter


    本文主要研究一下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;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    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 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) () -> {
    						((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 } or {@code
    	 * } attributes.
    	 * 

    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); } }

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133

    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))));
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    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为想要执行的销毁方法。

  • 相关阅读:
    python 图片爬虫记录
    力扣 8. 字符串转换整数 (atoi)
    Linux
    项目持续集成配置流程
    代码随想录Day19 LeetCode T669修剪二叉搜索树 LeetCode T108将有序数组转化为二叉搜索树 T538 把二叉搜索树转化为累加树
    【SSD1306 OLED屏幕测试程序 (开源)orangepi zero2 全志H616 】.md updata: 23/11/07
    VUE3 之 使用标签实现动画与过渡效果(下) - 这个系列的教程通俗易懂,适合新手
    Git&GitHub 团队协作
    经典/最新计算机视觉论文及代码推荐
    在ubuntu上安装hadoop完分布式
  • 原文地址:https://blog.csdn.net/hello_ejb3/article/details/133938945