Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

Is there a way to use maven property in Java class during compilation

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}"
    }

}
question from:https://stackoverflow.com/questions/11740618/is-there-a-way-to-use-maven-property-in-java-class-during-compilation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...