Spring Boot/第一回 Spring Boot事始め

Spring Bootを使ってみたのでメモする。

参考にしたのは「はじめての Spring Boot」。

Mavenでプロジェクト作成

以下でプロジェクト作成。

mvn archetype:create -DgroupId=tools.springsample.springsample01 -DartifactId=SpringSample01 -Dversion1.0.0-SNAPSHOT

準備(Mavenまわりの設定)

pom.xmlにSpring Boot関係の記述を追加する。

セントラルリポジトリの指定(なぜか指定しないとエラーになる)。

  <!-- append start -->
  <repositories>
    <repository>
      <id>central</id>
      <url>http://central.maven.org/maven2/</url>
    </repository>
  </repositories>
  <!-- append end -->

Spring Bootのテンプレートを親に。

  <!-- append start -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.5.RELEASE</version>
  </parent>
  <!-- append end -->

Spring Bootの依存関係を追加。

  <dependencies>
    <!-- append start -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- append end -->
  </dependencies>

Spring Bootのプラグインを追加。

  <!-- append start -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
  <!-- append end -->

ビルドターゲットは Java8。

  <properties>
    <!-- append start -->
    <java.version>1.8</java.version>
    <!-- append end -->
  </properties>

Spring Bootとは関係ないが、アクセサメソッドを作るのが面倒なのでLombokを使う。

  <dependencies>
    <!-- append start -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.12.2</version>
      <scope>provided</scope>
    </dependency>
    <!-- append end -->
  </dependencies>

pom.xmlが間違えていないかコンパイルしてみる。

mvn compile

ついでに依存関係ツリーも確認

mvn dependency:tree

以下のようになる。

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringSample01 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ SpringSample01 ---
[INFO] tools.springsample.springsample01:SpringSample01:jar:1.0-SNAPSHOT
[INFO] +- junit:junit:jar:3.8.1:test
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.1.5.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.1.5.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.1.5.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.1.5.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.1.5.RELEASE:compile
[INFO] |  |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.7:compile
[INFO] |  |  |  |  \- org.slf4j:slf4j-api:jar:1.7.7:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.7:compile
[INFO] |  |  |  +- org.slf4j:log4j-over-slf4j:jar:1.7.7:compile
[INFO] |  |  |  \- ch.qos.logback:logback-classic:jar:1.1.2:compile
[INFO] |  |  |     \- ch.qos.logback:logback-core:jar:1.1.2:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.13:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.1.5.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:7.0.54:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:7.0.54:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-logging-juli:jar:7.0.54:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.3.3:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.3.3:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.3.3:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.0.3.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.1.1.GA:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.0.0:compile
[INFO] |  +- org.springframework:spring-core:jar:4.0.6.RELEASE:compile
[INFO] |  +- org.springframework:spring-web:jar:4.0.6.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.0.6.RELEASE:compile
[INFO] |  |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  |  +- org.springframework:spring-beans:jar:4.0.6.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-context:jar:4.0.6.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.0.6.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:4.0.6.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-test:jar:1.1.5.RELEASE:test
[INFO] |  +- org.mockito:mockito-core:jar:1.9.5:test
[INFO] |  |  \- org.objenesis:objenesis:jar:1.0:test
[INFO] |  +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] |  +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] |  \- org.springframework:spring-test:jar:4.0.6.RELEASE:test
[INFO] \- org.projectlombok:lombok:jar:0.12.0:provided
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.994 s
[INFO] Finished at: 2015-01-21T10:20:10+09:00
[INFO] Final Memory: 11M/27M
[INFO] ------------------------------------------------------------------------

以上で準備完了。

サービスとコントローラを作る

サービスとコントローラを作る。
サービスでビジネスロジックを記述し、コントローラでビジネスロジックの呼び出しをする。

サービス用のパッケージを「service」として、そこにサービスを作る。
まずはSpringとは関係ない普通のクラスを作成する。

package tools.springsample.springsample01.service;

public class SampleService {
    public String getMessage() {
        return "Hello world.";
    }
}

これをSpringのサービスクラスにするにはクラス宣言に「@Component」を付ける。

package tools.springsample.springsample01.service;

import org.springframework.stereotype.Component;

@Component  // a
public class SampleService {
    public String getMessage() {
        return "Hello world.";
    }
}

a -> 「@Component」を付けることにより、インスタンスDIコンテナによって管理されることになる。


コントローラを作る。
コントローラは自動生成されたAppクラスを流用する。

package tools.springsample.springsample01;

import tools.springsample.springsample01.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  // d
@EnableAutoConfiguration  // a
@ComponentScan  // b
public class App 
{
    @Autowired  // c
    private SampleService sampleService;

    @RequestMapping("/")  // e
    @ResponseBody  // f
    public String hello() {
        return sampleService.getMessage();
    }

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

DI関係の宣言は下記のとおり。
a -> Springの設定を自動でやってくれるオマジナイ。
b -> @Autowiredで指定したコンポーネントをスキャンする場所(パッケージ)を指定。(自クラス配下なのでパラメータは不要)
c -> DIコンテナからインスタンスを取得する指定。

Web関係の宣言は下記のとおり。
d -> 「@Controller」を付けることにより、コントローラクラスになり、リクエストを受け付けられるようになる。
e -> URLとメソッドマッピング
f -> 戻り値をレスポンスとして返すという意味。
g -> Springの起動。Tomcatの起動とデプロイが自動で行われる。

コンパイルする。

mvn compile

起動する。

mvn spring-boot:run

スタックトレースが出なければ起動に成功していると思われるので、ブラウザでアクセスする。
http://localhost:8080/

Hello world.」が出れば成功。
コントローラからサービスを呼んで、サービスの結果を出力出来た。