我们在使用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