【问题标题】:Maven configuration of dependency (jar)Maven的依赖配置(jar)
【发布时间】:2010-11-18 23:49:04
【问题描述】:

我有一个依赖于“dep.jar”的 java 应用程序“app”。 “dep.jar”有一个配置文件——“conf.properties”,它被复制并打包到dep.jar中。问题是在“app”运行过程中,找不到“conf.properties”。

我应该如何指定“conf.properties”的路径(在“dep.jar”的代码中)以便在运行时找到它?

罗南。

更具体地说:我不需要文件作为 InputStream,但我需要文件的路径。特别是我需要它来配置 JMX:

HashMap<String, Object> env = new HashMap<String, Object>();
...
env.put("jmx.remote.x.password.file", "password.properties");

其中“password.properties”是运行时需要的配置文件。此代码在 jar 文件中,而不是在应用程序中。将“password.properties”放入资源后位于jar文件中,但如何在运行时访问它?

【问题讨论】:

    标签: configuration maven-2 dependencies


    【解决方案1】:

    这取决于您尝试加载文件的方式。如果您使用Class.getResourceAsStream(),则路径相对于您调用getResourceAsStream() 的类。要进入“根”,请在文件名前添加"/"

    InputStream in = Class.class.getResourceAsStream("/conf.properties");
    

    [编辑] 如果您需要文件的路径(即使它在 JAR 中),您可以使用返回 URL 的getResource()。使用new File(url.toURI()) 从 URL 中获取路径。

    【讨论】:

      【解决方案2】:

      你在 dep.jar 中哪里定义 conf.properties?

      如果项目是 jar 项目(没有声明的包装元素或 jar

      如果您的 conf.properties 定义在“dep”项目的 src/main/resources 文件夹中或下面,它将被输出到最终的 jar 中。

      例如,定义在的文件:

      src/main/resources/config/conf.properties
      

      会被打包在jar里

      config/conf.properties
      

      假设您有一个类 com.foo.Bar,并且您想通过以下方式访问它的属性文件:

      InputStream stream = Bar.getClass().getResourceAsStream("conf.properties");
      

      那么文件 conf.properties 将被定义在文件夹下:

      src/main/resources/com/foo/conf.properties
      

      如果您想从 jar 的根目录访问资源流,您可以按照 Aaron 的回答建议:

      InputStream stream = Bar.getClass().getResourceAsStream("/conf.properties");
      

      资源将在

      中定义
      src/main/resources/conf.properties
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-12
        • 1970-01-01
        • 2017-05-20
        • 1970-01-01
        • 2011-05-05
        • 2015-05-12
        相关资源
        最近更新 更多