火曜日, 8月 12, 2025
火曜日, 8月 12, 2025
- Advertisment -
ホームニューステックニュース【作業ログ+解説】Spring Boot 公式チュートリアル

【作業ログ+解説】Spring Boot 公式チュートリアル


Spring Boot を触る機会があり、公式チュートリアルを実施してみました。

筆者は5年前に Java および Spring Boot を触った経験があるのみで、その大部分を忘れています。今回は最初にチュートリアルを実施し、あとから深掘る形式にしました。

さっそくやっていきましょう!

まず初めに公式チュートリアルを進める。

Java は歴史が長くユーザー数も多い。ドキュメントも充実していると判断し、日本語のドキュメントを参照する。

Spring リファレンスドキュメント – Java フレームワーク

環境とバージョン

筆者が使用している OS は macOS である。

Java のバージョンには 21 を選択した。JDK Releases を参照し、最新の LTS が 21 系だったためである。

$ sw_vers
ProductName:		macOS
ProductVersion:		15.6
BuildVersion:		24G84

$ java --version
openjdk 21.0.2 2024-01-16
OpenJDK Runtime Environment (build 21.0.2+13-58)
OpenJDK 64-Bit Server VM (build 21.0.2+13-58, mixed mode, sharing)

$ gradle --version

------------------------------------------------------------
Gradle 9.0.0
------------------------------------------------------------

Build time:    2025-07-31 16:35:12 UTC
Revision:      328772c6bae126949610a8beb59cb227ee580241

Kotlin:        2.2.0
Groovy:        4.0.27
Ant:           Apache Ant(TM) version 1.10.15 compiled on August 25 2024
Launcher JVM:  21.0.2 (Oracle Corporation 21.0.2+13-58)
Daemon JVM:    /Users/user/.local/share/mise/installs/java/21.0.2 (no JDK specified, using current Java home)
OS:            Mac OS X 15.6 aarch64
[余談] Java のライブラリと mise

2025年8月9日現在、最新の Java 21 のバージョンは 21.0.8 (released 2025-07-15) だった。しかし、バージョン管理ツールの mise では、openjdk-21 の最新バージョンは 21.0.2 だった。mise のドキュメント では他にも temurin-21, zulu-21, corretto-21 が挙げられており、それぞれ最新の 21.0.8 まで対応していた。

$ mise ls-remote java | grep '^openjdk-21'
openjdk-21.0.0
openjdk-21.0.1
openjdk-21.0.2

筆者の知識は古いかもしれないが、もろもろのライセンスを回避するために openjdk が丸かったような気がする。Java には2010年に Oracle に買収された歴史があり、そこから様々な実装が存在する認識。そのうち Java 歴史も調べてみたいと感じた。

以下のチュートリアルを進めていく。

最初の Spring Boot アプリケーションの開発 – Spring Boot リファレンス

筆者は IDE に IntelliJ IDEA を使用しているが、”Spring Web” スターターの使用は行わなかった。プロジェクトの基本的な構成を学びたかったためである。必要なツールをインストールし、CLI から操作していく。

前提条件

Java と Maven or Gradle が必要なようだ。確か Gradle の方が後発で便利だった記憶があり、今回は Gradle を選択した。

Java をインストールする。前述の通り、バージョンは 21 系を選択した。筆者が使用してるバージョン管理ツールである mise-en-place を使用してインストールする。

次に Gradle のインストール を行う。Gradle 自体のバージョン管理するかは迷ったが、とりあえずパッケージマネージャー経由でインストールする。

これで必要なツールをインストールすることができた。

$ java --version
openjdk 21.0.2 2024-01-16
OpenJDK Runtime Environment (build 21.0.2+13-58)
OpenJDK 64-Bit Server VM (build 21.0.2+13-58, mixed mode, sharing)

$ gradle --version

------------------------------------------------------------
Gradle 9.0.0
------------------------------------------------------------

Build time:    2025-07-31 16:35:12 UTC
Revision:      328772c6bae126949610a8beb59cb227ee580241

Kotlin:        2.2.0
Groovy:        4.0.27
Ant:           Apache Ant(TM) version 1.10.15 compiled on August 25 2024
Launcher JVM:  21.0.2 (Oracle Corporation 21.0.2+13-58)
Daemon JVM:    /Users/user/.local/share/mise/installs/java/21.0.2 (no JDK specified, using current Java home)
OS:            Mac OS X 15.6 aarch64

