解决 Spring Cloud 中 context has been closed already
context has been closed already 解决方案
报错代码
有这样一段代码,在运行中可能会发生 context has been closed already
错误,且一旦发生,以后每次运行到这必定出错。
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextExt.context = applicationContext;
}
/** * 可以通过该静态方法从 Spring 上下文中获取想要的 Bean。 */
public static <T> T getBean(Class<T> cls) {
if (context == null)
throw new IllegalStateException("no application context aviliable.");
try {
return (T) context.getBean(cls); // 这里报错!!!
} catch (BeansException e) {
throw new RuntimeException(e);
}
return (T) null;
}
}
原因分析
但是类路径中包含 spring-cloud-context.jar
时,因为 ContextRefresher
这个类会在上下文刷新时关闭旧的上下文,导致这个静态类里的上下文是已经关闭的,因此会产生这个错误。
触发探索
寻找直接原因,发现依赖的某个jar里监听了MQ一个通知,听到要刷新的消息时,便会刷新上下文导致该现象。
还没有评论,来说两句吧...