我正在尝试为我的项目设置配置位置,但我不断收到以下错误:
java.io.FileNotFoundException:类路径资源 [main/resources/app-context.xml] 无法打开,因为它不 存在
我的项目是这样设置的:
我的代码设置为:
ApplicationContext context = new ClassPathXmlApplicationContext(configLocation: "main/resources/app-context.xml");
我该如何解决这个问题?
直接放在
src/main/java
下的内容位于默认包中,位于类路径的根目录下。对于放在 src/main/resources
下的资源也是如此:它们最终位于类路径的根部。
所以资源的路径是
app-context.xml
,而不是main/resources/app-context.xml
。
我们也可以尝试这个解决方案
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");
在此,spring 自动在类路径本身中查找类
试试这个:
ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");
文件位置/路径必须相对于您的类路径位置。如果资源目录位于您的类路径中,您只需要“app-context.xml”作为文件位置。
这对我有用
ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");
对于 Eclipse - 跟随路径
Build path -> Configure build path -> go to sources -> add folder
标记包含 XML 文件的资源文件夹。
现在,如果您尝试运行它就会运行得很好。
您可以使用下面的内容来阅读资源。它将提供输入流。
InputStream in = MyClass.class.getClassLoader().getResourceAsStream("files.properties");
对于我的情况,我正在运行一些测试并面临这些错误:
java.lang.IllegalStateException: Unable to load JSON from class path resource [com/springproject/cashcard/expected.json]
and
java.io.FileNotFoundException: class path resource [com/springproject/cashcard/expected.json] cannot be opened because it does not exist
所以,我注意到
test/resources
模块丢失了。因此,我将其添加到类路径中,添加了 JSON 文件并重建了项目,结果成功了。