返回介绍

5.7.5 注册 DisposableBean

发布于 2025-04-22 22:09:11 字数 1352 浏览 0 评论 0 收藏

Spring 中不但提供了对于初始化方法的扩展入口,同样也提供了销毁方法的扩展入口,对于销毁方法的扩展,除了我们熟知的配置属性 destroy-method 方法外,用户还可以注册后处理器 DestructionAwareBeanPostProcessor 来统一处理 bean 的销毁方法,代码如下:

protected void registerDisposableBeanIfNecessary(String beanName, Object bean,

RootBeanDefinition mbd) {

  AccessControlContext acc = (System.getSecurityManager() != null ? getAccess

  ControlContext() : null);

  if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {

   if (mbd.isSingleton()) {

   /*

    * 单例模式下注册需要销毁的 bean,此方法中会处理实现 DisposableBean 的 bean,

    * 并且对所有的 bean 使用 DestructionAwareBeanPostProcessors 处理

    * DisposableBean DestructionAwareBeanPostProcessors,

    */

   registerDisposableBean(beanName,

    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPost

    Processors(), acc));

   }else {

   /*

    * 自定义 scope 的处理

    */

    Scope scope = this.scopes.get(mbd.getScope());

    if (scope == null) {

     throw new IllegalStateException("No Scope registered for scope '"

     + mbd.getScope() + "'");

   }

   scope.registerDestructionCallback(beanName,

    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPost

    Processors(), acc));

  }

 }

}

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。