随着Devops的日渐深入,项目的部署越来越频繁,版本更迭越来越快,这些全靠流水线来完成,然而偶尔可能会因为流水线出问题而发生流水线“执行成功”,而实际代码未更新的问题,本文不讨论流水线是否有问题,而考虑如何在编译打包过程中,使用springboot-build-info附加项目构建信息,使用git-commit-id-plugin附加git信息,而能够清晰的了解代码是否完成更新。
获取代码是否更新几个要点:Maven中项目版本信息、Git提交信息
获取Maven中项目版本信息
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layout>ZIP</layout><!-- enables PropertiesLauncher -->
</configuration>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
<configuration>
<additionalProperties>
<!--自定义属性配置-->
<java.version>${java.version}</java.version>
<common.version>${common.version}</common.version>
</additionalProperties>
</configuration>
</execution>
</executions>
</plugin>
在spring-boot构建插件中增加上面执行配置,goal为build-info,可以将maven中的关键信息输出到MATE_INF/build-info.properties文件。
默认属性:
- build.artifact
- build.version
- build.group
- build.name
- build.time
接下来我们需要配置Bean来读到这些信息,注意用idea启动,不会使用spring-boot构建插件,因此没有这些信息,可能会报错,使用如下注解,控制只有build-info文件存在才可以工作。
@ConditionalOnResource(resources =
"${spring.info.build.location:classpath:META-INF/build-info.properties}")
Accessing Build Properties
@Autowired
BuildProperties buildProperties;
// Artifact's name from the pom.xml file
buildProperties.getName();
// Artifact version
buildProperties.getVersion();
// Date and Time of the build
buildProperties.getTime();
// Artifact ID from the pom file
buildProperties.getArtifact();
// Group ID from the pom file
buildProperties.getGroup();
实现原理参考:org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
参考文章:
https://www.vojtechruzicka.com/spring-boot-version/
获取Git提交信息
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>4.0.1</version>
<configuration>
<failOnNoGitDirectory>false</failOnNoGitDirectory>
<dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
<generateGitPropertiesFilename>
${project.build.outputDirectory}/git.properties
</generateGitPropertiesFilename>
</configuration>
</plugin>
引入git-commit-id-plugin构建插件
注意后面configuration配置为了让在流水线中可以相对地址找到.git目录,构建内容输出到git.properties。
@Bean
public static PropertySourcesPlaceholderConfigurer gitProperty() {
PropertySourcesPlaceholderConfigurer propsConfig
= new PropertySourcesPlaceholderConfigurer();
propsConfig.setLocation(new ClassPathResource("git.properties"));
propsConfig.setIgnoreResourceNotFound(true);
propsConfig.setIgnoreUnresolvablePlaceholders(true);
return propsConfig;
}
配置gitProperty Bean,会读取git.properties属性,使其可以通过@Value获取
@Value("${git.commit.message.short}")
private String commitMessage;
@Value("${git.branch}")
private String branch;
@Value("${git.commit.id}")
private String commitId;
@Value("${git.commit.id.abbrev}")
private String commitIdAbbrev;
通过@Value即可拿到git属性
参考文章:
https://www.baeldung.com/spring-git-information
DevOps流水线代码更新验证

本文介绍如何在DevOps环境中使用Spring Boot和Maven插件确保代码更新正确部署,通过构建信息和Git提交记录,增强流水线的透明度。
1577





