当我遇到这个问题Get Maven artifact version at runtime时,我正在查找如何从maven pom或manifest中获取应用程序名称(工件ID)和版本。
当我打包项目时,上面的工作对我来说,但是当我尝试使用eclipse运行程序时,我似乎无法工作。我在构建时尝试使用.properties方法,因为我认为它不依赖于包,但我仍然没有得到结果。如果有人对这个问题有任何想法或解决方案,我们将不胜感激。
我的最后一次尝试如下。这在打包(使用)时使用清单,并在eclipse中运行时尝试获取.properties文件。
String appVersion = getClass().getPackage().getImplementationVersion();
if(appVersion == null || "".equals(appVersion)) {
appVersion = Glob.getString(appVersion);
if(appVersion == null || "".equals(appVersion)) {
System.exit(0);
}
}
答案 0 :(得分:66)
创建属性文件
src/main/resources/project.properties
以下内容
version=${project.version}
artifactId=${project.artifactId}
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
以便将此文件处理为
target/classes/project.properties
有一些与此相似的内容
version=1.5
artifactId=my-artifact
现在你可以阅读这个属性文件来获得你想要的东西,这应该每次都有效。
final Properties properties = new Properties();
properties.load(this.getClassLoader().getResourceAsStream("project.properties"));
System.out.println(properties.getProperty("version"));
System.out.println(properties.getProperty("artifactId"));
答案 1 :(得分:0)
maven 4的一个简单解决方案是在您的程序包中添加一个VersionUtil
静态方法:
package my.domain.package;
public class VersionUtil {
public static String getApplicationVersion(){
String version = VersionUtil.class.getPackage().getImplementationVersion();
return (version == null)? "unable to reach": version;
}
}
问题是,您需要在项目的pom中使用这个“ mave-war-plugin”,说您想添加addDefaultImplementationEntries
:
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
...
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
...
然后从代码中的某个位置调用VersionUtil.getApplicationVersion()
。