2016-04-28 53 views
6

我試圖設置gradle以啓用啓用各種彈簧配置文件的​​進程。如何使用彈簧配置文件通過gradle任務運行bootRun

我現在​​配置是這樣的:

bootRun { 
    // pass command line options from gradle to bootRun 
    // usage: gradlew bootRun "-Dspring.profiles.active=local,protractor" 
    if (System.properties.containsKey('spring.profiles.active')) { 
     systemProperty "spring.profiles.active", System.properties['spring.profiles.active'] 
    } 
} 

我想用gradle任務設置系統屬性,然後執行​​。

我的嘗試是這樣的:

task bootRunDev 

bootRunDev { 
    System.setProperty("spring.profiles.active", "Dev") 
} 

幾個問題:

  1. systemProperty春季啓動bootRun配置的一部分?
  2. 是否可以在另一個任務中設置系統屬性?
  3. 我的下一步應該是什麼?我需要去發生bootRunDev配置之前​​
  4. 難道還有其他的方法,我應該考慮

-Eric

回答

3

簡單的方法是定義默認和允許它被覆蓋。我不確定在這種情況下systemProperty有什麼用處。簡單的論據將完成這項工作。

def profiles = 'prod' 

bootRun { 
    args = ["--spring.profiles.active=" + profiles] 
} 

要運行開發:

./gradlew bootRun -Pdev 

要在任務添加的依賴,你可以做這樣的事情:

task setDevProperties(dependsOn: bootRun) << { 
    doFirst { 
    System.setProperty('spring.profiles.active', profiles) 
    } 
} 

有很多方法在搖籃實現這一目標。

+0

我得到'在org.gradle.api類型的對象上找不到方法dev()參數[org.springframework.boot:spring-boot-devtools] .internal.artifacts.dsl.dependencies.DefaultDependencyHandler.'當我嘗試這種方法。 http://stackoverflow.com/a/31328621/1134197正常工作 – aycanadal

+0

儘管第一個代碼片段顯示瞭如何配置bootRun任務,但其他示例根本不起作用。 –

4

環境變量可用於設置彈簧屬性,如the documentation中所述。因此,要設置活動的配置文件(spring.profiles.active),您可以使用下面的代碼在Unix系統上:

SPRING_PROFILES_ACTIVE=test gradle clean bootRun 

和Windows,你可以使用:

SET SPRING_PROFILES_ACTIVE=test 
gradle clean bootRun 
+2

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – DimaSan

+0

這不適用於windows – JackDev

1

對於使用Spring引導那些人2.0+,你可以使用以下內容來設置將使用一組給定配置文件運行應用程序的任務。

task bootRunDev(type: org.springframework.boot.gradle.tasks.run.BootRun, dependsOn: 'build') { 
    group = 'Application' 

    doFirst() { 
     main = bootJar.mainClass 
     classpath = sourceSets.main.runtimeClasspath 
     systemProperty 'spring.profiles.active', 'dev' 
    } 
} 

然後,您可以簡單地從IDE運行./gradlew bootRunDev或類似軟件。

+0

我們如何爲此任務定製webapp文件夾..? – rijin

0

對於來自互聯網的人,有一個類似的問題https://stackoverflow.com/a/35848666/906265我從它提供修改後的答案在這裏還有:

// build.gradle 
<...> 

bootRun {} 

// make sure bootRun is executed when this task runs 
task runDev(dependsOn:bootRun) { 
    // TaskExecutionGraph is populated only after 
    // all the projects in the build have been evaulated https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html#whenReady-groovy.lang.Closure- 
    gradle.taskGraph.whenReady { graph -> 
     logger.lifecycle('>>> Setting spring.profiles.active to dev') 
     if (graph.hasTask(runDev)) { 
      // configure task before it is executed 
      bootRun { 
       args = ["--spring.profiles.active=dev"] 
      } 
     } 
    } 
} 

<...> 
在終端

則:

gradle runDev 

曾用gradle 3.4.1和​​