Coder Social home page Coder Social logo

enjoy-spring's Introduction

Enjoy Spring!!

プロジェクトの作成

Spring Initializrを使うと便利。

Spring Initializrを開く。

"Dependencies"でWeb, DevToolsを選んで"Generate Project"。

ダウンロードしたdemo.zipを任意の場所に解凍。

src/main/javacom.example.demo.HelloControllerクラスを作る。

package com.example.demo;

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

@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping
    public String sayHello() {
        return "Hello, world!";
    }
}

IDEからcom.example.demo.DemoApplicationを実行して http://localhost:8080/hello をブラウザで開く。

"Dependencies"でJPA, H2を追加で選択して"Generate Project"。

アプリケーションを一旦停止してpom.xmlを差し替えた後に再起動する。

Messageエンティティクラスを作る。

package com.example.demo;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Message implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String content;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

MessageRepositoryインターフェースを作る。

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

public interface MessageRepository extends JpaRepository<Message, Long> {
}

動作確認用のMessageControllerクラスを作る。

package com.example.demo;

import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/messages")
public class MessageController {

    private final MessageRepository repository;

    public MessageController(MessageRepository repository) {
        this.repository = repository;
    }

    @GetMapping
    public List<Message> getAllMessage() {
        return repository.findAll();
    }

    @PostMapping
    public Message post(@RequestParam String content) {
        final Message entity = new Message();
        entity.setContent(content);
        repository.save(entity);
        return entity;
    }
}

次のcurlコマンドでデータの取得ができる。

curl localhost:8080/messages

次のcurlコマンドでデータの登録ができる。

curl localhost:8080/messages -X POST -d "content=My message"

"Dependencies"でThymeleafを追加で選択して"Generate Project"。

アプリケーションを一旦停止してpom.xmlを差し替えた後に再起動する。

MessageControllerクラスを修正する。

package com.example.demo;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/messages")
public class MessageController {

    private final MessageRepository repository;

    public MessageController(MessageRepository repository) {
        this.repository = repository;
    }

    @GetMapping
    public ModelAndView getAllMessage() {
        final String viewName = "message-page";
        final String modelName = "messages";
        final List<Message> modelObject = repository.findAll();
        return new ModelAndView(viewName, modelName, modelObject);
    }

    @PostMapping
    public String post(@RequestParam String content) {
        final Message entity = new Message();
        entity.setContent(content);
        repository.save(entity);
        return "redirect:/messages";
    }
}

src/main/resources/templatesmessage-page.htmlを作成する。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Messages</title>
</head>
<body>
    <h1>Messages</h1>
    <form data-th-action="@{/messages}" method="post">
        <input type="text" name="content" autofocus>
        <button>Submit</button>
    </form>
    <p data-th-each="message : ${messages}"
        data-th-text="${message.id + ': ' + message.content}">Dummy message</p>
</body>
</html>

http://localhost:8080/messages をブラウザで開く。

"Dependencies"でSecurityを追加で選択して"Generate Project"。

アプリケーションを一旦停止してpom.xmlを差し替えた後に再起動する。

http://localhost:8080/messages をブラウザで開く。

ユーザー名はuser、パスワードはアプリケーション起動時にコンソールに出力されるUUID。

ユーザー名とパスワードを変更する場合はsrc/main/resources/にあるapplication.propertiesを変更する。 例えばユーザー名をuragami、パスワードをsecretに変更する場合はapplication.propertiesに次の記述を足す。

spring.security.user.name=uragami
spring.security.user.password=secret

"Dependencies"でActuatorを追加で選択して"Generate Project"。

アプリケーションを一旦停止してpom.xmlを差し替えた後に再起動する。

通常だと見られる情報が限られるのでapplication.propertiesに次の設定を加える。

management.endpoints.web.exposure.include=*

これでメトリクスを取得したり、Springが管理しているコンポーネントを一覧したり、環境値を一覧できる。

エンドポイントの種類 URL
ヘルスチェック http://localhost:8080/actuator/health
メトリクス(CPU使用量) http://localhost:8080/actuator/metrics/process.cpu.usage
メトリクス(メモリ使用量) http://localhost:8080/actuator/metrics/jvm.memory.used
メトリクス(ロードされたクラス数) http://localhost:8080/actuator/metrics/jvm.classes.loaded
メトリクス(ライブスレッド数) http://localhost:8080/actuator/metrics/jvm.threads.live
コンポーネント一覧 http://localhost:8080/actuator/beans
環境値一覧 http://localhost:8080/actuator/env
Spring MVCのエンドポイント一覧 http://localhost:8080/actuator/mappings

"Dependencies"でH2を削除して、PostgreSQLを追加で選択して"Generate Project"。

アプリケーションを一旦停止してpom.xmlを差し替える。

PostgreSQLを起動する。

ここではDockerでの方法を記載する。 次のコマンドでPostgreSQLが起動する。

docker run -d -p 5432:5432 --name=db -e POSTGRES_USER=demo postgres:10.3

接続情報は次の通り。

項目
ホスト localhost
ポート 5432
データベース名 demo
ユーザー名 demo
パスワード demo

Spring Data JPAはデフォルトだと組み込みH2なら勝手にDDLを発行してくれるが、PostgreSQLだと勝手には発行しなくなる。 手動でテーブルの準備をする。

今回はPostgreSQLクライアントもDockerから使用する。 次のコマンドでpsqlを起動する。

docker run -it --rm --link db postgres:10.3 psql -h db demo demo

messageテーブルを作成する。

CREATE TABLE message (
    id BIGINT GENERATED ALWAYS AS IDENTITY,
    content VARCHAR(1000),
    PRIMARY KEY (id)
);

動作確認のためレコードを登録しておく。

INSERT INTO message (content) VALUES ('Hello, world!');

このPostgreSQLと繋ぐためJDBC接続情報をapplication.propertiesへ追加する。

spring.datasource.url=jdbc:postgresql://localhost:5432/demo
spring.datasource.username=demo
spring.datasource.password=demo

アプリケーションを起動して http://localhost:8080/messages をブラウザで開く。

Spring Bootでは、WARを作ってTomcatなどにデプロイするのではなく、JARを作ってjava -jarで実行する。

まずJARを作る。 mvnwというコマンドが付いてくるので、それを使う。 mvnwはMavenを実行するスクリプトで、必要に応じてMaven自体のダウンロードも行ってくれる。

企業内ネットワークなど、プロキシ環境にある場合は環境変数MAVEN_OPTSを設定する必要がある。 例えばプロキシサーバーのホストがexample.com、ポートが3128とすると次のようにMAVEN_OPTSを設定する。

MAVEN_OPTS=-Dhttp.proxyHost=example.com -Dhttp.proxyPort=3128 -Dhttps.proxyHost=example.com -Dhttps.proxyPort=3128

packageゴールでJARを作る。

mvnw package

作ったJARを実行する。

java -jar target/demo-0.0.1-SNAPSHOT.jar

Spring Bootアプリケーションはいくつかの手段で環境毎に設定値を変更できる。

# コマンドライン引数
java -jar target/demo-0.0.1-SNAPSHOT.jar --server.port=8765
# システムプロパティ
java -Dserver.port=8765 -jar target/demo-0.0.1-SNAPSHOT.jar
# 環境変数 (cf. https://12factor.net/ja/config )
SERVER_PORT=8765 java -jar target/demo-0.0.1-SNAPSHOT.jar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.