SpringBoot: 读取项目的Git版本号

在开发项目的时候,我们经常会想要拿到线上运行的程序版本,以确定程序是否正确发布。Spring Boot提供了这样的能力支持。这个能力的核心组件是3个:

  1. Maven插件git-commit-id-maven-plugin,用于生成.properties文件,里边包含git的各种信息
  2. 加载git.properties文件,ProjectInfoAutoConfiguration判断是否存在git的properties文件,注册GitProperties Bean
  3. 引用GitProperties Bean,读取git信息

1. 使用Maven插件

首先我们需要在pom.xml里引入插件,在build/plugins/plugin配置插件git-commit-id-maven-plugin的

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


    ...
    <build>
        <plugins>
            <plugin>
                <groupId>io.github.git-commit-id</groupId>
                <artifactId>git-commit-id-maven-plugin</artifactId>
                <configuration>
                    <generateGitPropertiesFile>true</generateGitPropertiesFile>
                    <generateGitPropertiesFilename>
                        ${project.build.outputDirectory}/git.properties
                    </generateGitPropertiesFilename>
                </configuration>
            </plugin>
            ...
        </plugins>
    </build>

</project>

执行插件git-commit-id:revision,查看生成的target,最终会在class目录下创建一个git.properties文件

bash 复制代码
mvn clean package git-commit-id:revision

看一下生成的git.properties文件,可以看到,里边不仅有版本号(commit.id),还有分支(git.branch),用户名(user.name)等信息

2. 加载git.properties文件

SpringBoot定义了一个AutoConfiguration类(ProjectInfoAutoConfiguration),基于条件创建GitProperties对象。

1. 条件对象

GitResourceAvailableCondition通过环境变量spring.info.git.location获取git.proerties文件的路径。如果没有设置环境变量则直接查看classpath:git.properties。

获取配置文件的路径后,通过ResourceLoader#getResource(location)判断这个文件是否存在。

2. 创建Bean

ProjectInfoAutoConfiguration是一个AutoConfiguration类,定义了一个@Bean方法,创建一个GitProperties Bean。后续只需要引用这个Bean即可。

3. 引用GitProperties Bean

在我们的业务代码中只需要直接注入GitProperties Bean即可,GitProperties有5个核心方法:

  1. getBranch,获取分支
  2. getCommitId,获取提交版本号
  3. getShortCommitId,获取短的提交版本号
  4. get,按属性名读取git.properties文件,返回String类型
  5. getInstant,按属性名读取git.properties文件,返回Instant类型
相关推荐
码视野5 小时前
基于 Spring Boot + Vue3 的【大学英语四六级 (CET-4/6) 作文智能评分与句式润色系统】设计与实现(含PRD/三端高保真源码/大屏)
java·前端·人工智能·spring boot·后端·vue3
风尘小子6 小时前
git的.gitignore文件中文件和目录配置
git
李昊哲小课7 小时前
SpringBoot4 云端咖啡站 阶段二:数据访问与分层架构
spring boot·架构
宠友信息8 小时前
社区类源码开发实践中的仿小红书系统技术要点分析
java·spring boot·redis·mysql·uni-app·vue·内容运营
摇滚侠9 小时前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 1
spring boot·笔记·后端
李昊哲小课10 小时前
SpringBoot4 云端咖啡站 阶段四:安全、文件与性能
spring boot·安全·性能优化·文件·性能
南城以南溫暖如初14710 小时前
从零搭建24小时自助健身系统:技术选型与核心模块实战
java·spring boot·redis·mysql·vue·mybatis
Tanner_SL11 小时前
Linux笔记之GIT常用命令
linux·git
李昊哲小课12 小时前
SpringBoot4 云端咖啡站 阶段五:交付与进阶
人工智能·spring boot·大模型·log4j·智能体
MetaLite13 小时前
SpringBoot分页接口怎么设计-pageSize不设上限会发生什么
java·spring boot·后端