内容
- SpringBootで簡単なCRUDアプリを作る
- 今回は雛形を作って動作確認まで
雛形作成
SpringInitializrを使う
- ここでzipを落としてもいいけど今回はSTSプラグインから作成
- Eclipseの場合STSプラグインはヘルプの中のEclipseマーケットプレイスからダウンロードできる
手順
- 雛形作成

- サンプルなのでアプリ名はなんでもいい

- ビルドツールはmavenとgradleどちらもよく使われているが今回はmavenを選択
- 今回作る範囲ではどちらを選んでもさほど変わらない

- 必要なライブラリを選択すると同梱した状態で雛形ができる
- 今回は以下の5つを選択(後からでも追加可能)
- Devtools・・・ホットデプロイとかできるようになる
- JPA・・・JavaとDBをつなぐORMapper
- H2・・・インメモリのDB
- Thymeleaf・・・テンプレートエンジン
- Web・・・エンドポイント(URL)を簡単に作れる
アプリの起動
- 雛形の生成が終わったらまずは動作確認
- アプリの起動はBootダッシュボードを使うと便利

- Bootダッシュボードが表示されてない場合は以下の手順で追加できる


- 起動するとコンソールにこんな感じの出力がされる

- 最後にstartedと出ていれば正常に起動が完了している
- アプリの起動は以下のコマンドでターミナル上で実行することもできる
mvn spring-boot:run
雛形で生成されたファイルの確認
BaseballApplication.java
src/main/java/com/example/baseball/BaseballApplication.java
package com.example.baseball;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BaseballApplication {
public static void main(String[] args) {
SpringApplication.run(BaseballApplication.class, args);
}
}
- このmainメソッドがアプリのエントリーポイントになり、Springアプリを起動している
application.properties
src/main/resources/application.properties
- この時点では空のファイル
- アプリに関する設定を記述する
BaseballApplicationTests.java
src/test/java/com/example/baseball/BaseballApplicationTests.java
package com.example.baseball;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseballApplicationTests {
@Test
public void contextLoads() {
}
}
- テストコードの雛形
- テストは以下のメニューから実行できる

HelloWorldをブラウザから確認
- http://localhost:8080/ にアクセスするとHelloWorldと表示されるようにする
手順
- 作るファイルは2つ
- 1つ目はユーザからのアクセスを受け取ってテンプレートを返すファイル
- 2つ目はユーザに返すテンプレート
HelloWorld.java
-
com.example.baseball
にHelloWorld.java
を作成する
src/main/java/com/example/baseball/HelloWorld.java
package com.example.baseball;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller // ①
public class HelloWorld {
@GetMapping("/") // ②
public String hello() {
return "hello"; // ③
}
}
- ①:
@Controller
をつけることでこのClassがユーザからのアクセスを受け取ることができる - ②:
@GetMapping("/")
とすると、httpメソッドがGETでURLが/
のアクセスがあるとこのメソッドが呼ばれるようになる- ()の中のパスは、
http://localhost:8080
に続く内容を表す - 例えば
@GetMapping("/users")
だとhttp://localhost:8080/users
にマッピングされる
- ()の中のパスは、
- ③:
src/main/resources/templates/
配下のhello.html
をユーザに返す- Stringを返しているだけなのになぜそんな動きをするかというと、このClassに
@Controller
がついているから
- Stringを返しているだけなのになぜそんな動きをするかというと、このClassに
hello.html
-
src/main/resources/templates/
にhello.html
を作成する
src/main/resources/templates/hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>baseball</title>
</head>
<body>
<h1>HelloWorld</h1>
</body>
</html>
動作確認
- http://localhost:8080/ にアクセスすると以下の画面が表示される

ホットデプロイ
- ファイルを追加/修正をアプリを起動した状態で行うと、変更が保存される度に自動的にアプリが再起動される
- 雛形生成時にdevtoolsを入れたからこのような動きをする
次回
- 続きはこちら