リポジトリの作成

GitHub で適当なリポジトリを作成する。名前は spring-boot-tutorial とした。

https://github.com/HitoroOhria/spring-boot-tutorial

筆者は ghq でリポジトリを管理している。ローカルにリポジトリを clone する。

$ ghq get [email protected]:HitoroOhria/spring-boot-tutorial.git

$ cd ~/ghq/github.com/HitoroOhria/spring-boot-tutorial

Gradle でプロジェクトを設定する

build.gradle ファイルを作成する。プロジェクトのビルドに使用されるビルドスクリプトとのこと。Java のバージョンは 21 に変更した。

build.gradle

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.5.4'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '21'

repositories {
	mavenCentral()
}

dependencies {
}

このビルドスクリプトにより、動作するビルドが得られるとのこと。gradle classes でテストできるらしい。しかし、実行してみるとエラーが発生した。

$ gradle classes

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/user/ghq/github.com/HitoroOhria/spring-boot-tutorial/build.gradle' line: 10

* What went wrong:
A problem occurred evaluating root project 'spring-boot-tutorial'.
> Could not set unknown property 'sourceCompatibility' for root project 'spring-boot-tutorial' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to generate a Build Scan (Powered by Develocity).
> Get more help at https://help.gradle.org.

BUILD FAILED in 822ms

sourceCompatibility というプロパティは存在しないらしい。ふむ、なぜ発生するのかわからない。

とりあえず LLM に投げてみた。plugin ブロックで 'io.spring.dependency-management' ツールを指定するのと、java ブロックで Java バージョンを宣言することを教えてくれた。

build.gradle

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.5.4'
	id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = JavaVersion.VERSION_21
	targetCompatibility = JavaVersion.VERSION_21
}

repositories {
	mavenCentral()
}

dependencies {
}

今度はビルドに成功した。

$ gradle classes

BUILD SUCCESSFUL in 559ms
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.0.0/userguide/configuration_cache_enabling.html

また、このコマンドにより .gradle ディレクトリが作成されている。

$ ls -1 .gradle                                     
9.0.0
buildOutputCleanup
vcs-1

sourceCompatibility プロパティの問題は、Gradle のバージョンが関係しているのだろうか?後で調べてみよう。

クラスパスの依存関係を追加する

Spring Boot は、クラスパスに jar を追加できるスターターを多数提供しています。スターターは、特定の種類のアプリケーションを開発するときに必要になる可能性のある依存関係を提供します。

まず、Java のクラスパスというものがわかっていない。jar ファイルは Java プログラムをビルドした成果物だったはず。

Java のクラスパスについて、LLM に聞いてみる。

Java のクラスパス (classpath) とは、Java プログラムの実行時やコンパイル時に、Java クラスファイル(.class)やリソースファイルを探す場所を指定する仕組みです。
Java 仮想マシン(JVM)や javac コンパイラが、プログラム中で使われているクラスを見つけるために使います。

つまり、クラスパスはソースファイルのをマッピングしたものということか。「クラスパスに jar を追加できるスターター」とは、本来はクラスパスにはソースファイルしかマッピングできないが、成果物である jar もマッピングできるようにするツール、だといったん理解する。

org.springframework.boot Gradle プラグインは、便利なデフォルトと Gradle タスクを提供するものであり、io.spring.dependency-management Gradle プラグインは、依存関係管理を提供するものである、と説明されている。

gradle dependencies を実行し、現在のプロジェクトの依存関係を確認する。

$ gradle dependencies 

> Task :dependencies

------------------------------------------------------------
Root project 'spring-boot-tutorial'
------------------------------------------------------------

annotationProcessor - Annotation processors and their dependencies for source set 'main'.
No dependencies

bootArchives - Configuration for Spring Boot archive artifacts. (n)
No dependencies

compileClasspath - Compile classpath for source set 'main'.
No dependencies

compileOnly - Compile-only dependencies for the 'main' feature. (n)
No dependencies

default - Configuration for default artifacts. (n)
No dependencies

