如何通过命令行为Gradle构建配置Spring Boot的application.properties变量?
application.properties via Gradle Build Got it, let's break down how to make this work. You want to pass values like username, password, and host via your Gradle build command, and have those values populate the placeholders in your application.properties file. Here are two common approaches depending on your needs:
Option 1: Replace Placeholders During Build (Fixed Values in Jar)
If you want the built JAR file to have the actual values baked into application.properties (so they don't change unless you rebuild), you'll need to configure Gradle's resource processing to expand those placeholders using the system properties you pass.
Configure build.gradle (Groovy)
Add this configuration to your build.gradle file to tell Gradle to target application.properties and replace its placeholders with the system properties from your build command:
processResources { // Focus only on application.properties to avoid modifying other resources filesMatching('application.properties') { // Expand ${...} placeholders using the system properties passed via -D expand(System.properties) } }
Configure build.gradle.kts (Kotlin DSL)
If you're using Kotlin for your Gradle configuration, use this equivalent code:
tasks.processResources { filesMatching("application.properties") { expand(System.getProperties()) } }
Run the Build Command
Now execute your build with the system properties as you intended:
gradle build -Dusername="user" -Dpassword="pwd" -Dhost="192.X.X.X"
After building, if you inspect the application.properties file inside the built JAR (under BOOT-INF/classes), you'll see the ${host}, ${username}, and ${password} placeholders replaced with the values you passed.
Option 2: Keep Placeholders, Pass Values When Running the JAR
If you prefer to keep the placeholders in the built JAR and pass values dynamically when launching the app (so you can use different credentials/hosts without rebuilding), you don't need any special Gradle setup. Just run the JAR with the system properties directly:
java -jar build/libs/your-app-version.jar -Dusername="user" -Dpassword="pwd" -Dhost="192.X.X.X"
Spring Boot automatically reads system properties at runtime and uses them to resolve the ${...} placeholders in application.properties.
Important Notes
- Property Priority: Spring Boot follows a strict property precedence order, and system properties rank high—they will override any hardcoded values in
application.properties. - Security Heads-Up: Avoid passing sensitive values like passwords via command line arguments in production, as they may be visible in process lists. Consider using environment variables or a secure secrets manager instead.
内容的提问来源于stack exchange,提问作者Prash

