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类型
相关推荐
派大鑫wink12 小时前
【Day57】SpringBoot 整合 Redis:吃透缓存配置与 API 实战
spring boot·redis·缓存
九皇叔叔13 小时前
application.yml 文件无 Spring 图标 + 无自动提示
java·spring boot·spring
让我上个超影吧14 小时前
天机学堂——多级缓存
java·spring boot·spring cloud
CoderJia程序员甲15 小时前
GitHub 热榜项目 - 日榜(2026-01-24)
git·ai·开源·llm·github
莫问前路漫漫15 小时前
Electerm 连接远程服务器完整指南
运维·服务器·git
鸣弦artha16 小时前
TabBar标签页组件详解
linux·git·ubuntu
小王不爱笑13216 小时前
@PropertySource&@ImportResource&@Bean
spring boot
Wyy_9527*16 小时前
行为型设计模式——状态模式
java·spring boot·后端
编程彩机16 小时前
互联网大厂Java面试:从分布式事务到微服务架构场景应用
spring boot·分布式事务·微服务架构·java面试·电商场景
梅梅绵绵冰17 小时前
springboot初步2
java·spring boot·后端