Spring Boot アプリケーションの構築

このガイドでは、Spring Boot [GitHub] (英語) がアプリケーション開発の加速にどのように役立つかをご紹介します。Spring の入門ガイドを読み進めていくと、Spring Boot のユースケースがさらに増えていくことがわかります。このガイドは、Spring Boot の概要を紹介することを目的としています。独自の SpringBoot ベースプロジェクトを作成したい場合は、Spring Initializr にアクセスし、プロジェクトの詳細を入力し、オプションを選択して、バンドルされたプロジェクトを zip ファイルとしてダウンロードしてください。

構築するもの

Spring Boot を使用して簡単な Web アプリケーションを構築し、それに便利なサービスを追加します。

必要なもの

本ガイドの完成までの流れ

ほとんどの Spring 入門ガイドと同様に、最初から始めて各ステップを完了するか、すでに慣れている場合は基本的なセットアップステップをバイパスできます。いずれにしても、最終的に動作するコードになります。

最初から始めるには、Spring Initializr から開始に進みます。

基本をスキップするには、次の手順を実行します。

完了したときは、gs-spring-boot/complete のコードに対して結果を確認できます。

Spring Boot でできることを学ぶ

Spring Boot は、アプリケーションを迅速に構築する方法を提供します。Spring Boot は、追加した Spring Boot モジュールと設定した Bean を参照し、不足しているものを合理的に推測して追加します。Spring Boot を使用すると、インフラストラクチャへの負担を軽減し、ビジネス機能に重点を置くことができます。

以下の例は、Spring Boot ができることを示しています。

  • spring-boot-starter-webmvc はクラスパス上にありますか? ほぼ必ず必要となる特定の Bean がいくつかあり、Spring Boot はそれらを自動的に追加します。Spring MVC アプリケーションにはサーブレットコンテナーも必要なので、Spring Boot は組み込みの Tomcat を自動的に設定します。

  • Jetty はクラスパス上にあるのに、Tomcat はクラスパス上にありませんか? もしそうなら、Spring Boot がそれを処理し、代わりに Jetty を設定します。

  • spring-boot-starter-thymeleaf はクラスパス上にありますか? もしそうなら、アプリケーションコンテキストに必ず追加する必要がある Bean がいくつかあります。Spring Boot が追加します。

これらは Spring Boot が提供する自動構成のほんの一例です。同時に、Spring Boot はユーザーの操作を邪魔しません。たとえば、Thymeleaf がクラスパス上にある場合、Spring Boot は自動的に SpringTemplateEngine をアプリケーションコンテキストに追加します。しかし、独自の設定で SpringTemplateEngine を定義した場合、Spring Boot は SpringTemplateEngine を追加しません。これにより、ユーザー側ではほとんど手間をかけずに制御できます。

Spring Boot は、コードを生成したり、ファイルを編集したりしません。代わりに、アプリケーションを起動すると、Spring Boot は Bean と設定を動的に結び付け、アプリケーションコンテキストに適用します。

Spring Initializr から開始

IDE を使用する場合はプロジェクト作成ウィザードを使用します。IDE を使用せずにコマンドラインなどで開発する場合は、この事前に初期化されたプロジェクトからプロジェクトを ZIP ファイルとしてダウンロードできます。このプロジェクトは、このチュートリアルの例に合うように構成されています。

プロジェクトを手動で初期化するには:

  1. IDE のメニューまたはブラウザーから Spring Initializr を開きます。アプリケーションに必要なすべての依存関係を取り込み、ほとんどのセットアップを行います。

  2. Gradle または Maven のいずれかと、使用する言語を選択してください。

  3. 依存関係をクリックして、Spring Web を選択します。

  4. 生成をクリックします。

  5. 結果の ZIP ファイルをダウンロードします。これは、選択して構成された Web アプリケーションのアーカイブです。

