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

kukugou   ·   发表于 2020-12-31   ·   编程代码
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}.
*

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

11 Reply   |  Until 2021-1-10 | 3972 View

天空丶泪
发表于 2020-12-31

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, AccessControlContext)
public DisposableBeanAdapter(Object bean, List 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);
}

评论列表

  • 加载数据中...

编写评论内容

klmk
发表于 2020-12-31

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

评论列表

  • 加载数据中...

编写评论内容

微梦
发表于 2020-12-31

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

评论列表

  • 加载数据中...

编写评论内容

1679644933
发表于 2020-12-31

最后调用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) () -> {
((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));
}
}
}

评论列表

  • 加载数据中...

编写评论内容

1008612
发表于 2020-12-31

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

评论列表

  • 加载数据中...

编写评论内容

梦如南筏
发表于 2021-1-1

你好,你们的团队招人吗?我想加入你们的团队

评论列表

  • 加载数据中...

编写评论内容

道创网站官方账号
发表于 2021-1-1

这一看就是又从那个网站抄来的文章[汗]

评论列表

  • 加载数据中...

编写评论内容

天宇
发表于 2021-1-1

也就是说,那个内存空间没有被销毁,指针依然存在,那调用销毁方法有何意义?

评论列表

  • 加载数据中...

编写评论内容

2670459508
发表于 2021-1-1

明白了,调用销毁方法只是将对象还给容器。。。

评论列表

  • 加载数据中...

编写评论内容

明明哦
发表于 2021-1-1

搬砖的。。

评论列表

  • 加载数据中...

编写评论内容
LoginCan Publish Content