外部jar中的类在加载Resource时抛出异常

问题描述 投票:0回答:1

嗨,我正在开发一个依赖外部jar的Maven项目,该jar有一个类ConfigLoader,后面有loader()方法。

public class ConfigLoader {
   public void initialize() {
      loader();
   }
   private static void loader() {
      URL configURL = ConfigLoader.getClass().getResource("runtimeConfiguration.xml");
      //some other method calls to which configURL is an argument.
   }
   //other methods of ConfigLoader class
}

目录结构是这样的 -

src
|...main
|.......java
|.......resources
|................dev
|................prod

dev和prod都有一个名为runtimeConfiguration.xml的文件,而使用该类的代码是

public class Application {
   private Application application;
   public static void main(String []args){
      application = new Application();
      application.invokeConfigLoader();
      //additional code
   }
   private void invokeConfigLoader() {
      configLoader.initialize(); 
   }
}

我得到的错误是

could not find: runtimeConfiguration.xml
and the exception is thrown at the getResource() line in the class from jar.

我尝试将dev文件夹添加到classpath但仍然是相同的错误。我想从linux终端运行这个代码,我从trunk目录中给出的命令(所有我的exernal jar和资源文件夹位于maven构建之后)是 -

java -cp /resources/dev/*:configuration-loader.jar 

我正在使用intelliJ 2017.2并尝试将资源/ dev文件夹添加为模块依赖项,但我继续得到相同的错误。资源文件夹通过项目结构设置添加为库。我试图搜索很多,但没有发现任何问题。请帮助我,因为我是这个基于环境的开发的新手。谢谢!

java maven intellij-idea jar classloader
1个回答
0
投票

ConfigLoader.getClass().getResource("runtimeConfiguration.xml");将尝试从定义ConfigLoader的同一个包中获取runtimeConfiguration.xml,而不是从类路径的根目录获取。尝试将/附加到runtimeConfiguration.xml

这应该适用于ConfigLoader.getClass().getResource("/runtimeConfiguration.xml");ConfigLoader.getClass().getResource("/dev/runtimeConfiguration.xml");,具体取决于您如何向类路径添加资源。

有关更多信息,请参阅javadoc

© www.soinside.com 2019 - 2024. All rights reserved.