developmentOnly - Configuration for development-only dependencies such as Spring Boot's DevTools.
No dependencies

implementation - Implementation dependencies for the 'main' feature. (n)
No dependencies

...

A web-based, searchable dependency report is available by adding the --scan option.

BUILD SUCCESSFUL in 626ms
1 actionable task: 1 executed
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.0.0/userguide/configuration_cache_enabling.html

長い。ツールとその説明、そのツール自体の依存関係が表示されている。表示されたツールはすべて No dependencies となっており、依存関係はない。

新しく spring-boot-starter-web 依存関係を追加する。

build.gradle

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
}

もう一度 gradle dependencies を実行する。

$ gradle dependencies

> Task :dependencies

------------------------------------------------------------
Root project 'spring-boot-tutorial'
------------------------------------------------------------

annotationProcessor - Annotation processors and their dependencies for source set 'main'.
No dependencies

bootArchives - Configuration for Spring Boot archive artifacts. (n)
No dependencies

compileClasspath - Compile classpath for source set 'main'.
\--- org.springframework.boot:spring-boot-starter-web -> 3.5.4
     +--- org.springframework.boot:spring-boot-starter:3.5.4
     |    +--- org.springframework.boot:spring-boot:3.5.4
     |    |    +--- org.springframework:spring-core:6.2.9
     |    |    |    \--- org.springframework:spring-jcl:6.2.9
     |    |    \--- org.springframework:spring-context:6.2.9
     |    |         +--- org.springframework:spring-aop:6.2.9
     |    |         |    +--- org.springframework:spring-beans:6.2.9
     |    |         |    |    \--- org.springframework:spring-core:6.2.9 (*)
     |    |         |    \--- org.springframework:spring-core:6.2.9 (*)
     |    |         +--- org.springframework:spring-beans:6.2.9 (*)
     |    |         +--- org.springframework:spring-core:6.2.9 (*)
     |    |         +--- org.springframework:spring-expression:6.2.9
     |    |         |    \--- org.springframework:spring-core:6.2.9 (*)
     |    |         \--- io.micrometer:micrometer-observation:1.14.9 -> 1.15.2
     |    |              \--- io.micrometer:micrometer-commons:1.15.2
     |    +--- org.springframework.boot:spring-boot-autoconfigure:3.5.4
     |    |    \--- org.springframework.boot:spring-boot:3.5.4 (*)
     |    +--- org.springframework.boot:spring-boot-starter-logging:3.5.4
     |    |    +--- ch.qos.logback:logback-classic:1.5.18
     |    |    |    +--- ch.qos.logback:logback-core:1.5.18
     |    |    |    \--- org.slf4j:slf4j-api:2.0.17
     |    |    +--- org.apache.logging.log4j:log4j-to-slf4j:2.24.3
     |    |    |    +--- org.apache.logging.log4j:log4j-api:2.24.3
     |    |    |    \--- org.slf4j:slf4j-api:2.0.16 -> 2.0.17
     |    |    \--- org.slf4j:jul-to-slf4j:2.0.17
     |    |         \--- org.slf4j:slf4j-api:2.0.17
     |    +--- jakarta.annotation:jakarta.annotation-api:2.1.1
     |    +--- org.springframework:spring-core:6.2.9 (*)
     |    \--- org.yaml:snakeyaml:2.4
...

長い。すべての依存関係がツリー状に展開して表示される。

驚いたのは、依存関係のツールをインストールすることなく、依存関係のリストが表示されたことだ。gradle dependencies コマンドは、build.gradle の内容を元に、ツールの依存関係をリモートに問い合わせていることになる。環境のツールのインストール状況とリンクはしてなさそうだ。いったいいつ、実際にツールをインストールするのだろう?

また、コマンドの最後の方に追記があった。

(c) - A dependency constraint, not a dependency. The dependency affected by the constraint occurs elsewhere in the tree.
(*) - Indicates repeated occurrences of a transitive dependency subtree. Gradle expands transitive dependency subtrees only once per project; repeat occurrences only display the root of the subtree, followed by this annotation.

(n) - A dependency or dependency configuration that cannot be resolved.

依存関係の種類を表現しているようだ。(c) は、依存関係制約であり、依存関係そのものではない。(*) は、推移的な依存関係サブツリーが、繰り返し登場している。(n) は、解決できない依存関係を表す。

