Apache Maven Access Maven informations in code Keeping a properties file in sync using maven's property filtering mecanism


Example

As this documentation explains,

Sometimes a resource file will need to contain a value that can only be supplied at build time. To accomplish this in Maven, put a reference to the property that will contain the value into your resource file using the syntax ${<property name>}. The property can be one of the values defined in your pom.xml, a value defined in the user's settings.xml, a property defined in an external properties file, or a system property.

As an example, let's create a simple info.txt in src/main/resources containing the pom version and the build time.

  1. create a src/main/resources/info.txt with the following content:

    version=${pom.version} build.date=${timestamp}

  2. ask Maven to expand the properties by setting filtering to true:

     <build>
         <resources>
             <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
             </resource>
         </resources>
     </build>
    
  3. with that, the version will be updated, but unfortunately a bug within Maven prevents the ${maven.build.timestamp} property from getting passed to the resource filtering mechanism (more info here). So, let's create a timestamp property as a workaround ! Add the following to the pom's properties:

     <properties>
         <timestamp>${maven.build.timestamp}</timestamp>
         <maven.build.timestamp.format>yyyy-MM-dd'T'HH:mm</maven.build.timestamp.format>  
     </properties>
    
  4. run maven, you should find a info.txt in target/classes with a content like:

     version=0.3.2
     build.date=2017-04-20T13:56