Setting Up a Clean Gradle Multi-Project Structure from Scratch
This article will guide you through setting up a clean Gradle multi-project structure from scratch.
Project Structure Overview
A typical Gradle multi-project structure looks like this:
1 | my-multi-project/ |
Root Directory Setup
1. Creating settings.gradle
This is the core configuration file for multi-project structures:
1 | rootProject.name = 'my-multi-project' |
2. Gradle Wrapper Setup
Ensure your project includes these essential files:
gradlew
(Unix) andgradlew.bat
(Windows) - Gradle Wrapper executablesgradle/wrapper/gradle-wrapper.jar
- Wrapper JAR filegradle/wrapper/gradle-wrapper.properties
- Wrapper configuration
Initialize the wrapper using:
1 | gradle wrapper |
3. Root build.gradle (Optional)
If you need to manage common settings for all subprojects, create a root build.gradle:
1 | plugins { |
Subproject Configuration
Subproject Independence
For independent subproject operation, create a settings.gradle in the subproject directory:
1 | rootProject.name = 'projectA' |
Subproject build.gradle
Each subproject needs its own build script:
1 | plugins { |
Common Commands
View Project Structure
1 | ./gradlew projects |
Example output:
1 | Root project 'my-multi-project' |
Build Commands
Build all projects:
1 | ./gradlew build |
Build specific project:
1 | ./gradlew :projectA:build |
Running Specific Projects
Run from root directory:
1 | ./gradlew :projectA:run |
Or from subproject directory:
1 | cd projectA |
Best Practices
- Keep root directory clean with only necessary configuration files
- Place common configurations in root build.gradle
- Maintain modular subprojects, avoid excessive dependencies
- Utilize buildSrc directory for custom build logic
- Use version catalogs for unified dependency management
Alternative: Using Kotlin DSL
Gradle also supports Kotlin DSL for build scripts. Here’s how the previous examples would look using Kotlin DSL:
Root settings.gradle.kts
1 | rootProject.name = "my-multi-project" |
Root build.gradle.kts
1 | plugins { |
Subproject build.gradle.kts
1 | plugins { |
Advantages of Kotlin DSL
- Better IDE support with auto-completion
- Strong type checking
- Better refactoring support
- Better Kotlin project integration
However, Kotlin DSL might have:
- Steeper learning curve
- Slightly slower build times
- More verbose syntax in some cases
Important Notes When Using Kotlin DSL
- File names must end with
.gradle.kts
- String literals use double quotes instead of single quotes
- Different syntax for applying plugins and configuring tasks
- Cannot mix Groovy and Kotlin DSL in the same project
Conclusion
This multi-project structure enables:
- Better organization of large projects
- Reuse of common configurations
- Independent module management
- Improved build efficiency
This architecture is ideal for modular large-scale projects, facilitating team collaboration and code management.