モーダルを閉じる工作HardwareHub ロゴ画像

工作HardwareHubは、ロボット工作や電子工作に関する情報やモノが行き交うコミュニティサイトです。さらに詳しく

利用規約、プライバシーポリシー に同意したうえでログインしてください。

工作HardwareHub ロゴ画像 (Laptop端末利用時)
工作HardwareHub ロゴ画像 (Mobile端末利用時)

Spring Boot 環境構築 (Java/Gradle)

モーダルを閉じる

ステッカーを選択してください

モーダルを閉じる

お支払い内容をご確認ください

購入商品
「」ステッカーの表示権
メッセージ
料金
¥(税込)
決済方法
GooglePayマーク
決済プラットフォーム
確認事項

※利用規約をご確認のうえお支払いください

※カード情報はGoogleアカウント内に保存されます。本サイトやStripeには保存されません

※記事の執筆者は購入者のユーザー名を知ることができます

※購入後のキャンセルはできません

公開日公開日
2017/05/02
最終更新最終更新
2019/09/26
記事区分記事区分
一般公開

目次

    アカウント プロフィール画像 (サイドバー)

    Spring Bootでの実用的な機能をわかりやすく解説中

    0
    ステッカーを贈るとは?

    Spring は様々なフレームワークを提供する、Java のプロジェクト群です。Spring Batch、Spring Security、Spring Loaded といったプロジェクトがあります。Spring Boot は、これら Spring フレームワークを内部的に利用するフレームワークです。効率的なアプリケーション開発が可能になります。環境構築の手順を把握できるサンプルコードをまとめます。一通り把握できたら、次回以降は雛形を Spring Initializr で生成して、以下の公式ドキュメントを参考にしつつ開発できます。

    サンプルコード

    ディレクトリの作成

    ディレクトリを以下のように作成します。

    mkdir -p src/main/java/hello
    mkdir -p src/test/java/hello
    

    Gradle 設定

    ビルドスクリプトを作成します。特に Gradle の場合は以下のようになります。

    touch build.gradle
    

    build.gradle

    buildscript {
        ext {
            springBootVersion = '1.5.3.RELEASE'
        }
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        }
    }
    
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'idea'
    apply plugin: 'org.springframework.boot'
    
    jar {
        baseName = 'gs-spring-boot'
        version =  '0.1.0'
    }
    
    repositories {
        mavenCentral()
    }
    
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    
    dependencies {
    
        // Tomcat の代わりに Jetty を使用してみます。
        compile('org.springframework.boot:spring-boot-starter-web') {
            exclude module: 'spring-boot-starter-tomcat'
        }
        compile('org.springframework.boot:spring-boot-starter-jetty')
    
        // '/health' エンドポイントなどを自動で追加するライブラリです。
        // https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html
        compile('org.springframework.boot:spring-boot-starter-actuator')
    
        // Spring Test を利用できるように設定します。
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }
    
    項目 概要
    buildscript 文字通りビルドスクリプト build.gradle の設定を行います。
    ext extra properties を設定します。properties タスクで表示できる項目に加えて、独自定数を追加します。
    repositories 依存するレポジトリを設定します。buildscript ブロック内であれば、ビルドスクリプトが依存するレポジトリになります。buildscript ブロック外であれば、プロジェクトが依存するレポジトリになります。mavenCentral() は The Central Repository です。jcenter() レポジトリも有名です。社内に独自レポジトリが存在する場合もここで設定します。
    dependencies 依存するレポジトリ内のうち、使用するライブラリを指定します。
    apply plugin ビルドスクリプト build.gradle で必要になるプラグインを設定します。
    jar 成果物 JAR ファイルの名称を設定します。
    sourceCompatibility コンパイル時に必要になる Java のバージョンを指定します。例えば 1.8 を指定している場合は、実際には Java 1.7 ではコンパイルできるようなソースコードであっても、コンパイルに失敗するように設定したことになります。Java 8 で追加された記法を使用している場合などは、設定しておいたほうが親切です。
    targetCompatibility コンパイルしたクラスファイルを動作させる想定の JVM のバージョンを指定します。sourceCompatibility と同じ値が既定値になります。
    compile プロジェクトが実行時に依存するライブラリを指定します。
    testCompile プロジェクトがテスト実行時に依存するライブラリを指定します。

    Java ソースコード (後述)

    touch src/main/java/hello/Application.java
    touch src/main/java/hello/HelloController.java
    touch src/test/java/hello/HelloControllerTest.java
    touch src/test/java/hello/HelloControllerIT.java
    

    ビルドおよび実行

    gradle wrapper
    ./gradlew build
    java -jar build/libs/gs-spring-boot-0.1.0.jar
    

    curl 実行例

    $ curl http://localhost:8080/
    Greetings from Spring Boot!
    
    $ curl -s http://localhost:8080/health | jq .
    {
      "status": "UP"
    }
    

    Java ソースコード

    src/main/java/hello/Application.java

    package hello;
    
    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); // 定義された Bean 名を出力します。`commandLineRunner` も含まれます。
                }
            };
        }
    }
    
    項目 概要
    @SpringBootApplication @Configuration, @EnableAutoConfiguration, @ComponentScan を統合したアノテーションです。
    @Bean @Configuration が設定されたクラスのメソッドに対して設定できます。@Bean 設定されたメソッドはインスタンスを返します。これは設定値をもつシングルトンとして、アプリケーション全体で利用できます。CommandLineRunner を返す Bean 定義は特殊で、アプリケーション起動時に実行される処理を設定できます。

    src/main/java/hello/HelloController.java

    package hello;
    
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @RestController
    public class HelloController {
    
        @RequestMapping("/")
        public String index() {
            return "Greetings from Spring Boot!";
        }
    }
    
    項目 概要
    @RestController @Controller と @ResponseBody を統合したアノテーションです。View ではなくテキストをそのまま返すコントローラとして設定されます。
    @RequestMapping("/") 設定したパスのアクションとしてメソッド index() が設定されます。

    src/test/java/hello/HelloControllerTest.java

    Mock を利用したテスト

    package hello;
    
    import static org.hamcrest.Matchers.equalTo;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class HelloControllerTest {
    
        @Autowired
        private MockMvc mvc;
    
        @Test
        public void getHello() throws Exception {
            mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
        }
    }
    

    src/test/java/hello/HelloControllerIT.java

    Mock を利用しない Integration テスト

    package hello;
    
    import static org.hamcrest.Matchers.equalTo;
    import static org.junit.Assert.assertThat;
    
    import java.net.URL;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.embedded.LocalServerPort;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.web.client.TestRestTemplate;
    import org.springframework.http.ResponseEntity;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class HelloControllerIT {
    
        @LocalServerPort
        private int port;
    
        private URL base;
    
        @Autowired
        private TestRestTemplate template;
    
        @Before
        public void setUp() throws Exception {
            this.base = new URL("http://localhost:" + port + "/");
        }
    
        @Test
        public void getHello() throws Exception {
            ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
            assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
        }
    }
    

    Spring Tool Suite (Eclipse-based IDE)

    Spring プロジェクト向けにカスタマイズされた Eclipse が存在します。こちらのページからダウンロードして利用できます。

    0
    詳細設定を開く/閉じる
    アカウント プロフィール画像 (本文下)

    Spring Bootでの実用的な機能をわかりやすく解説中

    記事の執筆者にステッカーを贈る

    有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。

    さらに詳しく →
    ステッカーを贈る コンセプト画像

    Feedbacks

    Feedbacks コンセプト画像

      ログインするとコメントを投稿できます。

      関連記事

      • Spring Security フォームログインのサンプルコード
        Spring フレームワークによる Web アプリケーション開発で、ログイン処理を実装する際は Spring Security が便利です。ここでは特に Spring Boot で Web アプリケーションを開発する場合を対象とし、フォームによる ID/Password ログインを行うためのサンプルコードをまとめます。 公式ドキュメント [Spring Security チュートリアル](http...
        えびちゃんえびちゃん12/4/2019に更新
        いいねアイコン画像0
      • Java配列の宣言方法 (C/C++との違い)
        Javaの配列 Javaの配列宣言方法はC/C++と似ているようで若干異なる。 初期化しない場合 C/C++の int array[10]; はJavaでは int array[] = new int[10]; となる。同様にC/C++の int array[3][3]; はJavaでは int array[][] = new int[3][3]; となる。 初期化
        てんとうむしてんとうむし5/13/2018に更新
        いいねアイコン画像0
      • PlantUML による UML 図の描き方
        サムネイル画像-c788fffde5
        PlantUML はテキスト形式で表現されたシーケンス図やクラス図といった UML (Unified Modeling Language) 図の情報から画像を生成するためのツールです。簡単な使い方をまとめます。 インストール方法の選択 Atom や Eclipse のプラグインをインストールしてエディタから利用する方法、JAR をダウンロードして Java コマンドで実行する方法、Redmine ...
        kentakenta1/21/2020に更新
        いいねアイコン画像0
      • Akka HTTP サンプルコード (Scala)
        サムネイル画像-a98142497c
        Akka アクターを用いて実装された汎用 HTTP フレームワークです。Spray の後継です。コアモジュールである akka-http-core は 2016/2/17 に experimental が外れました。akka-http などのいくつかのサブモジュールは 2016/3/1 現在 experimental のままですが、基本的な
        雄太雄太10/7/2021に更新
        いいねアイコン画像0
      • Kestrel の使用例
        Kestrel は Message Queue (MQ) の実装のひとつです。一般に MQ はアプリケーション間やプロセス間、スレッド間で非同期に通信するために用いられます。メッセージの送信側は MQ に書き込めば受信側の応答を待たずに次の処理に非同期に進むことができます。Kestrel はわずか 2500 行程の Scala で実装されており JVM で動作します。MQ 自体はメモリ上に存在する...
        したくんしたくん10/12/2017に更新
        いいねアイコン画像0