Using Maven for building my project, can I include the version in a specific file?

108 Views Asked by At

I have a file that I'd like to show the version on top. For example, if my POM.xml is on version 1.1-SNAPSHOT, I like this file also include 1.1-SNAPSHOT on top of it (or somewhere close to top). When I release, I want the version change to 1.1 (i.e. the same as POM.xml). I could write a bash script to do that before and after each Maven build, but I wonder if Maven can do that.

I see buildnumber Maven plugin may do something similar (eg. Puts the build number in manifest of a jar file). But can Maven put the "version" into a "specific file" that I specify?

1

There are 1 best solutions below

4
bmargulies On

You need to use the maven-resources-plugin for filtering. Instead of putting into the file, consider the following, which makes it available to your code.

You need to put a .properties file into src/main/resources, and then enable filtering.

Here's an example for some tests:

In the pom:

    <build>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
            <filtering>true</filtering>
        </testResource>
    </testResources>

In src/test/resources, a file test-config.properties:

project.version=${project.version}

And then the usual Java code to open a file from the classpath and feed it into the 'properties' class.

 public static void beforeClass() throws Exception {
    URL configPropUrl = Resources.getResource(AbstractIT.class, "test-config.properties");
    Properties props = new Properties();
    try (InputStream propStream = configPropUrl.openStream()) {
        props.load(propStream);
    }

    basedir = props.getProperty("basedir");
    projectVersion = props.getProperty("project.version");

}