gpt4 book ai didi

java - 从 Spring Batch 项目中的 build.gradle 获取值

转载 作者:行者123 更新时间:2023-11-30 10:10:16 30 4
gpt4 key购买 nike

我的 gradle.properties 文件中有一些数据:

appVersion=1.4.31
appGroup=com.business
appName=projectName

我希望能够在 .java 项目中访问它们。我正试图像这样访问变量:

@Value("${appVersion}")
private int version;

但是,当我尝试从主类运行应用程序时,出现以下错误:

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'appVersion' in value "${appVersion}"

这表明它找不到正确的变量。

尝试解决问题

添加一个@propertySource注解

我试过将它添加到主类中@PropertySource(value = "file:build.gradle", ignoreResourceNotFound = true) 未成功。

build.gradle 中进行更改

我尝试了以下内容,摘自 this StackOverflow 回答:

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

同样没有成功。

This下面回答

我做了这个答案中所说的(我必须添加一个 application.properties 文件)并且我收到了这个错误消息:

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Circular placeholder reference 'appVersion' in property definitions

我认为它可能会与使用相同的名称 (appVersion = appVersion) 混淆,所以我将 application.properties 行更改为

version=${appVersion}

然后在我的 .java 文件中,我将行更改为:

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

得到错误:

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'appVersion' in value "${appVersion}"

最佳答案

这应该有效:

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

但是你好像忘记了另一部分。这只是告诉 Gradle 处理您的 application.properties 文件并替换它找到的任何占位符。您还需要在 application.properties 中放置一个占位符:

version=${appVersion}

那么你的值注释应该可以工作(但它应该是一个 String 而不是 int)

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

最后,由于您是通过 IDEA 启动的,您可能需要确保 gradle:processResources 在您的应用程序启动之前运行,以便 Gradle 有机会替换您在 中放置的占位符应用程序属性。您应该能够利用运行配置中的“Before Launch Options”部分让 IDEA 在构建任务之后运行 processResources Gradle 任务。这应该会导致每次运行应用程序时正确替换占位符。


此外,只是为了帮助理解。 Gradle 是应用程序的构建系统,它不是应用程序本身的一部分。一旦项目构建完成,与 Gradle 相关的一切都无关紧要。这就是为什么您不能只执行 @Value("${appVersion}") 并让它工作的原因。应用程序/Spring 对用于构建它的工具一无所知(而且它不应该)。因此,如果您想访问它,您需要以某种方式在构建时将 Gradle 项目版本注入(inject)到应用程序中。有多种方法可以实现这一点,但上面的资源处理方法是一种非常常见的方法。

关于java - 从 Spring Batch 项目中的 build.gradle 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52876820/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com