Context has been closed already solution
Error code
With such a piece of code, the context has been closed already
error may occur during running, and once it occurs, it will make an error every time it runs in the future.
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextExt.context = applicationContext;
}
/**
* This static method allows you to retrieve the desired bean from the Spring context.
*/
public static <T> T getBean(Class<T> cls) {
if (context == null)
throw new IllegalStateException("no application context aviliable.");
try {
return (T) context.getBean(cls); // Wrong!
} catch (BeansException e) {
throw new RuntimeException(e);
}
return (T) null;
}
}
Cause analysis
However, when spring cloud context. Jar
is included in the classpath, because the contextrefresher
class will close the old context when the context is refreshed, so that the context in the static class has been closed, so this error will occur.
Trigger exploration
Find out the direct reason. Find out that a jar that you depend on listens to a notification from MQ. When you hear the message to be refreshed, you will refresh the context, which leads to this phenomenon.
Read More:
- How to Fix Error when integrating spring cloud openfeign with spring cloud Alibaba
- Gateway Error: Cannot resolve org.springframework.cloud:spring-cloud-starter-gateway:unknown
- How to Solve Error Swift 4 Expression type ‘@value CGRect’ is ambiguous without more context
- [Solved] Spring cloud introduces zuul dependency error
- How to Solve AOP error in Spring
- [Solved] Spring cloud load balancing, error: no instances available for localhost
- How to Solve Spring MVC upload file error
- How to Solve the jump error after Spring Security Login
- [Solved] Spring cloud config server can’t parse the YML file of the remote warehouse, and it will also report an error
- Spring cloud Eureka error creating bean with name
- Centos7 hive started to report an error. There is no route to the host. The firewall has been closed
- [Solved] Stream Error: stream has already been operated upon or closed
- Docker: How to Enter the Closed Container and View the Logging
- How to Solve SSH Login Error: WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
- Spring boot uses configuration interface webmvcconfigurer to solve cross domain problems
- How to Solve Error: Type mismatch: cannot convert from Object to Car
- How to Solve Error: Cannot find the declaration of element ‘beans’.
- [Solved] Springcloud Add gateway to Startup Error: Exception encountered during context initialization – cancelling refresh
- How to Solve forEach cannot exit the loop Issue