将Gradle.build版本导入Spring Boot

我正在尝试在视图中显示我的Spring Boot应用程序的应用程序版本。 我确定我可以访问这个版本信息,我只是不知道如何。

我尝试了以下信息: https : //docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html ,并将其放在我的application.properties

 info.build.version=${version} 

然后在我的控制器中加载@Value("${version.test}") ,但这不起作用,我只会得到如下错误:

 Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'version' in string value "${version}" 

有关获取我的应用程序版本,弹簧启动版本等信息的正确方法的任何建议到我的控制器?

如参考文档中所述 ,您需要指示Gradle处理应用程序的资源,以便它将${version}占位符替换为项目的版本:

 processResources { expand(project.properties) } 

为了安全起见,您可能希望缩小范围,以便只处理application.properties

 processResources { filesMatching('application.properties') { expand(project.properties) } } 

现在,假设您的属性名为info.build.version ,它将通过@Value

 @Value("${info.build.version}") 

我通过在application.yml中添加以下内容来解决这个问题:

 ${version?:unknown} 

它也可以在cli: gradle bootRun和IntelliJ中工作,在启动IntelliJ或使用spring配置文件之前,您不必调用Gradle任务processResources。

这适用于Gradle ver: 4.6以及Spring Boot ver: 2.0.1.RELEASE 。 希望能帮助到你 ;)

我用这种方式解决了它:在application.properties定义你的info.build.version

 info.build.version=whatever 

在你的组件中使用它

 @Value("${info.build.version}") private String version; 

现在将您的版本信息添加到build.gradle文件中,如下所示:

 version = '0.0.2-SNAPSHOT' 

然后添加一个方法来用你的application.properties替换正则表达式来更新你的版本信息:

 def updateApplicationProperties() { def configFile = new File('src/main/resources/application.properties') println "updating version to '${version}' in ${configFile}" String configContent = configFile.getText('UTF-8') configContent = configContent.replaceAll(/info\.build\.version=.*/, "info.build.version=${version}") configFile.write(configContent, 'UTF-8') } 

最后,确保在触发buildbootRun时调用该方法:

 allprojects { updateVersion() } 

而已。 如果您让Gradle编译您的应用程序以及从IDE运行Spring Boot应用程序,此解决方案将起作用。 该值不会更新但不会引发exception,只要您运行Gradle它就会再次更新。

我希望这有助于其他人以及它为我解决问题。 我找不到更合适的解决方案,所以我自己编写了脚本。