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

后端 未结 5 1660
[愿得一人]
[愿得一人] 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:28

    My solution for the standard Maven WAR plugin

    Add a resources tag to you build section which enables filtering (aka "search and replace"):

    
        
            
                src/main/resources
                true
            
        
    ....
    
    

    Then in your src/main/resources add a version.properties file containing any filter variables that matches one of the standard maven build variables (you can also use filtering feature to load your own custom variables):

    pom.version=${pom.version}
    

    Now when you do a "maven package" or a maven install it will copy the version.properties file into the WEB-INF/classes and do a search and replace to add the pom version into the file.

    To get at this with Java use a class such as:

    public class PomVersion {
        final private static Logger LOGGER = LogManager.getLogger(PomVersion.class);
    
        final static String VERSION = loadVersion();
    
        private static String loadVersion() {
            Properties properties = new Properties();
            try {
                InputStream inStream = PomVersion.class.getClassLoader().getResourceAsStream("version.properties");
                properties.load(inStream);
            } catch (Exception e){
                LOGGER.warn("Unable to load version.properties using PomVersion.class.getClassLoader().getResourceAsStream(...)", e);
            }
            return properties.getProperty("pom.version");
        }
    
        public static String getVersion(){
            return VERSION;
        }
    }
    

    Now you can just call PomVersion.getVersion() to put the version number of the pom file into the page. You can also have the WAR file be given the same number by using a filter variable in the finalName within the pom.xml:

    
        my-killer-app-${pom.version}
    ...
    
    

    so now if you set your application version in your pom to be 01.02.879:

    
        4.0.0
        com.killer.app
        my-killer-app
        war
        This App Will Rule The World
        01.02.879
        ...
    
    

    when you do an "mvn install" the war file name include the version number also:

    my-killer-app-01.02.879.war
    

    finally if you use Spring heavily such as with SpringMVC/SpringWebFlow you can make a singleton service bean which uses that class to avoid having to reference the low level class by name:

    @Service("applicationVersion")
    public class ApplicationVersion {
        final static String VERSION = PomVersion.getVersion();
    
        public String getVersion() {
            return VERSION;
        }
    }
    

提交回复
热议问题