Getting maven project version and artifact ID from pom while running in Eclipse

后端 未结 2 440
-上瘾入骨i
-上瘾入骨i 2020-12-08 09:43

I was looking up how to get the application name(artifact id) and version from maven pom or manifest when I came across this question Get Maven artifact version at runtime.<

相关标签:
2条回答
  • 2020-12-08 10:32

    Create a property file

    src/main/resources/project.properties
    

    with the below content

    version=${project.version}
    artifactId=${project.artifactId}
    

    Now turn on maven resource filtering

      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    

    so that this file is processed into

    target/classes/project.properties
    

    with some content similar to this

    version=1.5
    artifactId=my-artifact
    

    Now you can read this property file to get what you want and this should work every time.

    final Properties properties = new Properties();
    properties.load(this.getClassLoader().getResourceAsStream("project.properties"));
    System.out.println(properties.getProperty("version"));
    System.out.println(properties.getProperty("artifactId"));
    
    0 讨论(0)
  • 2020-12-08 10:39

    An easy solution with maven 4 is now to add a VersionUtil static method in your package:

    package my.domain.package;
    public class VersionUtil {
      public static String getApplicationVersion(){
        String version = VersionUtil.class.getPackage().getImplementationVersion();
        return (version == null)? "unable to reach": version;
      }
    }
    

    The thing is you need this ´mave-war-plugin´ in the project's pom, saying you want to add addDefaultImplementationEntries:

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
         ...
          <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        ...
    

    Then call the VersionUtil.getApplicationVersion() from some place in your code.

    0 讨论(0)
提交回复
热议问题