(n) が出てきたら怪しい、くらいに覚えておこう。

コードの作成

デフォルトでは、Maven および Gradle は src/main/java からソースをコンパイルします。アプリケーションを完成するには、次の Java ファイルを作成する必要があります。

いよいよ Java プログラムを書いていく。内容を見る限り、/ パスにアクセすると Hello World! を表示する単純な Web アプリケーションのようだ。

src/main/java/com/example/MyApplication.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class MyApplication {

	@RequestMapping("https://zenn.dev/")
	String home() {
		return "Hello World!";
	}

	public static void main(String[] args) {
		SpringApplication.run(MyApplication.class, args);
	}

}

アノテーションと main メソッドの説明があるが、ここでは割愛する。

サンプルの実行

この時点で、アプリケーションは動作するはずです。org.springframework.boot Gradle プラグインを使用したため、アプリケーションの起動に使用できる便利な bootRun ゴールができました。

いよいよアプリケーションを実行していく。

❯ gradle bootRun

> Task :bootRun

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.5.4)

2025-08-10T20:34:14.758+09:00  INFO 75019 --- [           main] com.example.MyApplication                : Starting MyApplication using Java 21.0.2 with PID 75019 (/Users/user/ghq/github.com/HitoroOhria/spring-boot-tutorial/build/classes/java/main started by user in /Users/user/ghq/github.com/HitoroOhria/spring-boot-tutorial)
2025-08-10T20:34:14.759+09:00  INFO 75019 --- [           main] com.example.MyApplication                : No active profile set, falling back to 1 default profile: "default"
2025-08-10T20:34:15.035+09:00  INFO 75019 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2025-08-10T20:34:15.043+09:00  INFO 75019 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2025-08-10T20:34:15.043+09:00  INFO 75019 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.43]
2025-08-10T20:34:15.059+09:00  INFO 75019 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2025-08-10T20:34:15.060+09:00  INFO 75019 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 283 ms
2025-08-10T20:34:15.168+09:00  INFO 75019 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2025-08-10T20:34:15.171+09:00  INFO 75019 --- [           main] com.example.MyApplication                : Started MyApplication in 0.562 seconds (process running for 0.681)
=========---> 80% EXECUTING [37s]
> :bootRun

gradle bootRun コマンドでビルドが走ったようだ。build ディレクトリが作成されている。

$ ls -1 build  
classes
generated
resolvedMainClassName
tmp

ブラウザで http://localhost:8080/ を開いてみよう。レスポンスが表示されている。

実行可能 Jar の作成

本番環境で実行できる、完全に自己完結型の実行可能ファイル jar ファイルを作成します。実行可能 jar は、コンパイルされたクラスとコードの実行に必要なすべての jar 依存関係を含むアーカイブです。

実行可能 jar をビルドしてみよう。

$ gradle bootJar

BUILD SUCCESSFUL in 896ms
3 actionable tasks: 3 executed
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.0.0/userguide/configuration_cache_enabling.html

gradle bootJar コマンドで gradlew 関連のファイルが作成されたようだ。Gradle Wrapper と呼ばれるものだと思うが、後ほど調べてみよう。(Gradle Wrapper セクション)

$ git status
sOn branch main
Your branch is based on 'origin/main', but the upstream is gone.
  (use "git branch --unset-upstream" to fixup)

Untracked files:
  (use "git add ..." to include in what will be committed)
        gradle/wrapper/gradle-wrapper.jar
        gradle/wrapper/gradle-wrapper.properties
        gradlew
        gradlew.bat

nothing added to commit but untracked files present (use "git add" to track)

gradle bootJar コマンドにより、build/libs ディレクトリに実行可能 jar が作成された。実行時ディレクトリがプレフィックスとして付与されるようだ。

$ ls -1 build/libs
spring-boot-tutorial-0.0.1-SNAPSHOT.jar

実行可能 jar を java コマンドから直接起動してみよう。

$ java -jar build/libs/spring-boot-tutorial-0.0.1-SNAPSHOT.jar 

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.5.4)