Eclipse や IntelliJ のような IDE は新規プロジェクト作成ウィザードから Spring Initializr の機能が使用できるため、手動での ZIP ファイルのダウンロードやインポートは不要です。
プロジェクトを GitHub からフォークして、IDE または他のエディターで開くこともできます。

簡単な Web アプリケーションを作成する

これで、次のように、単純な Web アプリケーション用の Web コントローラーを作成できます。

Java
package com.example.springboot;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

  @GetMapping("/")
  public String index() {
    return "Greetings from Spring Boot!";
  }

}
Kotlin
package com.example.springboot

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class HelloController {
  @GetMapping("/")
  fun index(): String = "Greetings from Spring Boot!"
}

クラスには @RestController のフラグが設定されています。これは、Web リクエストを処理するために Spring MVC が使用できる状態になっていることを意味します。@GetMapping は、/ を index() メソッドにマップします。ブラウザーから、またはコマンドラインで curl を使用して呼び出された場合、メソッドは純粋なテキストを返します。これは、@RestController が @Controller と @ResponseBody を組み合わせているためです。これは、Web リクエストがビューではなくデータを返す結果となる 2 つのアノテーションです。

アプリケーションクラスを作成する

Spring Initializr はシンプルなアプリケーションクラスを作成します。しかし、今回の場合はシンプルすぎるため、以下のリストに合わせてアプリケーションクラスを修正する必要があります。

Java
package com.example.springboot;

import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

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

  @Bean
  public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

      System.out.println("Let's inspect the beans provided by Spring Boot:");

      String[] beanNames = ctx.getBeanDefinitionNames();
      Arrays.sort(beanNames);
      for (String beanName : beanNames) {
        System.out.println(beanName);
      }

    };
  }

}
Kotlin
package com.example.springboot

import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean

@SpringBootApplication
class Application {

  @Bean
  fun commandLineRunner(ctx: ApplicationContext) = CommandLineRunner {
    println("Let's inspect the beans provided by Spring Boot:")
    val beanNames = ctx.beanDefinitionNames
    beanNames.sorted().forEach { println(it) }
  }
}

fun main(args: Array<String>) {
  runApplication<Application>(*args)
}

@SpringBootApplication は、次のすべてを追加する便利なアノテーションです。

  • @Configuration: アプリケーションコンテキストの Bean 定義のソースとしてクラスにタグを付けます。

  • @EnableAutoConfiguration: クラスパス設定、他の Bean、さまざまなプロパティ設定に基づいて Bean の追加を開始するよう Spring Boot に指示します。例: spring-webmvc がクラスパスにある場合、このアノテーションはアプリケーションに Web アプリケーションとしてフラグを立て、DispatcherServlet のセットアップなどの主要な動作をアクティブにします。

  • @ComponentScan: Spring に、com/example パッケージ内の他のコンポーネント、構成、サービスを探して、コントローラーを検出させるように指示します。

main() メソッドは、Spring Boot の SpringApplication.run() メソッドを使用してアプリケーションを起動します。XML が 1 行もないことに気付きましたか? web.xml ファイルもありません。この Web アプリケーションは 100% 純粋な Java であり、接続機能やインフラストラクチャの構成に対処する必要はありませんでした。

@Bean としてマークされた CommandLineRunner メソッドも起動時に実行されます。このメソッドは、アプリケーションによって作成された、または Spring Boot によって自動的に追加されたすべての Bean を取得し、ソートして出力します。

アプリケーションの実行

アプリケーションを実行するには、ターミナルウィンドウディレクトリで次のコマンドを実行します。

./gradlew bootRun

Maven を使用する場合は、ターミナルウィンドウディレクトリで次のコマンドを実行します。

./mvnw spring-boot:run

次のような出力が表示されます。

Let's inspect the beans provided by Spring Boot:
application
applicationAvailability
applicationTaskExecutor
applicationTaskExecutorAsyncConfigurer
availabilityProbesHealthEndpointGroupsPostProcessor
basicErrorController
beanNameHandlerMapping
beanNameViewResolver
...

