Gradle詳細
Gradleの詳細解説
Section titled “Gradleの詳細解説”Gradleは、GroovyまたはKotlin DSLを使用する柔軟なビルドツールです。この章では、Gradleの詳細な使い方と実践的な設定方法について解説します。
Gradleの基本概念
Section titled “Gradleの基本概念”プロジェクト構造
Section titled “プロジェクト構造”my-project/├── build.gradle # ビルドスクリプト(Groovy DSL)├── build.gradle.kts # ビルドスクリプト(Kotlin DSL)├── settings.gradle # プロジェクト設定├── gradle.properties # Gradleプロパティ├── gradle/│ └── wrapper/ # Gradle Wrapper│ ├── gradle-wrapper.jar│ └── gradle-wrapper.properties└── src/ ├── main/ │ ├── java/ │ └── resources/ └── test/ ├── java/ └── resources/build.gradleの詳細設定
Section titled “build.gradleの詳細設定”基本的なbuild.gradle(Groovy DSL)
Section titled “基本的なbuild.gradle(Groovy DSL)”// プラグインの適用plugins { id 'java' id 'org.springframework.boot' version '3.1.0' id 'io.spring.dependency-management' version '1.1.0'}
// プロジェクト情報group = 'com.example'version = '1.0.0'sourceCompatibility = '17'targetCompatibility = '17'
// リポジトリの設定repositories { mavenCentral() // Maven Centralリポジトリ maven { url 'https://repo.spring.io/milestone' } // Springリポジトリ mavenLocal() // ローカルMavenリポジトリ}
// 依存関係の定義dependencies { // 実装依存関係(コンパイル時と実行時に必要) implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.postgresql:postgresql'
// 開発時のみ必要な依存関係 developmentOnly 'org.springframework.boot:spring-boot-devtools'
// テスト時にのみ必要な依存関係 testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.junit.jupiter:junit-jupiter-api' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
// コンパイル時のみ必要な依存関係 compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
// 実行時のみ必要な依存関係 runtimeOnly 'com.h2database:h2'}
// テスト設定test { useJUnitPlatform() testLogging { events 'passed', 'skipped', 'failed' }}
// カスタムタスクtask hello { doLast { println 'Hello, Gradle!' }}build.gradle.kts(Kotlin DSL)
Section titled “build.gradle.kts(Kotlin DSL)”// プラグインの適用plugins { java id("org.springframework.boot") version "3.1.0" id("io.spring.dependency-management") version "1.1.0"}
// プロジェクト情報group = "com.example"version = "1.0.0"java.sourceCompatibility = JavaVersion.VERSION_17java.targetCompatibility = JavaVersion.VERSION_17
// リポジトリの設定repositories { mavenCentral() maven { url = uri("https://repo.spring.io/milestone") } mavenLocal()}
// 依存関係の定義dependencies { // 実装依存関係 implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter-data-jpa") implementation("org.postgresql:postgresql")
// 開発時のみ developmentOnly("org.springframework.boot:spring-boot-devtools")
// テスト時のみ testImplementation("org.springframework.boot:spring-boot-starter-test") testImplementation("org.junit.jupiter:junit-jupiter-api") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
// コンパイル時のみ compileOnly("org.projectlombok:lombok") annotationProcessor("org.projectlombok:lombok")
// 実行時のみ runtimeOnly("com.h2database:h2")}
// テスト設定tasks.test { useJUnitPlatform() testLogging { events("passed", "skipped", "failed") }}
// カスタムタスクtasks.register("hello") { doLast { println("Hello, Gradle!") }}依存関係の管理
Section titled “依存関係の管理”依存関係のスコープ
Section titled “依存関係のスコープ”dependencies { // implementation: コンパイル時と実行時に必要(推奨) implementation 'org.springframework.boot:spring-boot-starter-web'
// api: implementationと同様だが、依存関係が公開される(ライブラリ開発時) api 'com.example:my-library:1.0.0'
// compileOnly: コンパイル時のみ必要(実行時は提供される) compileOnly 'org.projectlombok:lombok'
// runtimeOnly: 実行時のみ必要 runtimeOnly 'com.h2database:h2'
// testImplementation: テスト時にのみ必要 testImplementation 'junit:junit:4.13.2'
// testRuntimeOnly: テスト実行時のみ必要 testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
// developmentOnly: 開発時のみ必要 developmentOnly 'org.springframework.boot:spring-boot-devtools'}バージョン管理
Section titled “バージョン管理”// 1. 直接指定dependencies { implementation 'org.springframework.boot:spring-boot-starter-web:3.1.0'}
// 2. 変数を使用ext { springBootVersion = '3.1.0' junitVersion = '5.9.2'}
dependencies { implementation "org.springframework.boot:spring-boot-starter-web:${springBootVersion}" testImplementation "org.junit.jupiter:junit-jupiter:${junitVersion}"}
// 3. gradle.propertiesを使用// gradle.propertiesspringBootVersion=3.1.0junitVersion=5.9.2
// build.gradledependencies { implementation "org.springframework.boot:spring-boot-starter-web:$springBootVersion" testImplementation "org.junit.jupiter:junit-jupiter:$junitVersion"}依存関係の除外
Section titled “依存関係の除外”dependencies { implementation('org.springframework.boot:spring-boot-starter-web') { // 特定の依存関係を除外 exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' }
// 複数の依存関係を除外 implementation('com.example:my-library:1.0.0') { exclude group: 'org.slf4j' exclude group: 'log4j', module: 'log4j' }
// すべての推移的依存関係から特定のモジュールを除外 configurations.all { exclude group: 'commons-logging', module: 'commons-logging' }}カスタムタスクの作成
Section titled “カスタムタスクの作成”基本的なタスク
Section titled “基本的なタスク”// シンプルなタスクtask hello { doLast { println 'Hello, Gradle!' }}
// タスクの依存関係task compile { doLast { println 'Compiling...' }}
task test { dependsOn compile // compileタスクの後に実行 doLast { println 'Testing...' }}
// 条件付きタスクtask build { doLast { if (project.hasProperty('skipTests')) { println 'Skipping tests' } else { println 'Running tests' } }}高度なタスク
Section titled “高度なタスク”// ファイル操作タスクtask copyResources(type: Copy) { from 'src/main/resources' into 'build/resources' include '**/*.properties' exclude '**/*.tmp'}
// アーカイブ作成タスクtask createJar(type: Jar) { archiveBaseName = 'my-app' from sourceSets.main.output manifest { attributes 'Main-Class': 'com.example.MyApp' }}
// カスタムタスククラスclass MyCustomTask extends DefaultTask { @TaskAction void execute() { println "Executing custom task" }}
task customTask(type: MyCustomTask) { // カスタムタスクの設定}マルチプロジェクトの構成
Section titled “マルチプロジェクトの構成”settings.gradle
Section titled “settings.gradle”rootProject.name = 'my-multi-project'
include 'core'include 'web'include 'api'
project(':core').projectDir = file('modules/core')project(':web').projectDir = file('modules/web')project(':api').projectDir = file('modules/api')ルートのbuild.gradle
Section titled “ルートのbuild.gradle”// ルートプロジェクトのbuild.gradleallprojects { repositories { mavenCentral() }}
subprojects { apply plugin: 'java'
sourceCompatibility = '17' targetCompatibility = '17'
dependencies { testImplementation 'junit:junit:4.13.2' }}
// 特定のサブプロジェクトのみに適用project(':web') { dependencies { implementation project(':core') implementation 'org.springframework.boot:spring-boot-starter-web' }}サブプロジェクトのbuild.gradle
Section titled “サブプロジェクトのbuild.gradle”dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa'}
// modules/web/build.gradledependencies { implementation project(':core') // 他のサブプロジェクトに依存 implementation 'org.springframework.boot:spring-boot-starter-web'}Gradle Wrapper
Section titled “Gradle Wrapper”Wrapperの生成
Section titled “Wrapperの生成”# Wrapperを生成gradle wrapper --gradle-version 8.0
# 生成されるファイル# gradle/wrapper/gradle-wrapper.jar# gradle/wrapper/gradle-wrapper.propertiesgradle-wrapper.properties
Section titled “gradle-wrapper.properties”distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zipnetworkTimeout=10000zipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsWrapperの使用
Section titled “Wrapperの使用”# Windowsgradlew.bat build
# macOS/Linux./gradlew buildプラグインの使用
Section titled “プラグインの使用”標準プラグイン
Section titled “標準プラグイン”plugins { id 'java' id 'application' // アプリケーション実行用 id 'java-library' // ライブラリ開発用 id 'war' // WARファイル作成用}
application { mainClass = 'com.example.MyApp'}サードパーティプラグイン
Section titled “サードパーティプラグイン”// プラグインの適用plugins { id 'org.springframework.boot' version '3.1.0' id 'io.spring.dependency-management' version '1.1.0' id 'com.github.johnrengelman.shadow' version '8.1.1'}
// または、buildscriptブロックを使用(古い方法)buildscript { repositories { mavenCentral() } dependencies { classpath 'org.springframework.boot:spring-boot-gradle-plugin:3.1.0' }}
apply plugin: 'org.springframework.boot'ビルドの最適化
Section titled “ビルドの最適化”ビルドキャッシュ
Section titled “ビルドキャッシュ”org.gradle.caching=trueorg.gradle.parallel=trueorg.gradle.configureondemand=trueorg.gradle.daemon=trueorg.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512mインクリメンタルビルド
Section titled “インクリメンタルビルド”// タスクの入力と出力を定義することで、インクリメンタルビルドが有効になるtask processResources { inputs.dir 'src/main/resources' outputs.dir 'build/resources'
doLast { copy { from 'src/main/resources' into 'build/resources' } }}プロファイルの使用
Section titled “プロファイルの使用”環境別の設定
Section titled “環境別の設定”def environment = project.hasProperty('env') ? project.env : 'dev'
sourceSets { main { resources { srcDirs "src/main/resources", "src/main/resources-${environment}" } }}
dependencies { if (environment == 'prod') { runtimeOnly 'org.postgresql:postgresql' } else { runtimeOnly 'com.h2database:h2' }}使用例:
# 開発環境./gradlew build -Penv=dev
# 本番環境./gradlew build -Penv=prodよく使うGradleコマンド
Section titled “よく使うGradleコマンド”# プロジェクトのビルド./gradlew build
# クリーンビルド./gradlew clean build
# テストの実行./gradlew test
# 特定のタスクの実行./gradlew hello
# タスクの一覧表示./gradlew tasks
# 依存関係の表示./gradlew dependencies
# 依存関係の更新確認./gradlew dependencyUpdates
# Spring Bootアプリケーションの実行./gradlew bootRun
# デバッグモードで実行./gradlew bootRun --debug-jvm
# 並列ビルド./gradlew build --parallel
# ビルドキャッシュを使用./gradlew build --build-cacheトラブルシューティング
Section titled “トラブルシューティング”よくある問題と解決方法
Section titled “よくある問題と解決方法”問題1: 依存関係の解決エラー
// 解決方法: リポジトリを追加repositories { mavenCentral() maven { url 'https://repo.spring.io/milestone' } // 必要に応じて追加のリポジトリを指定}問題2: ビルドが遅い
# gradle.propertiesに追加org.gradle.parallel=trueorg.gradle.caching=trueorg.gradle.daemon=trueorg.gradle.jvmargs=-Xmx2048m問題3: メモリ不足エラー
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryErrorSpring BootプロジェクトでのGradle設定例
Section titled “Spring BootプロジェクトでのGradle設定例”完全なbuild.gradle
Section titled “完全なbuild.gradle”plugins { id 'java' id 'org.springframework.boot' version '3.1.0' id 'io.spring.dependency-management' version '1.1.0'}
group = 'com.example'version = '1.0.0'sourceCompatibility = '17'
configurations { compileOnly { extendsFrom annotationProcessor }}
repositories { mavenCentral()}
dependencies { // Spring Boot Starters implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-security'
// データベース runtimeOnly 'org.postgresql:postgresql'
// Lombok compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
// 開発ツール developmentOnly 'org.springframework.boot:spring-boot-devtools'
// テスト testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test'}
test { useJUnitPlatform() testLogging { events 'passed', 'skipped', 'failed' exceptionFormat 'full' }}
// Spring Bootアプリケーションの実行設定bootRun { jvmArgs = ['-Dspring.profiles.active=dev']}
// JARファイルの設定jar { enabled = false // Spring BootのJARを使用するため、標準JARは無効化}
// カスタムタスク: コードフォーマットtask formatCode(type: Exec) { commandLine 'prettier', '--write', 'src/**/*.java'}
// カスタムタスク: コード品質チェックtask checkCodeQuality { dependsOn test doLast { println 'Code quality check completed' }}Gradleの主要な機能:
- 柔軟なDSL: GroovyまたはKotlin DSLで記述
- 依存関係管理: 細かいスコープ制御
- カスタムタスク: 独自のビルドタスクを作成
- マルチプロジェクト: 大規模プロジェクトの管理
- Gradle Wrapper: 環境に依存しないビルド
- プラグインエコシステム: 豊富なプラグイン
- ビルド最適化: インクリメンタルビルド、並列ビルド
これらの機能を適切に使用することで、効率的なビルドプロセスを構築できます。