2025-08-10T20:42:33.595+09:00  INFO 78771 --- [           main] com.example.MyApplication                : Starting MyApplication v0.0.1-SNAPSHOT using Java 21.0.2 with PID 78771 (/Users/user/ghq/github.com/HitoroOhria/spring-boot-tutorial/build/libs/spring-boot-tutorial-0.0.1-SNAPSHOT.jar started by user in /Users/user/ghq/github.com/HitoroOhria/spring-boot-tutorial)
2025-08-10T20:42:33.596+09:00  INFO 78771 --- [           main] com.example.MyApplication                : No active profile set, falling back to 1 default profile: "default"
2025-08-10T20:42:33.970+09:00  INFO 78771 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2025-08-10T20:42:33.977+09:00  INFO 78771 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2025-08-10T20:42:33.977+09:00  INFO 78771 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.43]
2025-08-10T20:42:33.991+09:00  INFO 78771 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2025-08-10T20:42:33.992+09:00  INFO 78771 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 369 ms
2025-08-10T20:42:34.150+09:00  INFO 78771 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2025-08-10T20:42:34.160+09:00  INFO 78771 --- [           main] com.example.MyApplication                : Started MyApplication in 0.745 seconds (process running for 0.967)

こちらも無事に起動できていそうだ。

公式チュートリアルを通して、Spring Boot のプロジェクト構成とアプリケーションの実行までのステップを知ることができた。登場した用語や概念をさらに深掘りしてみよう。

Java

良さげなサイトがなかったため、LLM の回答をまとめる。

  • Java
    • 汎用的でオブジェクト指向のプログラミング言語である
    • その実行環境(Java Platform)を指すこともある
    • 1995年に Sun Microsystems が発表し、現在は Oracle が継承した
  • 特徴
    • プラットフォーム非依存性
      • Java のコードはコンパイルされるとバイトコード(.classファイル)になる
      • バイトコードは Java Virtual Machine (JVM) 上で実行される
      • 「一度書けばどこでも動く(Write Once, Run Anywhere)」ことが可能である
    • オブジェクト指向
      • クラス、継承、カプセル化、ポリモーフィズムといったオブジェクト指向の概念をサポート
    • 豊富な標準ライブラリ
      • ネットワーク、ファイル入出力、データ構造、並行処理など、幅広い機能を標準で提供
    • ガベージコレクション
      • メモリ管理を自動化し、手動でメモリ解放する必要がない
    • セキュリティ
      • JVM 上で実行するため、サンドボックス的な安全性が確保されやすい
  • 構成要素
    • Java 言語
      • ソースコード(.java ファイル)を書くための文法や構文
    • Java コンパイラ (javac)
      • ソースコードをバイトコード(.class)に変換する
    • Java 仮想マシン (JVM)
      • バイトコードを読み取り、実行する環境
    • Java API(ライブラリ)
      • 標準で利用できるクラスやメソッド群。

プラットフォーム非依存、およびバイトコードや JVM の概念の説明は助かった。

クラスパス

以下の記事を読んだが、あまり理解できていない。Java のビルドや実行に関する内部機構を理解する必要がありそうだ。後回しにしよう。

What is a classpath and how do I set it? – Stack Overflow

jar ファイル

  • JAR
    • Java Archive の略称
    • 一般的な ZIP ファイル形式に基づいたファイル形式
    • 多くのファイルを1つに集約するために使用される
      • クラスファイル、画像、音声など

ふむ。アプリケーション開発の文脈においては、アプリケーションをビルドした成果物だと理解しておく。アプリケーションを実行するための単一ファイルであると。

  • Maven
    • Java プロジェクトの構築と管理に使用できるツール
  • 発端
    • Jakarta Turbine プロジェクトのビルドプロセスを簡素化する試みとしてスタートした
    • 複数のサブプロジェクトが存在し、それらを管理する方法が必要だった
      • プロジェクトを構築するための標準的な方法
      • プロジェクトが構成しているものの明確な定義
      • プロジェクト情報を公開する簡単な方法
      • いくつかのプロジェクトでJARを共有する方法
  • 役割
    • ビルドプロセスの簡略化
    • 均一なビルドシステムの提供
    • プロジェクト情報の提供
    • より良い開発習慣の推奨

