Bean被IoC容器销毁后还能使用吗?

Talk is cheap. Show me the code

第一步:定义一个Bean用来测试。

package com.xxx.hyl.ioc;

/**
 * Bean 销毁演示
 * @author 君战
 *
 * **/
public class DestroyBean {
}

第二步:使用IoC容器来销毁Bean,再次获取。

package com.xxx.hyl.ioc;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/****
 * 演示Bean销毁后依然可以从IoC容器中获取
 * @author 君战
 * */
public class DestroyBeanDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(DestroyBean.class);
        context.refresh();
        DestroyBean beforeDestroy = context.getBean(DestroyBean.class);
        System.out.println("执行Bean销毁前:" + beforeDestroy);
        context.getAutowireCapableBeanFactory().destroyBean(beforeDestroy);
        DestroyBean afterDestroy = context.getBean(DestroyBean.class);
        System.out.println("执行Bean销毁后:" + afterDestroy);
    }
}

第三步:查看控制台打印

需要搞明白的一点是,Bean所实现的或遵守的Spring提供的接口或者按照JSR-330规范的销毁方法被调用时,并不意味着该对象即将被GC掉,这和JVM的垃圾回收机制没有任何关系,也不意味它会被IoC容器给移除掉。

可以通过手动调用AutowireCapableBeanFactory提供的destroyBean方法来触发指定Bean所实现的销毁方法的调用。该方法需要传入Bean实例。

/**
	 * Destroy the given bean instance (typically coming from {@link #createBean}),
	 * applying the {@link org.springframework.beans.factory.DisposableBean} contract as well as
	 * registered {@link DestructionAwareBeanPostProcessor DestructionAwareBeanPostProcessors}.
	 * <p>Any exception that arises during destruction should be caught
	 * and logged instead of propagated to the caller of this method.
	 * @param existingBean the bean instance to destroy
	 */
	void destroyBean(Object existingBean);

AbstractAutowireCapableBeanFactory实现了该方法,在该实现中,手动创建DisposableBeanAdapt-er的实例,然后调用其destroy方法。其构造函数中需要三个参数,分别为:要销毁的Bean实例、IoC容器所有已注册的BeanPostProcessor实现类以及访问控制上下文。在DisposableBeanAdapter构造函数中通过判断当前传入的Bean是否是DisposableBean类型来确定属性invokeDisposableBean的值。

public void destroyBean(Object existingBean) {
   new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy();
}

// DisposableBeanAdapter#DisposableBeanAdapter(Object, List<BeanPostProcessor>, AccessControlContext)
public DisposableBeanAdapter(Object bean, List<BeanPostProcessor> postProcessors, AccessControlContext acc) {
		Assert.notNull(bean, "Disposable bean must not be null");
		this.bean = bean;
		this.beanName = bean.getClass().getName();
		this.invokeDisposableBean = (this.bean instanceof DisposableBean);
		this.nonPublicAccessAllowed = true;
		this.acc = acc;
		this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
}

在DisposableBeanAdapter的destroy方法中,首先调用IoC容器中所有DestructionAwareBeanPostPr-ocessor接口实现类的postProcessBeforeDestruction方法。Spring IoC容器对于使用JSR-330规范中定义的@PreDestroy注解标注的方法就是在这里完成的调用(CommonAnnotationBeanPostProcessor)。

比较有意思的是接下来处理Bean实现DisposableBean的destroy方法,可以看到使用try…catch捕获住了该方法可能发生的异常,在catch块中,仅仅是打印日志。这也意味着即使在Bean实现Disposable-Bean的destroy方法中发生异常,也不会影响接下来对Bean自定义销毁方法的调用。

最后调用Bean自定义的销毁方法。

// DisposableBeanAdapter#destroy
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);
         }
      }
   }
	//在这里调用Bean自定义的销毁方法
   if (this.destroyMethod != null) {
      invokeCustomDestroyMethod(this.destroyMethod);
   } else if (this.destroyMethodName != null) {
      Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
      if (methodToInvoke != null) {
         invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
      }
   }
}

总结

以上就是我们对Bean被IoC容器销毁后还能使用吗问题的分析,答案是依然可以使用,但不建议使用,因为Bean可能在销毁方法中释放了一些资源或者修改了一些状态,使得Bean不再处于正确的状态。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值