给Spring Boot 项目打上编译时间

为了方便查阅项目的编译时间,确定部署在服务器上的服务对应哪个版本,以前总是要手动的改动property文件。最近摸索出一种新的方法。
核心思路是将maven build time 写入Spring Boot 的application.yml,然后将application.yml的属性注入代码,暴露API供外部查询。

获取maven build time

主要参考了这篇文章:
https://rterp.wordpress.com/2...
在properties section 添加两个属性,maven.build.timestamp这个变量保存了maven编译时间戳,但无法直接替换到资源文件,所以使用timestamp 变量中转一下。maven.build.timestamp.format 是设置时间格式的。怎么设置看大家的喜好。

<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm</maven.build.timestamp.format>

将编译时间替换进application.yml

在POM文件的build section使能资源文件替换

<resources>
   <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
   </resource>
</resources>

然后往application.yml注入时间,这里我犯过一个错误,使用了 ${timestamp},spring boot框架,将替换语法改成了@@。

self:
  time: @timestamp@

将application.yml属性注入Java变量

一个简单的Value映射,即可将timestamp注入到变量,映射API,即可通过REST API查询到编译时间。

    @Value("${self.time}")
    String buildTime;
    @RequestMapping("/version")
    public String version() {
        return buildTime;
    }

时区问题

maven.build.timestamp 在maven 3.2.2 版本之后,取出来的是utc时间,和我们相差8个小时。最简单的方法是用build-helper-maven-plugin,自己定义build.timestamp.with.offset,后面在application.yml中直接build.timestamp.with.offset就可以了。

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>3.0.0<ersion>
                <executions>
                    <execution>
                        <id>timestamp-property</id>
                        <goals>
                            <goal>timestamp-property</goal>
                        </goals>
                        <configuration>
                            <name>build.timestamp.with.offset</name>
                            <pattern>yyyy-MM-dd HH:mm</pattern>
                            <timeZone>CCT</timeZone>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

妈妈再也不用担心搞不清编译版本了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值