Spring Boot/第二回 Spring Bootで階層モデル

Spring Bootで階層モデルを実装する。
まずは実装の内容なしで、処理の呼び出しがうまくいくことを確認する。

階層モデルとは

Spring Bootの階層モデルは下記のようになる。
f:id:nave_kazu:20150320013616p:plain
HTTPリクエストを起点にそれぞれの階層でそれぞれの役割を果たして処理をリレーする。

Controller

いわゆるMVCのコントローラ。
HTTPを受け取ってサービスを呼び出し、その結果からUIをコントロールする。

Service

ビジネスロジックを書く。
コントローラからの入力値をチェックしたり、データベースの値と比較したり、データベースへの書き込み要求をしたりする。

Repository

永続化処理を書く。
データベースから値を取ったり書いたりする。

Controller

コントローラは下記のように実装する。
@Controllerアノテーションを付けて宣言すると、そのクラスがコントローラとして機能する。

package tools.springsample.springsample02;

import tools.springsample.springsample02.service.SampleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Hello world!
 *
 */
@Controller  // a -> コントローラの目印
@EnableAutoConfiguration  // b -> Springの設定を自動でやってくれるオマジナイ
@ComponentScan  // c -> @Autowiredで指定したコンポーネントをスキャンする場所(パッケージ)を指定
                //      自クラス配下なのでパラメータは不要
public class App {

    @Autowired  // d -> DIコンテナからインスタンスを取得する
    private SampleService sampleService;

    @RequestMapping("/")  // e -> URLとメソッドのマッピング
    @ResponseBody  // f -> 戻り値をレスポンスとして返すという意味
    public String hello() {
        System.out.println("★★★★★ Controller called.");
        return sampleService.getMessage();
    }

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

Service

サービスは下記のように実装する。
これもServiceアノテーションを付けて宣言すると、そのクラスがサービスとして機能する。

package tools.springsample.springsample02.service;

import tools.springsample.springsample02.repository.CustomerRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service  // DIする対象の目印
public class SampleService {
    @Autowired  // d -> DIコンテナからインスタンスを取得する
    private CustomerRepository customerRepository;

    public String getMessage() {
        System.out.println("★★★★★ Service called.");
        return "Hello world. Hello "+customerRepository.getCustomer()+".";
    }
}

Repository

これもRepositoryアノテーションを付けて宣言すると、そのクラスがリポジトリとして機能する。
今は中身は空っぽで。

package tools.springsample.springsample02.repository;

import org.springframework.stereotype.Repository;

@Repository  // DIする対象の目印
public class CustomerRepository {
    public String getCustomer() {
        System.out.println("★★★★★ Repository called.");
        return "Smith";
    }
}

コンパイルして実行

以下のようにコンパイルする。

mvn compile

続いて起動

mvn spring-boot:run

その後、http://localhost:8080/ にアクセスしてコマンドプロンプトに表示される内容を見てみる。

★★★★★ Controller called.
★★★★★ Service called.
★★★★★ Repository called.

お、それぞれの階層の処理が呼ばれている。
今日はここまで。

■ 参考文献 ■

この記事で参考にしたのは「はじめての Spring Boot」です。