gradle 构建项目添加版本信息

gradle 构建项目添加版本信息,打包使用 spring boot 的打包插件

build.gradle 配置文件

groovy 复制代码
bootJar {
    manifest {
        attributes(
                'Project-Name': project.name,
                'Project-Version': project.version,
                "project-Vendor": "XXX Corp",
                "Built-By": "Gradle ${gradle.gradleVersion}",
                "Built-At": new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
                'Git-Branch': getGitBranch(),
                'Git-Commit': getGitCommit(),
                'Git-Commit-Time': getGitCommitTime()
        )

    }
}

// 获取当前分支名称
static def getGitBranch() {
    try {
        def branch = 'git rev-parse --abbrev-ref HEAD'.execute().text.trim()
        return branch ?: 'unknown'
    } catch (Exception e) {
        System.err.println("fail to get branch, errMsg:" + e.getMessage())
        return 'unknown'
    }
}

// 获取当前提交的记录的commitId
static def getGitCommit() {
    try {
        def commit = 'git rev-parse  HEAD'.execute().text.trim()
        return commit ?: 'unknown'
    } catch (Exception e) {
        System.err.println("fail to get commit id, errMsg:" + e.getMessage())
        return 'unknown'
    }
}

// 获取当前Git提交的时间
static def getGitCommitTime() {
    try {
        def commitTime = 'git show -s --format=%ct HEAD'.execute().text.trim()
        return commitTime ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(commitTime) * 1000L)) : 'unknown'
    } catch (Exception e) {
        System.err.println("fail to get commit time, errMsg:" + e.getMessage())
        return 'unknown'
    }
}

版本信息模型

java 复制代码
public class VersionModel {
    private String projectName;
    private String projectVersion;
    private String projectVendor;
    private String builtBy;
    private String builtAt;
    private String gitBranch;
    private String gitCommit;
    private String gitCommitTime;

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public String getProjectVersion() {
        return projectVersion;
    }

    public void setProjectVersion(String projectVersion) {
        this.projectVersion = projectVersion;
    }

    public String getProjectVendor() {
        return projectVendor;
    }

    public void setProjectVendor(String projectVendor) {
        this.projectVendor = projectVendor;
    }

    public String getBuiltBy() {
        return builtBy;
    }

    public void setBuiltBy(String builtBy) {
        this.builtBy = builtBy;
    }

    public String getBuiltAt() {
        return builtAt;
    }

    public void setBuiltAt(String builtAt) {
        this.builtAt = builtAt;
    }

    public String getGitBranch() {
        return gitBranch;
    }

    public void setGitBranch(String gitBranch) {
        this.gitBranch = gitBranch;
    }

    public String getGitCommit() {
        return gitCommit;
    }

    public void setGitCommit(String gitCommit) {
        this.gitCommit = gitCommit;
    }

    public String getGitCommitTime() {
        return gitCommitTime;
    }

    public void setGitCommitTime(String gitCommitTime) {
        this.gitCommitTime = gitCommitTime;
    }

    @Override
    public String toString() {
        return "VersionModel{" +
                "projectName='" + projectName + '\'' +
                ", projectVersion='" + projectVersion + '\'' +
                ", implementationVendor='" + projectVendor + '\'' +
                ", builtBy='" + builtBy + '\'' +
                ", builtAt='" + builtAt + '\'' +
                ", gitBranch='" + gitBranch + '\'' +
                ", gitCommit='" + gitCommit + '\'' +
                ", gitCommitTime='" + gitCommitTime + '\'' +
                '}';
    }
}

版本工具类

java 复制代码
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

public class BuildUtils {
    public static final String projectName = "Project-Name";
    public static final String projectVersion = "Project-Version";
    public static final String projectVendor = "Project-Vendor";
    public static final String builtBy = "Built-By";
    public static final String builtAt = "Built-At";
    public static final String gitBranch = "Git-Branch";
    public static final String gitCommit = "Git-Commit";
    public static final String gitCommitTime = "Git-Commit-Time";
    private static final Logger log = LoggerFactory.getLogger(BuildUtils.class);

