解决 Spring Cloud 中 context has been closed already

分手后的思念是犯贱 2023-02-27 12:29 137阅读 0赞

context has been closed already 解决方案

报错代码

有这样一段代码,在运行中可能会发生 context has been closed already 错误,且一旦发生,以后每次运行到这必定出错。

  1. @Component
  2. public class SpringContextUtil implements ApplicationContextAware {
  3. private static ApplicationContext context = null;
  4. @Override
  5. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  6. ApplicationContextExt.context = applicationContext;
  7. }
  8. /** * 可以通过该静态方法从 Spring 上下文中获取想要的 Bean。 */
  9. public static <T> T getBean(Class<T> cls) {
  10. if (context == null)
  11. throw new IllegalStateException("no application context aviliable.");
  12. try {
  13. return (T) context.getBean(cls); // 这里报错!!!
  14. } catch (BeansException e) {
  15. throw new RuntimeException(e);
  16. }
  17. return (T) null;
  18. }
  19. }

原因分析

但是类路径中包含 spring-cloud-context.jar 时,因为 ContextRefresher 这个类会在上下文刷新时关闭旧的上下文,导致这个静态类里的上下文是已经关闭的,因此会产生这个错误。

触发探索

寻找直接原因,发现依赖的某个jar里监听了MQ一个通知,听到要刷新的消息时,便会刷新上下文导致该现象。

发表评论

表情:
评论列表 (有 0 条评论,137人围观)

还没有评论,来说两句吧...

相关阅读