BeanFactory not initialized or already closed

Exception in thread "main" java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

遇到这种错误的时候,看到网上很多人都是建议这么解决:

BeanFactory没有实例化或者已经关闭了,其实产生错误的原因很简单,在写:

ApplicationContext ctx = new ClassPathXmlApplicationContext();

时,没有指定配置文件,Spring实例化BeanFactory的时候是默认到classPath下面查找名为applicationContext.xml的文件的,但是呢,你又没有指定,所以出现了这个错误。

这就是错误的原因,在括号写上配置文件名就行了。

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

这样的话就不会出现这样的错误了。

但是还是有其他错误原因的:

当你的控制层controller文件有重名的时候也会报这个错误。

博客地址迁移,博客目前更新在 csdn: https://blog.csdn.net/H_Rhui
原文地址:https://www.cnblogs.com/hui-run/p/5799155.html