Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

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

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.

The above works for me when I package the project but I can't seem to get anything to work when I try to run the program using eclipse. I tried using the .properties method when building since I assumed that is not package dependent but I am still not getting a result. If anyone has an idea or solution to this problem it would be greatly appreciated.

My last attempt is below. This uses the manifest when packaged(which works) and trying to get the .properties file when running in eclipse.

String appVersion = getClass().getPackage().getImplementationVersion();
    if(appVersion == null || "".equals(appVersion)) {
        appVersion = Glob.getString(appVersion);
        if(appVersion == null || "".equals(appVersion)) {
            System.exit(0);
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...