How to Get Maven Project Version From Java Method as Like at Pom

8.3k Views Asked by At

I can get some variable's values from my pom file i.e.:

${project.version}

and I am developing a custom maven plugin and I can set it with expressions however I don't want it. How can I get it in a Java method as like my pom file?

PS: System.getProperty("project.version") doesn't work, I should find a generic solution because I will use it at other things too i.e. getting bamboo build number etc.

4

There are 4 best solutions below

0
On BEST ANSWER

I've created a properties file and indicated at my pom:

<build>
    <resources>
        <resource>
            <directory>src/main/resources/</directory>
            <filtering>true</filtering>
        </resource>
 ...
</build>
1
On

I did this in my web project by using the maven-war-plugin to inject the version into the manifest, then getting it from there with some Java code. I see no reason why something similar can't be done with a non-web project.

E.g.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    version>2.4</version>
    <configuration>
        <archive>
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

Then in Java (excluding error handling):

public String getMavenVersion(ServletContext ctx) {
    String appServerHome = ctx.getRealPath("/");
    File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");

    Manifest mf = new Manifest();

    mf.read(new FileInputStream(manifestFile));

    Attributes atts = mf.getMainAttributes();

    return atts.getValue("Implementation-Build");
}
0
On

Are you asking if you can pass parameters in as a class or some other structure all at once?

If so, you can pass them in as a System Properties file using the -D arguement and use System.getProperties() to get them out on the other side. Google around, a lot of project support reading settings in like this, there's a lot of example code out there.

0
On
@Component
MavenProject project;

...

    project.getVersion()

Assuming you are using the Java 5 annotations