我們在使用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的讀取
1 public static String getAppVersion() { 2 if (null == appVersion) { 3 Properties properties = new Properties(); 4 try { 5 properties.load(AppUtils.class.getClassLoader().getResourceAsStream("app.properties")); 6 if (!properties.isEmpty()) { 7 appVersion = properties.getProperty("app.version"); 8 } 9 } catch (IOException e) { 10 e.printStackTrace(); 11 } 12 } 13 return appVersion; 14 }
4. 測試獲取版本信息
1 @Test 2 public void testApplicationVersion(){ 3 String version = AppUtils.getAppVersion(); 4 log.info("app version:'{}'",version); 5 }
參考:http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html