【发布时间】:2022-06-11 06:28:18
【问题描述】:
应用程序在 Eclipse 中的 Gradle 任务下作为 bootRun 任务运行时按预期运行,但是,右键单击项目 --> 运行方式 --> Spring Boot App 不会替换以下原型中的属性值。
- build.gradle 文件
import org.apache.tools.ant.filters.ReplaceTokens
plugins {
id 'org.springframework.boot' version '2.6.1'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'eclipse'
}
group = 'com.sample.auto.expanson'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
// enable auto property expansion for passing gradle property to spring boot
// https://www.baeldung.com/spring-boot-auto-property-expansion
processResources {
duplicatesStrategy = 'include'
with copySpec {
from 'src/main/resources'
include '**/application*.properties'
include '**/application*.yaml'
include '**/application*.yml'
project.properties.findAll().each {
prop ->
if (prop.key != null) {
filter(ReplaceTokens, tokens: [(prop.key): prop.value.toString()])
filter(ReplaceTokens, tokens: [('project.' + prop.key): prop.value.toString()])
}
}
}
}
- gradle.properties
expansion.property=Hello Expansion Property!
- application.properties
com.test.value=@expansion.property@
- DemoApplication.java
package com.sample.auto.expanson.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Value("${com.test.value}")
String expansionProperty;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(expansionProperty);
}
}
bootRun 任务产生预期的输出:
Hello Expansion Property!
BUILD SUCCESSFUL in 1s
4 actionable tasks: 4 executed
在 Eclipse 中将其作为 Spring Boot App 运行会导致文字输出,而不会替换值。
2021-12-04 21:49:35.598 INFO 27293 --- [ main] c.s.auto.expanson.demo.DemoApplication : Started DemoApplication in 1.097 seconds (JVM running for 2.105)
@expansion.property@
【问题讨论】:
标签: java spring eclipse spring-boot gradle