在Eclipse中运行时从pom获取maven项目版本和工件ID

swh*_*ite 28 java pom.xml maven-3

当我遇到这个问题时,我正在查找如何从maven pom或manifest获取应用程序名称(工件id)和版本.在运行时获取Maven工件版本.

对我来说,上述工程时,我包的项目,但我似乎无法得到任何工作,当我尝试运行使用eclipse的程序.我在构建时尝试使用.properties方法,因为我认为它不依赖于包,但我仍然没有得到结果.如果有人有这个问题的想法或解决方案,将不胜感激.

我的最后一次尝试如下.这在打包(使用)时使用清单,并在eclipse中运行时尝试获取.properties文件.

String appVersion = getClass().getPackage().getImplementationVersion();
    if(appVersion == null || "".equals(appVersion)) {
        appVersion = Glob.getString(appVersion);
        if(appVersion == null || "".equals(appVersion)) {
            System.exit(0);
        }
    }
Run Code Online (Sandbox Code Playgroud)

cod*_*lus 77

创建属性文件

src/main/resources/project.properties
Run Code Online (Sandbox Code Playgroud)

以下内容

version=${project.version}
artifactId=${project.artifactId}
Run Code Online (Sandbox Code Playgroud)

现在打开maven资源过滤

  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
  </resource>
Run Code Online (Sandbox Code Playgroud)

以便将此文件处理成

target/classes/project.properties
Run Code Online (Sandbox Code Playgroud)

与此类似的一些内容

version=1.5
artifactId=my-artifact
Run Code Online (Sandbox Code Playgroud)

现在你可以阅读这个属性文件来获得你想要的东西,这应该每次都有效.

final Properties properties = new Properties();
properties.load(this.getClassLoader().getResourceAsStream("project.properties"));
System.out.println(properties.getProperty("version"));
System.out.println(properties.getProperty("artifactId"));
Run Code Online (Sandbox Code Playgroud)

  • 我需要使用`properties.load(this.getClass().getClassLoader().getResourceAsStream("project.properties"));`以使其工作 (16认同)
  • 我确实按照你的步骤但它不起作用.你能看看我的问题http://stackoverflow.com/questions/37490162/get-maven-properties-at-build-time#37490162 (2认同)
  • 如果您从 public static void main() 尝试它,“this”将无法作为静态方法使用。因此,您需要将其与包含 public static void main() 的类名一起使用,如下所示:`properties.load(&lt;Main Class Name&gt;.class.getResourceAsStream("project.properties"));` (2认同)
  • 对于 Spring Boot 应用程序,请考虑默认占位符已重新配置:使用 @ - so @project.version@ ​​而不是 ${project.version}。请参阅/sf/answers/2624401811/ (2认同)