Maven 2: How to package current project version in a WAR file?

后端 未结 5 1649
[愿得一人]
[愿得一人] 2021-02-06 10:14

I am using Maven 2 to build my Java project and I am looking for a way to present the current version number of the pom.xml to the user (using a Servlet or JSP for example).

5条回答
  •  囚心锁ツ
    2021-02-06 10:44

    Of course, variables can be included in resources and filtered wih the maven-resource-plugin by adding a tag to the POM and set it to true like this:

    ...
    
      src/main/resources
      true
    
    ...
    

    And you could use this feature to read and replace ${version} (or ${project.version} or ${pom.version} which are equivalent) in a properties file for example.

    But, actually, the information you are looking for is available by default by Maven (unless you configured it to not do so which is very unlikely if you are not aware of that). If you unpack the WAR that Maven created for you and take a look at it you would see the following:

    |-- META-INF
    |   |-- MANIFEST.MF
    |   `-- maven
    |       `-- com.mycompany.app
    |           `-- my-app
    |               |-- pom.properties
    |               `-- pom.xml
    |-- WEB-INF
    |   |-- classes
    |   |   |-- ...
    |   |-- lib
    |   |   |-- ...
    |   `-- web.xml
    |-- bar.jsp
    |-- ...
    `-- foo.jsp
    

    As you can see, you'll find a pom.xm and pom.properties file in it and, as explained in How do I add resources to my JAR?:

    The pom.xml and pom.properties files are packaged up in the JAR so that each artifact produced by Maven is self-describing and also allows you to utilize the metadata in your own application if the need arises. One simple use might be to retrieve the version of your application. Operating on the POM file would require you to use some Maven utilities but the properties can be utilized using the standard Java API and look like the following:

    #Generated by Maven
    #Tue Oct 04 15:43:21 GMT-05:00 2005
    version=1.0-SNAPSHOT
    groupId=com.mycompany.app
    artifactId=my-app
    

    So you could just load this pom.properties file with something like this (pseudo code):

    // Retrieve resource
    InputStream is = getClass().getResourceAsStream( "/META-INF/maven/com.mycompany.app/my-app/pom.properties" );
    
    // Do something with the resource, e.g. load it as Properties
    Properties prop = new Properties();
    prop.load(is);
    String version = prop.getProperty("version");
    

提交回复
热议问题