EclipseでSpringBoot 動かしてみた


参考

Springの公式ページの「Spring Quickstart Guide」を参考にやってみた。
https://spring.io/quickstart

注意

動くのか確認するためだけのプログラムなので
Mainのクラスにルーティング処理とかController設定とかしちゃってるけど
実際にはこんな書き方はしません。

しっかりレイヤー構成を考慮して作りましょう。

環境

Springのプロジェクトを作成

公式のプロジェクト生成ページで好みに合わせてジェネレート。

  • Gradle
    • Mavenのpomファイルは性に合わないのでビルドシステムはGradleを選択
  • Java 8
    • Kotlinも気になるけどJava
    • Versionはデフォルト設定
  • Spring Boot 2.2.6
    • これは適当
  • Packaging Jar
    • Webであることを考えるとWarだけど試しにJarを選択

GENERATEボタンを押すとプロジェクトがzipでダウンロードされる。

Eclipseでプロジェクトをインポート

Gradleプロジェクトをインポート

ダウンロードしたフォルダを指定

インポートされた

必要なライブラリとかダウンロードされてビルドも勝手に行われて問題なければこんなん出る。

実行

Spring Bootが起動したらこんな感じ

http://localhost:8080/ にアクセス。
まだルーティング処理書いてないので「Whitelabel Error Page」というエラーが出る。

ルーティング処理を作成

プロジェクトに入っているメインのクラスにルーティング処理を追加する。

GETリクエストでリクエストパラメータを取得

package com.pakhuncho.hello;

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

@SpringBootApplication
@RestController
public class HelloApplication {

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

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }
}

変更したアプリケーションを再配置する。

http://localhost:8080/hello でアクセスする。

http://localhost:8080/hello?name=pakhuncho でアクセスする。

http://localhost:8080/hello?name=ぱくぱく でアクセス

パス・パラメータを取得

package com.pakhuncho.hello;

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

@SpringBootApplication
@RestController
public class HelloApplication {

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

    @RequestMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        return String.format("Hello %s!", name);
    }
}

http://localhost:8080/hello/ぱくぱく でアクセス