    public static String getManifestAttribute(String attributeName) {
        try {
            Manifest manifest = new Manifest(BuildUtils.class.getResourceAsStream("/META-INF/MANIFEST.MF"));
            Attributes attributes = manifest.getMainAttributes();
            return attributes.getValue(attributeName);
        } catch (IOException e) {
            log.warn("fail to get info from manifest file, errMsg:{}", e.getMessage(), e);
            return "unknown";
        }
    }

    public static Attributes getManifestAttribute() {
        try {
            Manifest manifest = new Manifest(BuildUtils.class.getResourceAsStream("/META-INF/MANIFEST.MF"));
            return manifest.getMainAttributes();
        } catch (IOException e) {
            log.warn("fail to get info from manifest file, errMsg:{}", e.getMessage(), e);
            return new Attributes();
        }
    }

    public static String getManifestAttributeJsonFormat() {
        return JSONObject.toJSONString(getVersionModel(), true);
    }

    public static VersionModel getVersionModel() {
        VersionModel versionModel = new VersionModel();
        try {
            Manifest manifest = new Manifest(BuildUtils.class.getResourceAsStream("/META-INF/MANIFEST.MF"));
            versionModel.setBuiltAt(manifest.getMainAttributes().getValue(builtAt));
            versionModel.setBuiltBy(manifest.getMainAttributes().getValue(builtBy));
            versionModel.setProjectName(manifest.getMainAttributes().getValue(projectName));
            versionModel.setProjectVersion(manifest.getMainAttributes().getValue(projectVersion));
            versionModel.setProjectVendor(manifest.getMainAttributes().getValue(projectVendor));
            versionModel.setGitBranch(manifest.getMainAttributes().getValue(gitBranch));
            versionModel.setGitCommit(manifest.getMainAttributes().getValue(gitCommit));
            versionModel.setGitCommitTime(manifest.getMainAttributes().getValue(gitCommitTime));
        } catch (IOException e) {
            log.warn("fail to get info from manifest file, errMsg:{}", e.getMessage(), e);
        }
        return versionModel;
    }
}

方法1 controller 示例

java 复制代码
@RestController
@RequestMapping("/version")
public class VersionController {
    @GetMapping("/build")
    public VersionModel getVersionModel(){
        return BuildUtils.getVersionModel();
    }
}

方法2 执行 jar 包中的类执行获取版本信息

java 复制代码
package com.version;
public class Version {
    public static void main(String[] args) {
        System.out.println(BuildUtils.getManifestAttributeJsonFormat());
    }
}

java -cp you-app.jar -Dloader.main=com.version.Version org.springframework.boot.loader.PropertiesLauncher

参考连接

https://blog.csdn.net/russle/article/details/130658805

相关推荐
武昌库里写JAVA3 分钟前
Java成长之路(一)--SpringBoot基础学习--SpringBoot代码测试
java·开发语言·spring boot·学习·课程设计
Q_192849990610 分钟前
基于Spring Boot的九州美食城商户一体化系统
java·spring boot·后端
张国荣家的弟弟27 分钟前
【Yonghong 企业日常问题 06】上传的文件不在白名单,修改allow.jar.digest属性添加允许上传的文件SH256值?
java·jar·bi
ZSYP-S39 分钟前
Day 15:Spring 框架基础
java·开发语言·数据结构·后端·spring
yuanbenshidiaos1 小时前
C++----------函数的调用机制
java·c++·算法
是小崔啊1 小时前
开源轮子 - EasyExcel01(核心api)
java·开发语言·开源·excel·阿里巴巴
黄公子学安全1 小时前
Java的基础概念(一)
java·开发语言·python
liwulin05061 小时前
【JAVA】Tesseract-OCR截图屏幕指定区域识别0.4.2
java·开发语言·ocr
jackiendsc1 小时前
Java的垃圾回收机制介绍、工作原理、算法及分析调优
java·开发语言·算法
Yuan_o_1 小时前
Linux 基本使用和程序部署
java·linux·运维·服务器·数据库·后端