如何在无POM的Maven Tycho构建RCP应用中运行时展示版本信息
无POM Tycho构建下RCP版本信息传递到「关于」板块的标准方案
核心思路
利用Tycho的内置资源过滤机制,将父POM中手动定义的版本注入到Bundle的运行时资源中,无需复杂插件配置。
步骤1:父POM中统一版本定义
在父POM的<properties>里明确版本属性(如果尚未定义):
<properties> <app.version>1.2.0-SNAPSHOT</app.version> </properties>
可以直接把父POM的<version>也设为这个值,保证版本统一:<version>${app.version}</version>
步骤2:配置Bundle的资源过滤
在需要获取版本的RCP Bundle模块(无pom.xml)中:
- 创建模板属性文件
src/main/resources/version.properties.template,内容如下:
app.version=${app.version}
- 修改该Bundle的
build.properties,添加资源过滤配置:
# 指定需要替换占位符的模板文件 filteredResources=src/main/resources/version.properties.template # 输出路径,确保生成的文件能被打包到最终bundle中 outputDirectory=target/classes
Tycho构建时会自动用父POM中的app.version值替换模板里的占位符,生成version.properties到target/classes目录。
步骤3:运行时读取版本
在RCP「关于」页面的实现代码中,读取生成的属性文件:
public String getAppVersion() { Properties versionProps = new Properties(); try (InputStream is = getClass().getResourceAsStream("/version.properties")) { versionProps.load(is); return versionProps.getProperty("app.version", "未知版本"); } catch (IOException e) { return "未知版本"; } }
更简洁的替代方案:直接读取Bundle版本
如果你的Bundle版本与父POM版本完全同步(Tycho默认会从父POM继承版本到Bundle-Version),可以跳过资源文件生成,直接通过OSGi API获取版本:
import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.Version; // 在关于页面代码中 Bundle bundle = FrameworkUtil.getBundle(YourAboutDialog.class); Version version = bundle.getVersion(); String versionStr = String.format("%d.%d.%d%s", version.getMajor(), version.getMinor(), version.getMicro(), version.getQualifier().isEmpty() ? "" : "-" + version.getQualifier());
为什么properties-maven-plugin不适用?
properties-maven-plugin是标准Maven插件,而Tycho的无POM Bundle模块遵循OSGi构建规范,构建流程由Tycho插件主导,标准Maven插件的配置无法直接在无POM模块中生效,因此会出现整合问题。
内容的提问来源于stack exchange,提问作者umpapa
相关产品推荐
相关产品推荐

