Reputation: 158051
I have two versions in my projects.
These should of course be the same, but sometimes I forget to change one or the other.
Is there a good way to define this version only once and have it used by both maven and code during runtime?
Upvotes: 3
Views: 198
Reputation: 48065
This is some code that I usually use when I want the version specified in the pom file.
private final static String GROUP_ID = "my.group";
private final static String ARTIFACT_ID = "my-artifact";
private String getVersion() {
String propFileName = "META-INF/maven/" + GROUP_ID + "/" + ARTIFACT_ID + "/pom.properties";
Properties properties = new Properties();
String version = "n/a";
try {
InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propFileName);
if (inStream != null) {
properties.load(inStream);
version = properties.getProperty("version", "n/a");
}
} catch (IOException e) { }
return version;
}
And as mthmulders says in his answer, this file does only exist in a packaged project (in the final war/jar/any, not in the working directory).
Upvotes: 1
Reputation: 9705
When you package your application using Maven, Maven will generate a directory META-INF/maven/<groupId>/<artifactId>/pom.properties
. That file contains the version of your project according to the POM, and you could load that file from the JAR file on runtime in order to read your version number.
Only thing is, this file does only exist in a packaged project (be it a JAR, a WAR or an EAR). You might want to write some fallback mechanism for when you are running the code from your workbench.
Upvotes: 2
Reputation: 4113
http://www.sonatype.com/books/mvnref-book/reference/resource-filtering-sect-description.html
Have a look at this, you should have a properties file, which has a certain property which refers to the version number. And using filtering you can set the version same both in maven artifact and application.
Upvotes: 4