元々はあるプロジェクトのからスタートし、徐々に広がっていったようだ。本書ではビルドツールに Gradle を選択した。これ以上の深掘りはしない。

  • Gradle Build Tool
    • 宣言的ビルド言語を備えたビルド自動化ツールである
    • タスクの管理、依存関係の管理、ビルドの構成、プラグインの管理などができる
  • サポート
    • Android、Java、Kotlin Multiplatform、Groovy、Scala、JavaScript、C/C++

Java 以外でも使用できるらしい。。さまざまな機能がありそうだ。

Getting Started にある通り、まずはチュートリアルと基本を学ぶことが良さそうだ。

build.gradle ファイル


公式サイトより引用

  • ビルドスクリプト
    • 一般的に、ビルド構成、タスク、プラグインを記述する
  • ビルドスクリプトの種類
    • Groovy で書かれた build.gradle ファイル
    • Kotlin で書かれた build.gradle.kts ファイル
  • 含まれるもの
    • プラグイン
      • Gradle の機能を拡張するツール
      • コードのコンパイル、実行中のテスト、パッケージングアーティファクトなどのタスクを提供する
    • 依存関係
      • プロジェクトが使用する外部ライブラリとツール
  • 2つの依存関係
    • Gradle とビルドスクリプトの依存関係
      • Gradle 自体、ビルドスクリプトロジックに必要なプラグインとライブラリ
    • プロジェクトの依存関係
      • プロジェクトのソースコードをコンパイルして正しく実行するために必要なライブラリ

build.gradle


plugins {   
    
    id 'application'
}


dependencies {  
    
    testImplementation libs.junit.jupiter

    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

    
    implementation libs.guava
}


application {   
    
    mainClass = 'org.example.App'
}

Gradle の本質はビルド構成の定義とタスクの実行だと理解した。

Gradle はさまざまな言語で利用可能なので、プラグインで基本的なツールから追加する必要がある。さらにプラグインを追加し、Gradle にさまざまなタスクを追加していく。コンパイル、アーティファクト作成、テストなどを行うことができる。

依存関係にプロジェクトのライブラリを追加していく。おそらくここで定義したライブラリは、プロジェクトをビルドする時に組み込まれるはずだ。

最後に、規則的なプロパティを追加していく。Java であれば、おそらくプログラムを動かすためにメインクラスを明示的に指定する必要がある。そのようなプロパティを必要に応じて定義していく。

タスク


公式サイトより引用

  • タスク
    • ビルドが実行する独立した作業単位のこと
    • クラスのコンパイル、JARの作成、Javadocの生成、リポジトリへの公開アーカイブなど
  • タスクの種類
    • ソースコードのコンパイル
    • テストの実行
    • パッケージの出力(JAR や APK など)
    • ドキュメントの生成(Javadoc など)
    • 公開リポジトリへのアーティファクトの構築
  • タスクの例
    • ./gradlew build

      • ビルドタスクの実行
    • ./gradlew tasks

      • プロジェクトで利用可能なタスクの一覧
    • ./gradlew run

      • プロジェクトの実行
  • タスクの依存関係
    • Gradle はタスクの依存関係を自動的に解決する
    • たとえば ./gradlew build を実行すると、Gradle は最初に compileJavatestjar などのタスクも実行する

試しに tasks タスクを実行してみよう。

$ ./gradlew tasks

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'spring-boot-tutorial'
------------------------------------------------------------

Application tasks
-----------------
bootRun - Runs this project as a Spring Boot application.
bootTestRun - Runs this project as a Spring Boot application using the test runtime classpath.

Build tasks
-----------
assemble - Assembles the outputs of this project.
bootBuildImage - Builds an OCI image of the application using the output of the bootJar task
bootJar - Assembles an executable jar archive containing the main classes and their dependencies.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
resolveMainClassName - Resolves the name of the application's main class.
resolveTestMainClassName - Resolves the name of the application's test main class.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
updateDaemonJvm - Generates or updates the Gradle Daemon JVM criteria.
wrapper - Generates Gradle wrapper files.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.

