1. 介绍
作为应用程序尤其是框架和库的作者,常常需要了解运行程序的版本:
- 作为 bug 报告的关键信息
- 在应用启动的时候打印版本带来更加清晰的信息展示
例如下面是一个ActFramework应用项目启动时的 Banner:

针对这样的需求,我开发了一个小小的工具 (9K jar 包) 来帮助大家轻松方便地管理和访问应用/库/框架在运行时的版本信息.
2. 安装
该工具已经发行到了 maven 中央库, 可以在你的 pom 文件中加入一下依赖:
<dependency> <groupId>org.osgl</groupId> <artifactId>osgl-bootstrap</artifactId> <version>${osgl-bootstrap.version}</version> </dependency>
3. 准备应用/库的版本信息
作为应用/库的开发者,你需要将软件的版本信息按照下面的方式加入到项目当中:
假设你的产品的包名是 `org.mrcool.swissknife`,你需要将一个名为 .version
的文件存放在 src/resources/org/mrcool/swissknife
目录里, 文件的内容大致如下:
# artifact is optional, if not provided the package name will be used artifact=<delivery-name> # version is mandatory, if not provided then UNKNOWN version will be returned version=<the project version> # build number is optional, if not provided then empty string will be used build=<SCM build number, e.g. git hash>
因为不想每次发布新版都手工编辑这个文件,我们可以利用 maven 的资源过滤功能, 将上面的文件定义为一下内容:
artifact=${project.artifactId} version=${project.version} ## build number is optional build=${buildNumber}
同时在 pom 文件里面加上资源过滤插件:
<resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/.version</include> </includes> </resource> </resources>
另外如果需要上面的 buildNumber
的话,还需要加上 buildnumber maven plugin 插件:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>buildnumber-maven-plugin</artifactId> <version>${buildnumber-maven-plugin.version}</version> <executions> <execution> <phase>validate</phase> <goals> <goal>create</goal> </goals> </execution> </executions> <configuration> <shortRevisionLength>4</shortRevisionLength> </configuration> </plugin>
这样就可以了.只要运行 mvn package
,生成出来的 jar 文件里会包含足够的版本信息.
4. 在运行时访问版本信息
假如某个库已经按照上面的方式加入版本信息到 jar 文件当中了,使用库的应用可以利用 osgl-bootstrap 里面的 Version
类来访问该库的版本, 如下面代码所示:
Version version1 = Version.of(org.mrcool.swissknife.SwissKnife.class); System.out.println(version1.getPackage()); // print `org.mrcool.swissknife` System.out.println(version1.getArtifactId()); // print `swissknife` System.out.println(version1.getProjectVersion()); // print `1.0` System.out.println(version1.getBuildNumber()); // print `ebf1` System.out.println(version1.getVersion()); // print `r1.0-ebf1` System.out.println(version1); // print `swissknife-r1.0-ebf1` // Another method to get Version info Version version2 = Version.of("org.mrcool.swissknife.db"); // If a certain library's version is SNAPSHOT, e.g. 1.0-SNAPSHOT, // then the version tag is decorated with `v` instead of `r`: System.out.println(version2.getProjectVersion()); // print `1.0-SNAPSHOT` System.out.println(version2.getBuildNumber()); // print `51b9` System.out.println(version2.getVersion()); // print `v1.0-SNAPSHOT-51b9` System.out.println(version2); // print `swissknife-v1.0-SNAPSHOT-ebf1`
如果访问到的库正好没有版本信息也不会出打错, Version
会返回一个 Unknown
版本实例给调用方.
最后说明一点, 该软件已经放在码云上了:
http://git.oschina.net/osglworks/java-osgl-bootstrap