将Gradle.build版本导入Spring Boot

时间:2016-01-23 11:47:28

标签: java spring gradle 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}"

有关将应用程序版本,弹簧启动版本等信息提供给控制器的正确方法的建议吗?

4 个答案:

答案 0 :(得分:16)

您也可以在build.gradle中添加它:

springBoot {    
    buildInfo() 
}

然后,您可以使用BuildProperties bean:

@Autowired
private BuildProperties buildProperties;

并使用buildProperties.getVersion()

获取版本

答案 1 :(得分:8)

作为described in the reference documentation,您需要指示Gradle处理您的应用程序资源,以便它将${version}占位符替换为项目的版本:

processResources {
    expand(project.properties)
}

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

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

现在,假设您的媒体资源名为info.build.version,可以通过@Value投放:

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

答案 2 :(得分:3)

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

${version?:unknown}

它也适用于cli: gradle bootRun 以及IntelliJ,您无需在IntelliJ中启动或使用弹簧配置文件之前调用Gradle任务processResources。

这项工作与Gradle ver: 4.6 以及Spring Boot ver: 2.0.1.RELEASE 。 希望它有所帮助;)

答案 3 :(得分:0)

我这样解决了: 在info.build.version中定义application.properties

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应用程序,此解决方案将起作用。该值不会更新但不会抛出异常,只要您运行Gradle,它就会再次更新。

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