org.springframework.boot.<tech>.autoconfigure の Bean が見えます。tomcatServletWebServerFactory の Bean もあります。

次に、次のコマンド (出力とともに表示) を実行して、curl (別のターミナルウィンドウで) でサービスを実行します。

$ curl http://localhost:8080
Greetings from Spring Boot!

単体テストを追加する

追加したエンドポイントにテストを追加する必要があります。Spring Boot は、サポートするすべてのテクノロジーのテストスターターを提供しています。

Gradle を使用する場合は、build.gradle(.kts) ファイルに次の依存関係を追加します。

Groovy
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
Kotlin
testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test")

Maven を使用する場合は、pom.xml ファイルに次を追加します。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webmvc-test</artifactId>
  <scope>test</scope>
</dependency>

次に、次のように、エンドポイントを介してサーブレットのリクエストとレスポンスをモックする簡単な単体テストを作成します。

Java
package com.example.springboot;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

  @Autowired
  private MockMvc mvc;

  @Test
  public void getHello() throws Exception {
    mvc.perform(get("/").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
  }
}
Kotlin
package com.example.springboot

import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get

@SpringBootTest
@AutoConfigureMockMvc
class HelloControllerTest(@Autowired private val mvc: MockMvc) {

  @Test
  fun getHello() {
    mvc.get("/") {
      accept(MediaType.APPLICATION_JSON)
    }.andExpect {
      status { isOk() }
      content { string("Greetings from Spring Boot!") }
    }
  }
}

MockMvc は Spring Test に由来し、便利なビルダークラスのセットを介して、HTTP リクエストを DispatcherServlet に送信し、結果についてアサーションを作成できます。@AutoConfigureMockMvc および @SpringBootTest を使用して MockMvc インスタンスを注入することに注意してください。@SpringBootTest を使用したため、アプリケーションコンテキスト全体を作成するように求めています。別のメソッドは、@WebMvcTest を使用してコンテキストの Web レイヤーのみを作成するように Spring Boot に依頼することです。いずれの場合も、Spring Boot はアプリケーションのメインアプリケーションクラスを自動的に見つけようとしますが、別のものを構築する場合は、それをオーバーライドするか、絞り込むことができます。

HTTP リクエストサイクルをモックするだけでなく、Spring Boot を使用してシンプルなフルスタック統合テストを作成することもできます。例: 前述のモックテストの代わりに (またはそれに加えて)、次のテストを作成できます。

Java
package com.example.springboot;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.client.RestTestClient;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
public class HelloControllerIntegrationTest {

  @Autowired
  private RestTestClient client;

  @Test
  public void getHello() {
    client.get().uri("/").exchangeSuccessfully()
        .expectBody(String.class)
        .isEqualTo("Greetings from Spring Boot!");
  }
}
Kotlin
package com.example.springboot

import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.web.servlet.client.RestTestClient
import org.springframework.test.web.servlet.client.expectBody

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
class HelloControllerIntegrationTest(@Autowired private val client: RestTestClient) {

  @Test
  fun getHello() {
    client.get().uri("/")
      .exchangeSuccessfully()
      .expectBody<String>()
      .isEqualTo("Greetings from Spring Boot!")
  }
}

組み込みサーバーは webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT のためにランダムなポートで起動し、実際のポートは RestTestClient のベース URL で自動的に構成されます。

本番グレードのサービスを追加する

ビジネス用の Web サイトを構築する場合、管理サービスを追加する必要があるかもしれません。Spring Boot は、アクチュエーターモジュールを使用して、そのようなサービス(ヘルス、監査、Bean など)をいくつか提供しています。

Gradle を使用する場合は、build.gradle(.kts) ファイルに次の依存関係を追加します。

Groovy
implementation 'org.springframework.boot:spring-boot-starter-actuator'
Kotlin
implementation("org.springframework.boot:spring-boot-starter-actuator")

Maven を使用する場合は、pom.xml ファイルに次の依存関係を追加します。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

