java读取jar包中的程序版本号
java程序打包后的jar如下图所示:可以看到META-INF目录下的三处均可以读取到程序的版本号:程序版本号字段 即 Implementation-Version2、build-info.properties这个是依赖maven插件 git-commit-id-plugin,具体在我之前的博文都有详细讲述。这里就不再赘述~路径是maven/{基本package名}/{服务名},读取pom.xml
·
java程序打包后的jar如下图所示:
可以看到META-INF目录下的三处均可以读取到程序的版本号:
- MANIFEST.MF
- build-info.properties
- maven/xxx/xx/pom.properties 或 pom.xml
一、MANIFEST.MF
程序版本号字段 即 Implementation-Version
Manifest-Version: 1.0
Implementation-Title: task-notification
Implementation-Version: 2.4.2
Archiver-Version: Plexus Archiver
Built-By: xxx
Implementation-Vendor-Id: com.xxx.platform
Spring-Boot-Version: 2.2.4.RELEASE
Implementation-Vendor: Xxx Education Technology Co, Inc.
Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.xxx.platform.notification.NotificationApplicatio
n
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Created-By: Apache Maven 3.5.4
Build-Jdk: 1.8.0_201
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLDecoder;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class Manifestation {
private static final Logger logger = LoggerFactory.getLogger(Manifestation.class);
private AtomicBoolean loaded = new AtomicBoolean(false);
private Manifest manifest;
// 程序版本号
private String version = "";
public void load() {
if (loaded.compareAndSet(false, true)) {
try {
String location = URLDecoder.decode(Manifestation.class.getProtectionDomain().getCodeSource().getLocation().getPath(), Charsets.UTF_8.name());
location = StringUtils.substringBefore(location, "!");
if (location.startsWith("file:")) {
location = location.substring(5);
}
JarFile jarfile = new JarFile(location);
this.manifest = jarfile.getManifest();
this.version = manifest.getMainAttributes().getValue("Implementation-Version");
logger.info("load manifest[{}]: {}", location, toString());
} catch (Exception e) {
logger.error("读取程序版本号出现异常", e);
}
}
}
public String version() {
return this.version;
}
@Override
public String toString() {
return "{" + "version = " + version + "}";
}
}
2、build-info.properties
build.artifact=task-notification
build.group=com.xxx.platform
build.name=task-notification
build.time=2023-08-15T02\:08\:33.043Z
build.version=2.4.2
这个是依赖maven插件 git-commit-id-plugin,具体在我之前的博文都有详细讲述。这里就不再赘述~
3、pom依赖
路径是maven/{基本package名}/{服务名},读取pom.xml或者pom.properties都可以。
当然读取pom.properties相对简单,格式见下:
#Created by Apache Maven 3.5.4
#Wed Nov 02 11:29:00 CST 2022
version=1.25.11
groupId=com.xxx.platform
artifactId=user-service
如果你是CICD中需要读取版本号,需要知道Jar包的根包名,不同的项目,包名不一样。
建议采用上面两种办法去读取。
更多推荐
已为社区贡献10条内容
所有评论(0)