在 Spring Boot 中,可以通过 Maven 的资源过滤功能,将 pom.xml 中的构建时间注入到配置文件中。以下是实现步骤:

配置关系图:

┌─────────────────┐     定义时间格式     ┌─────────────────────┐
│   properties    │ ─────────────────→  │ yyyy-MM-dd HH:mm:ss │
└─────────────────┘                     └─────────────────────┘

┌─────────────────┐     开启过滤功能     ┌─────────────────────┐
│   resources     │ ─────────────────→  │ 允许替换配置文件变量 │
└─────────────────┘                     └─────────────────────┘

┌─────────────────┐     配置分隔符       ┌─────────────────────┐
│  maven-resources-plugin │ ─────────→  │ 使用@作为变量标记    │
└─────────────────┘                     └─────────────────────┘
  1. 修改 pom.xml 配置
    在 pom.xml 中添加资源过滤配置,允许 Maven 替换配置文件中的变量:
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering> <!-- 开启过滤,允许替换变量 -->
        </resource>
    </resources>
    
    <!-- 定义打包时间属性 -->
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.3.0</version>
            <configuration>
                <delimiters>
                    <delimiter>@</delimiter> <!-- 使用 @ 作为变量分隔符,避免与 Spring 配置冲突 -->
                </delimiters>
                <useDefaultDelimiters>false</useDefaultDelimiters>
            </configuration>
        </plugin>
    </plugins>
</build>
  1. 在配置文件中引用打包时间
    在 application.properties 或 application.yml 中使用 Maven 变量引用打包时间:

application.properties:

# 引用 Maven 构建时间
build.time=@maven.build.timestamp@
# 可以自定义时间格式(需要在 pom.xml 中额外配置)
build.time.formatted=@build.timestamp.formatted@

如果需要自定义时间格式,在 pom.xml 中添加:

<properties>
    <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
    <build.timestamp.formatted>${maven.build.timestamp}</build.timestamp.formatted>
</properties>
  1. 在 Spring Boot 中使用打包时间
    通过 @Value 注解在代码中获取配置的打包时间:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BuildInfoController {

    @Value("${build.time}")
    private String buildTime;
    
    @Value("${build.time.formatted:}")
    private String formattedBuildTime;

    @GetMapping("/build-info")
    public String getBuildInfo() {
        return "打包时间(原始):" + buildTime + "<br>" +
               "打包时间(格式化):" + formattedBuildTime;
    }
}

原理说明

  • Maven 在打包时会自动替换配置文件中 @变量名@ 格式的占位符
  • maven.build.timestamp 是 Maven 内置的构建时间变量,默认格式为 yyyyMMdd-HHmm
  • 通过自定义 maven.build.timestamp.format 可以修改时间格式
  • 资源过滤功能确保打包后的配置文件中已替换为实际的构建时间

这种方式可以方便地在应用中展示或记录打包时间,便于版本追踪和问题排查。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