アプリケーションを再起動します。Gradle を使用している場合は、ターミナルウィンドウで次のコマンドを実行してください。

./gradlew bootRun

Maven を使用する場合は、ターミナルウィンドウで次のコマンドを実行します。

./mvnw spring-boot:run

アプリケーションに新しい RESTful エンドポイントが追加されているはずです。これらは Spring Boot が提供する管理サービスです。以下に典型的な出力を示します。

management.endpoint.health-org.springframework.boot.health.autoconfigure.actuate.endpoint.HealthEndpointProperties
management.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties
management.endpoints.web.cors-org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties
management.health.diskspace-org.springframework.boot.health.autoconfigure.application.DiskSpaceHealthIndicatorProperties
management.health.ssl-org.springframework.boot.health.autoconfigure.application.SslHealthIndicatorProperties
management.info-org.springframework.boot.actuate.autoconfigure.info.InfoContributorProperties
management.metrics-org.springframework.boot.micrometer.metrics.autoconfigure.MetricsProperties
management.observations-org.springframework.boot.micrometer.observation.autoconfigure.ObservationProperties
management.simple.metrics.export-org.springframework.boot.micrometer.metrics.autoconfigure.export.simple.SimpleProperties

アクチュエーターは次を公開します。

/actuator/shutdown エンドポイントも存在しますが、デフォルトでは無効になっています。公開するには、application.properties ファイルに management.endpoint.shutdown.access=unrestricted を追加し、management.endpoints.web.exposure.include=health,info,shutdown で公開してください。ただし、公開アプリケーションではシャットダウンエンドポイントを有効にしない方が良いでしょう。

次のコマンドを実行して、アプリケーションの正常性を確認できます。

$ curl http://localhost:8080/actuator/health
{"status":"UP"}

また、curl を使用してシャットダウンを呼び出して、application.properties に必要な行(前の注を参照)を追加していない場合に何が起こるかを確認することもできます。

$ curl -X POST http://localhost:8080/actuator/shutdown
{"timestamp":"2026-02-06T08:13:01.514Z","status":404,"error":"Not Found","path":"/actuator/shutdown"}

有効にしなかったため、リクエストされたエンドポイントは使用できません(エンドポイントが存在しないため)。

これらの各 REST エンドポイントの詳細と、application.properties ファイル (src/main/resources 内) を使用して設定を調整する方法については、エンドポイントに関するドキュメントを参照してください。

Spring Boot のスターターを見る

スターターをいくつか見てきました。これらはすべてソースコード [GitHub] (英語) で確認できます。

JAR のサポート

最後の例では、Spring Boot を使用して、必要なことに気付かない可能性のある Bean をワイヤリングする方法を示しました。また、便利な管理サービスを有効にする方法も示しました。

ただし、Spring Boot はそれ以上のことを行います。従来の WAR ファイルデプロイだけでなく、Spring Boot のローダーモジュールのおかげで実行可能 JAR をまとめることもできます。さまざまなガイドが、spring-boot-gradle-plugin および spring-boot-maven-plugin によるこの二重サポートを示しています。

要約

おめでとうございます! Spring Boot を使ってシンプルな Web アプリケーションを構築し、開発スピードを加速させる方法を学びました。また、便利な本番環境向けサービスもいくつか利用できました。これは Spring Boot の機能のほんの一部です。さらに詳しい情報は Spring Boot リファレンスガイドを参照してください。

関連事項

次のガイドも役立つかもしれません:

新しいガイドを作成したり、既存のガイドに貢献したいですか? 投稿ガイドラインを参照してください [GitHub] (英語) 。

すべてのガイドは、コード用の ASLv2 ライセンス、およびドキュメント用の帰属表示、NoDerivatives クリエイティブコモンズライセンス (英語) でリリースされています。

コードを入手する

FREE

クラウドでの作業

Spring アカデミーのクラウドでガイドを完成させよう。

Spring アカデミーへ