I just want to use maven placeholder in my Java class at compile time in order to reduce duplication.
Something like that:
pom.xml
<properties> <some.version>1.0</some.version> </properties>
SomeVersion.java
package some.company; public class SomeVersion { public static String getVersion() { return "${some.version}" } }
Use the properties-maven-plugin to write specific pom properties to a file at compile time, and then read that file at run time.
Maven properties are value placeholders, like properties in Ant. Their values are accessible anywhere within a POM by using the notation ${X}, where X is the property. Or they can be used by plugins as default values, for example: In your case you have defined properties as version of java.
User-defined properties can be referenced in a POM, or they can be used to filter resources via the Maven Resource plugin.
simply create file app.properties in src/main/resources with content like this
application.version=${project.version}
then enable maven filtering like this
<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources>
That's all - in app code just read properties file
ClassPathResource resource = new ClassPathResource( "app.properties" ); p = new Properties(); InputStream inputStream = null; try { inputStream = resource.getInputStream(); p.load( inputStream ); } catch ( IOException e ) { LOGGER.error( e.getMessage(), e ); } finally { Closeables.closeQuietly( inputStream ); }
and provide method like this
public static String projectVersion() { return p.getProperty( "application.version" ); }
Even though it's not a very nice solution it is possible with the default maven resource plugin.
First you need to specify the resource plugin.
<project> <build> <!-- Configure the source files as resources to be filtered into a custom target directory --> <resources> <resource> <directory>src/main/java</directory> <filtering>true</filtering> <targetPath>../filtered-sources/java</targetPath> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> </project>
Afterwards you will need to change the 'default' configuration of the compiler plugin.
<project> <build> <!-- Overrule the default pom source directory to match our generated sources so the compiler will pick them up --> <sourceDirectory>target/filtered-sources/java</sourceDirectory> </build> </project>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With