这篇文章首先介绍了在SpringBoot中如何获得项目的编译时间和版本号,并向外提供接口,然后介绍了介绍了新版maven获得时间戳时区错误的解决方案,最后介绍了把时间戳加到包名的两种方法。
SpringBoot项目获得编译时间戳和版本号,然后提供接口大概分为以下步骤:
application.yml
在 pom文件properties
中添加两个属性
<properties>
<timestamp>${maven.build.timestamp}timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm:ssmaven.build.timestamp.format>
properties>
application.yml
在pom文件build
中配置
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<filtering>truefiltering>
resource>
resources>
build>
在application.yml
中配置
不能使用
${}
app:
version: @project.version@
build:
time: @timestamp@
创建AppController
,提供接口 Get /app
package cn.yshow.modules.sys.controller;
import cn.yshow.common.utils.restResult.RestResult;
import cn.yshow.common.utils.restResult.ResultGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @author zhaod [email protected]
* @version v1.0
* @since 2018/12/16 16:19
*/
@Slf4j
@RestController
@RequestMapping("/app")
public class AppController {
/**
* 当前版本
*/
@Value("${app.version}")
private String version;
/**
* 打包时间
*/
@Value("${app.build.time}")
private String buildTime;
@GetMapping
public RestResult uploadImg() {
Map<String,String> ret = new HashMap<>();
ret.put("version",version);
ret.put("buildTime",buildTime);
//RestResult是我封装的返回对象
return ResultGenerator.genSuccessResult(ret);
}
}
maven.build.timestamp
时区错误解决方案在Maven 3.2.2+中, maven.build.timestamp已被重新定义,显示UTC中的时间,比中国时间慢8个小时。可以使用插件build-helper-maven-plugin
获得本时区的时间
在plugins
块添加插件,这个配置与官网不一样,按照官网的配置方式会报错
<project>
<build>
<finalName>
${project.artifactId}-${project.version}-${build.time}
finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojogroupId>
<artifactId>build-helper-maven-pluginartifactId>
<version>1.8version>
<executions>
<execution>
<id>timestamp-propertyid>
<goals>
<goal>timestamp-propertygoal>
goals>
execution>
executions>
<configuration>
<name>build.timename>
<pattern>yyyy-MM-dd HH:mmpattern>
<timeZone>GMT+8timeZone>
configuration>
plugin>
plugins>
build>
project>
经过上述处理后,属性${build.time}
已经代表GMT-8时区的时间
application.yml
配置如下
app:
version: @project.version@
build:
time: @build.time@
IDEA 编译项目不会调用 maven 生命周期,导致安装的 plugin 不被执行。虽然 maven 自带变量可以被替换,但是自定义变量却不会被替换。
可以将 IDEA 的 Build
与 maven goal
绑定起来,在 build 之前执行 maven goal
,IDEA 右侧 Maven Projects
-> LifeCycle
-> compile
勾选 Execute After Build
和Execute After Rebuild
,如下图
两种方法不要重复,否则
方法一:把时间戳加到版本号
<project>
<versioin>
0.0.5.${build.time}
version>
project>
方法二:把时间戳直接加到包名
<project>
<build>
<finalName>
${project.artifactId}-${project.version}-${build.time}
finalName>
build>
project>