對於maven項目來說,目錄結構是固定的,也就是像這樣:
src/main/
src/main/java/
src/main/resources/
src/test/
src/test/java/
src/test/jresources/
Gradle也是一樣的,他也有一個約定的目錄結構,格式和maven的結構一樣。但不同的是,gradle的目錄結構是可以改的,官網中叫做Changing the project layout。怎么改,或者說怎么自定義?這就要用到SourceSet了。
SourceSet到底是什么,官網中像下面這樣解釋的,大意是說SourceSet包括源文件及位置、它們的依賴、編譯輸出的位置這三個概念,SourceSet可以把不同文件目錄里的文件按照邏輯關系組織起來。具體請參考Declaring your source files via source sets。
Gradle’s Java support was the first to introduce a new concept for building source-based projects: source sets. The main idea is that source files and resources are often logically grouped by type, such as application code, unit tests and integration tests. Each logical group typically has its own sets of file dependencies, classpaths, and more. Significantly, the files that form a source set don’t have to be located in the same directory!
Source sets are a powerful concept that tie together several aspects of compilation:
the source files and where they’re located
the compilation classpath, including any required dependencies (via Gradle configurations)
where the compiled class files are placed
Gradle有兩個SourceSet是默認必須有的,這兩個SourceSet的特殊性在於,你不需要在build文件中去申明它們,並且,操作它們的時候,也不需要帶上他們的名字,比如你編譯的時候,只需要compile,測試的時候,只需要test,而不是compilemain,testtest之類的。
mainContains the production source code of the project, which is compiled and assembled into a JAR.
testContains your test source code, which is compiled and executed using JUnit or TestNG. These are typically unit tests, but you can include any test in this source set as long as they all share the same compilation and runtime classpaths
SourceSet有一些屬性,比如名字、源文件位置、資源位置、classpath等等,這些屬性有些是只讀的,有些是可寫的,並且可以被當作變量來引用。有可寫的屬性那么就提供了自定義的功能了,比如,你可以改變一個SourceSet源代碼的位置,像這樣下面這樣,你就改變了main這個SourceSet的源代碼目錄和資源目錄。
sourceSets { main { java { srcDirs = ['src/java'] } resources { srcDirs = ['src/resources'] } } }
這樣,gradle就只在src/java下搜源代碼,而不是在src/main/java下。如果你只是想添加額外的目錄,而不想覆蓋原來的目錄,則像下面這樣:
sourceSets { main { java { srcDir 'thirdParty/src/main/java' } } }
此時,gradle就會同時在src/main/java和thirdParty/src/main/java兩個目錄下都進行源代碼搜索。
除了可以更改原有的SourceSet,你也可以添加一個新的SourceSet。比如我們在test這個SourceSet中,做的一般都是單元測試,如果我們要做集成測試和驗收測試,因為這些測試有它們自己的dependencies, classpaths, 以及其他的資源,所以這些測試應該是單獨分開的,而不應該和單元測試混為一談。但是,集成測試和驗收測試也是這個項目的一部分,因此我們也不能為集成測試或驗收測試單獨建立一個項目。它們也不是子項目,所以用subproject也不合適。此時,我們就可以新建一個集成測試或者驗收測試的SourceSet,把相關的測試資源管理起來。比如你需要建立一個集成測試,則你定義如下SourceSet:
sourceSets { integrationTest {
java
resource compileClasspath += sourceSets.test.runtimeClasspath runtimeClasspath += sourceSets.test.runtimeClasspath } }
然后,你添加一個集成測試的運行任務:
task integrationTest(type: Test) { testClassesDir = sourceSets.integrationTest.output.classesDir classpath = sourceSets.integrationTest.runtimeClasspath }
在這個任務中,你指定了測試的目錄為集成測試SourceSet的輸出目錄,classpath為集成測試的runtimeClasspath,這樣,集成測試就可以運行了。
參考:
https://docs.gradle.org/current/userguide/java_plugin.html#sec:java_source_sets
https://blog.csdn.net/honjane/article/details/52579304
