Gradle构建Spring Boot项目:打包Jar时动态修改文件内容
processResources in Spring Boot + Gradle Looks like you've already nailed the file copying part—great start! To tweak the content of your HTML files as they get copied into the JAR's static directory, you can use Gradle's built-in filter method right within your processResources task. This lets you manipulate file content line-by-line (or even as a full block) during the copy process.
Here are practical examples tailored to different use cases:
1. Basic Single Placeholder Replacement
If you just need to swap a simple placeholder (like {{VERSION}}) with a project value, use a closure with replace():
processResources { println 'process resources..' from('./dist') { into('static') // Modify content while copying filter { String line -> line.replace('{{VERSION}}', project.version) } } }
2. Multiple Placeholder Swaps
For replacing several values at once, chain multiple replace() calls:
processResources { println 'process resources..' from('./dist') { into('static') filter { String line -> line.replace('{{APP_NAME}}', project.name) .replace('{{BUILD_DATE}}', new Date().format('yyyy-MM-dd HH:mm:ss')) .replace('{{ENV}}', project.findProperty('env') ?: 'production') } } }
Note: project.findProperty('env') ?: 'production' uses a default value if the env property isn't set (e.g., via ./gradlew build -Penv=staging).
3. Target Only Specific Files
If you don't want to modify every file (just, say, index.html), split the copy logic into two clear parts:
processResources { println 'process resources..' // Modify and copy index.html from('./dist') { into('static') include 'index.html' filter { String line -> line.replace('{{BACKEND_API_URL}}', project.backendUrl) } } // Copy remaining files without changes from('./dist') { into('static') exclude 'index.html' } }
4. Advanced Template Processing
For more complex dynamic content, use Groovy's SimpleTemplateEngine for full template support:
import groovy.text.SimpleTemplateEngine processResources { println 'process resources..' from('./dist') { into('static') include '**/*.html' filter { String content -> def templateEngine = new SimpleTemplateEngine() def template = templateEngine.createTemplate(content) // Pass variables to the template template.make([ version: project.version, appName: project.name, buildTimestamp: new Date().getTime() ]).toString() } } }
With this setup, your HTML files can use Groovy template syntax like ${version} instead of custom placeholders.
Test Your Changes First
Before building the final JAR, run the processResources task directly to verify modified files:
./gradlew processResources
Check the output in build/resources/main/static—your updated HTML files should be there. Once confirmed, run ./gradlew bootJar to generate the JAR with the modified content.
内容的提问来源于stack exchange,提问作者Arvind Kumar

