SpringBoot读取中的version变量

时间:2025-04-21 09:33:33

一、背景需求

基于Maven的SpringBoot微服务发布后,在后端管理页面,管理员希望看到各服务模块的当前版本号,因此在需要在Java代码中读取到中的version版本信息,通过API接口向管理页面提供版本数据。

二、实现方案

1、maven构建时,将中的变量,写入到SpringBoot的yml配置文件中。

中,添加从文件中读取变量的配置:

spring:
  application:
    # @变量名@ 读取中的值
    version: @@

中添加resource资源文件过滤,在编译构建的时候,将yml中引用的变量,替换成真实的值。

<project>
    <!-- pom中定义的 -->
    <version>1.8.0-SNAPSHOT</version>

    <build>        
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <!-- 配置资源文件 -->
                    <include>**/*.yml</include>
                </includes>
                <!-- 启用过滤器,过滤器会解析需要过滤的的资源文件,将其中的变量替换成真实的值 -->
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

编译构建后,真实内容(注意version变成了真实值):

spring:
  application:
    # @变量名@ 读取中的值
    version: 1.8.0-SNAPSHOT

2、在Java代码中注入SpringBoot变量。

@Component
public class PomConfigTest{
    private static final Logger log = ();
    
    @Value("${}")
    private String applicationVersion;

    public PomConfigTest() {
        ("当前版本 applicationVersion: {}", applicationVersion);
    }
}