我们在使用maven开发一些项目的时候需要知道当前的版本状态,但版本状态储存在pom.xml文件中,可以采用以下2种方式进行获取:
1、 采用xml解析的方式去获取pom文件的{project.version}变量,但工作量会有点大;
2、 采用maven提供的方案:在自定义的资源文件( properties )中放置 pom.xml 设置的变量,在构建之后就会自动将变量替换成为真实值。
步骤
1、 在src/main/resources中新建app.properties文件并设置如下内容:
app.version=${project.version}
2、 配置pom文件
<build>
       <resources>
           <resource>
               <directory>src/main/resources</directory>
               <filtering>true</filtering>
           </resource>
       </resources>
</build>
3、 实现对app.version的读取
 public static String getAppVersion() {
        if (null == appVersion) {
            Properties properties = new Properties();
            try {
                properties.load(AppUtils.class.getClassLoader().getResourceAsStream("app.properties"));
                if (!properties.isEmpty()) {
                    appVersion = properties.getProperty("app.version");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return appVersion;
    }
4、 测试获取版本信息
 @Test
   public void testApplicationVersion(){
       String version = AppUtils.getAppVersion();
       log.info("app version:'{}'",version);
   }
参考:http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html