Help tasks
----------
artifactTransforms - Displays the Artifact Transforms that can be executed in root project 'spring-boot-tutorial'.
buildEnvironment - Displays all buildscript dependencies declared in root project 'spring-boot-tutorial'.
dependencies - Displays all dependencies declared in root project 'spring-boot-tutorial'.
dependencyInsight - Displays the insight into a specific dependency in root project 'spring-boot-tutorial'.
dependencyManagement - Displays the dependency management declared in root project 'spring-boot-tutorial'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'spring-boot-tutorial'.
projects - Displays the sub-projects of root project 'spring-boot-tutorial'.
properties - Displays the properties of root project 'spring-boot-tutorial'.
resolvableConfigurations - Displays the configurations that can be resolved in root project 'spring-boot-tutorial'.
tasks - Displays the tasks runnable from root project 'spring-boot-tutorial'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.

Rules
-----
Pattern: cleanTaskName>: Cleans the output files of a task.
Pattern: buildConfigurationName>: Assembles the artifacts of a configuration.

To see all tasks and more detail, run gradlew tasks --all

To see more detail about a task, run gradlew help --task task>

BUILD SUCCESSFUL in 602ms
1 actionable task: 1 executed
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.0.0/userguide/configuration_cache_enabling.html

カテゴリー分けして表示してくれるのは助かる。思ったよりリッチな出力だった。

Gradle Wrapper


公式サイトより引用

  • Gradle Wrapper
    • Gradle のバージョンを固定して、Gradle ビルドを実行する方法のこと
  • 実態
    • 事前にダウンロードするスクリプトである
      • gradlew もしくは gradlew.bat
      • gradle wrapper タスクにより作成される
  • 使用方法
  • Gradle Wrapper の追加
  • バージョン管理対象のファイル
    • gradlew (Unix Shell script)
    • gradlew.bat (Windows batch file)
    • gradle/wrapper/gradle-wrapper.jar (Wrapper JAR)
    • gradle/wrapper/gradle-wrapper.properties (Wrapper properties)

やってみよう。

まずは Gradle Wrapper を追加する。

$ gradle wrapper

BUILD SUCCESSFUL in 458ms
1 actionable task: 1 executed
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.0.0/userguide/configuration_cache_enabling.html

以下のファイルが追加される。

  • gradlew (Unix Shell script)
  • gradlew.bat (Windows batch file)
  • gradle/wrapper/gradle-wrapper.jar (Wrapper JAR)
  • gradle/wrapper/gradle-wrapper.properties (Wrapper properties)

次に、Gradle Wrapper を使用する。

❯ ./gradlew build    
Downloading https://services.gradle.org/distributions/gradle-9.0.0-bin.zip
............10%.............20%.............30%.............40%.............50%............60%.............70%.............80%.............90%.............100%

BUILD SUCCESSFUL in 9s
4 actionable tasks: 4 executed
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.0.0/userguide/configuration_cache_enabling.html

初回だったため、プロジェクトに gradle のダウンロードが行われたようだ。

  • Spring Boot
    • 「実行可能」なスタンドアロンの Spring ベースのアプリケーションを簡単に作成できる
    • Spring プラットフォームとサードパーティライブラリについて独自の見解を持っており、最小限のコストで使い始めることができる
      • ほとんどの Spring Boot アプリケーションは、最小限の Spring 設定で済む
  • 特徴
    • スタンドアロンの Spring アプリケーションを作成する
    • Tomcat、Jetty、Undertow が直接含まれている
    • 独自の「スターター」依存関係を提供し、ビルド構成を簡素化する
    • 可能な限り、Spring およびサードパーティのライブラリを自動的に構成する
    • 本番環境ですぐに使用できる機能を提供する
      • メトリクス、ヘルスチェック、外部化された構成など

母体として Spring Framework があり、その高速なスターターが Spring Boot のようだ。

Tomcat、Jetty、Undertow について LLM に聞いた。いずれも「Java のサーブレットコンテナ / HTTP サーバー」のようだ。HTTP サーバーにはデフォルトで Tomcat が選択されているようだが、他の選択肢も含まれれいるのか。

いかがでしたでしょうか。公式チュートリアルの内容もわかりやすく、さすがにドキュメントも豊富です。次回はガイドの方をやっていきたいと思います。



Source link

Views: 0

RELATED ARTICLES

返事を書く

あなたのコメントを入力してください。
ここにあなたの名前を入力してください

- Advertisment -