Spring-boot-quick-guide

提供:Dev Guides
移動先:案内検索

スプリングブート-はじめに

Spring Bootは、マイクロサービスの作成に使用されるオープンソースのJavaベースのフレームワークです。 Pivotal Teamによって開発され、スタンドアロンおよび生産準備が整ったスプリングアプリケーションの構築に使用されます。 この章では、Spring Bootの概要を説明し、その基本概念を理解します。

マイクロサービスとは何ですか?

マイクロサービスは、開発者がサービスを独自に開発および展開できるようにするアーキテクチャです。 実行中の各サービスには独自のプロセスがあり、これによりビジネスアプリケーションをサポートする軽量モデルが実現されます。

利点

マイクロサービスは、その開発者に次の利点を提供します-

  • 簡単な配置
  • シンプルなスケーラビリティ
  • コンテナとの互換性
  • 最小構成
  • 生産時間の短縮

Spring Bootとは何ですか?

Spring Bootは、Java開発者が*実行*できるスタンドアロンおよびプロダクショングレードのSpringアプリケーションを開発するための優れたプラットフォームを提供します。 Spring構成全体をセットアップする必要なく、最小限の構成で開始できます。

利点

Spring Bootは、その開発者に次の利点を提供します-

  • スプリングアプリケーションの理解と開発が簡単
  • 生産性を向上
  • 開発時間を短縮

目標

春のブートは、次の目標で設計されています-

  • Springでの複雑なXML構成を回避するには
  • 生産準備が整ったSpringアプリケーションをより簡単な方法で開発するには
  • 開発時間を短縮し、アプリケーションを独立して実行するには
  • アプリケーションを使い始める簡単な方法を提供する

なぜSpring Bootなのか?

ここで与えられる機能と利点のために、Spring Bootを選択できます-

  • Java Beans、XML構成、およびデータベーストランザクションを構成するための柔軟な方法を提供します。
  • 強力なバッチ処理を提供し、RESTエンドポイントを管理します。
  • Spring Bootでは、すべてが自動構成されます。手動で構成する必要はありません。
  • 注釈ベースのスプリングアプリケーションを提供します
  • 依存関係管理を容易にします
  • 組み込みサーブレットコンテナが含まれています

それはどのように機能しますか?

Spring Bootは、 @ EnableAutoConfiguration アノテーションを使用して、プロジェクトに追加した依存関係に基づいてアプリケーションを自動的に構成します。 たとえば、MySQLデータベースがクラスパスにあるが、データベース接続を設定していない場合、Spring Bootはインメモリデータベースを自動設定します。

スプリングブートアプリケーションのエントリポイントは、 @ SpringBootApplication アノテーションとmainメソッドを含むクラスです。

Spring Bootは、 @ ComponentScan アノテーションを使用して、プロジェクトに含まれるすべてのコンポーネントを自動的にスキャンします。

スプリングブートスターター

依存関係管理の処理は、大きなプロジェクトにとって難しいタスクです。 Spring Bootは、開発者の利便性のために一連の依存関係を提供することにより、この問題を解決します。

たとえば、データベースアクセスにSpringとJPAを使用する場合は、 spring-boot-starter-data-jpa 依存関係をプロジェクトに含めるだけで十分です。

すべてのSpring Bootスターターは同じ名前付けパターン spring-boot-starter- *に従うことに注意してください。*は、それがアプリケーションのタイプであることを示します。

理解を深めるために、以下で説明する次のSpring Bootスターターを見てください-

  • Spring Boot Starter Actuator依存性*は、アプリケーションの監視と管理に使用されます。 そのコードは以下に示されています-
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • Spring Boot Starter Securityの依存関係*は、Spring Securityに使用されます。 そのコードは以下に示されています-
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  • Spring Boot Starter Web依存*は、Rest Endpointsの記述に使用されます。 そのコードは以下に示されています-
<dependency&gt
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • Spring Boot Starter Thyme Leaf依存関係*は、Webアプリケーションの作成に使用されます。 そのコードは以下に示されています-
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • Spring Boot Starter Testの依存関係*は、テストケースの記述に使用されます。 そのコードは以下に示されています-
<dependency&gt
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
</dependency>

自動設定

Spring Boot Auto Configurationは、プロジェクトに追加したJAR依存関係に基づいて、Springアプリケーションを自動的に構成します。 たとえば、MySQLデータベースがクラスパスにあるが、データベース接続を設定していない場合、Spring Bootはインメモリデータベースを自動設定します。

この目的のために、メインクラスファイルに @ EnableAutoConfiguration アノテーションまたは @ SpringBootApplication アノテーションを追加する必要があります。 その後、Spring Bootアプリケーションが自動的に構成されます。

より良い理解のために次のコードを観察します-

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

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

スプリングブートアプリケーション

Spring Bootアプリケーションのエントリポイントは、 @ SpringBootApplication アノテーションを含むクラスです。 このクラスには、Spring Bootアプリケーションを実行するためのmainメソッドが必要です。 @ SpringBootApplication 注釈には、自動構成、コンポーネントスキャン、およびスプリングブート構成が含まれます。

*@ SpringBootApplication* 注釈をクラスに追加した場合、 *@ EnableAutoConfiguration、@ ComponentScan* 、および *@ SpringBootConfiguration* 注釈を追加する必要はありません。 *@ SpringBootApplication* 注釈には、他のすべての注釈が含まれます。

より良い理解のために次のコードを観察します-

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

コンポーネントスキャン

Spring Bootアプリケーションは、アプリケーションの初期化時にすべてのBeanとパッケージ宣言をスキャンします。 プロジェクトに追加されたコンポーネントをスキャンするには、クラスファイルに @ ComponentScan 注釈を追加する必要があります。

より良い理解のために次のコードを観察します-

import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

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

スプリングブート-クイックスタート

This chapter will teach you how to create a Spring Boot application using Maven and Gradle.

前提条件

システムは、Spring Bootアプリケーションを作成するために次の最小要件を満たしている必要があります-

  • Java 7
  • Maven 3.2
  • Gradle 2.5

Spring Boot CLI

Spring Boot CLIはコマンドラインツールであり、Groovyスクリプトを実行できます。 これは、Spring Bootコマンドラインインターフェイスを使用して、Spring Bootアプリケーションを作成する最も簡単な方法です。 コマンドプロンプト自体でアプリケーションを作成、実行、およびテストできます。

このセクションでは、Spring Boot CLIの手動インストールに含まれる手順について説明します。 さらにヘルプが必要な場合は、次のリンクを使用できます。https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-spring-boot[[[1]]]

次のURLのSpring SoftwareリポジトリからSpring CLIディストリビューションをダウンロードすることもできます。https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation

手動インストールの場合、次の2つのフォルダを使用する必要があります-

  • spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip
  • spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz

ダウンロード後、アーカイブファイルを解凍し、install.txtファイルに記載されている手順に従います。 環境をセットアップする必要がないというわけではありません。

Windowsでは、コマンドプロンプトでSpring Boot CLI bin ディレクトリに移動し、コマンド spring –-version を実行して、spring CLIが正しくインストールされていることを確認します。 コマンドを実行した後、以下に示すように、春のCLIバージョンを見ることができます-

Spring CLIバージョン

GroovyでHello Worldを実行する

Rest Endpointスクリプトを含む単純なgroovyファイルを作成し、スプリングブートCLIでgroovyファイルを実行します。 この目的のためにここに示されているコードを観察します-

@Controller
class Example {
   @RequestMapping("/")
   @ResponseBody
   public String hello() {
      "Hello Spring Boot"
   }
}

次に、 hello.groovy という名前でgroovyファイルを保存します。 この例では、groovyファイルをSpring Boot CLI bin ディレクトリ内に保存したことに注意してください。 次に、以下のスクリーンショットに示すように、コマンド spring run hello.groovy を使用してアプリケーションを実行します-

GroovyでHello Worldを実行

groovyファイルを実行すると、必要な依存関係が自動的にダウンロードされ、以下のスクリーンショットに示すようにTomcat 8080ポートでアプリケーションが開始されます-

GroovyファイルTomcatポートの実行

Tomcatが起動したら、Webブラウザーに移動し、URL http://localhost:8080/ にアクセスすると、次のように出力を確認できます。

Hello Spring Boot

スプリングブート-ブートストラップ

この章では、Spring Bootアプリケーションでブートストラップを実行する方法について説明します。

春の初期化子

Spring Bootアプリケーションをブートストラップする方法の1つは、Spring Initializerを使用することです。 これを行うには、Spring Initializer Webページhttps://start.spring.io/[www.start.spring.io]にアクセスして、ビルド、Springブートバージョン、およびプラットフォームを選択する必要があります。 また、アプリケーションを実行するには、グループ、アーティファクト、および必要な依存関係を提供する必要があります。

RESTエンドポイントを作成するために spring-boot-starter-web 依存関係を追加した例を示す次のスクリーンショットを確認してください。

Spring Initializer

グループ、アーティファクト、依存関係、ビルドプロジェクト、プラットフォーム、およびバージョンを指定したら、[プロジェクトの生成]ボタンをクリックします。 zipファイルがダウンロードされ、ファイルが抽出されます。

このセクションでは、MavenとGradleの両方を使用して例を説明します。

メーベン

プロジェクトをダウンロードしたら、ファイルを解凍します。 これで、 pom.xml ファイルは次のようになります-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle

プロジェクトをダウンロードしたら、ファイルを解凍します。 これで、 build.gradle ファイルは次のようになります-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

クラスパスの依存関係

Spring Bootは、クラスパスにjarを追加するための多くの Starters を提供します。 たとえば、Rest Endpointを作成するには、クラスパスに spring-boot-starter-web 依存関係を追加する必要があります。 より良い理解のために以下に示すコードを観察します-

Mavenの依存関係

<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies>

Gradle依存関係

dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
}

主な方法

メインメソッドは、Spring Boot Applicationクラスを記述する必要があります。 このクラスには、 @ SpringBootApplication の注釈を付ける必要があります。 これは、起動するスプリングブートアプリケーションのエントリポイントです。 メインクラスファイルは、デフォルトパッケージの src/java/main ディレクトリにあります。

この例では、メインクラスファイルは src/java/main ディレクトリにあり、デフォルトパッケージは com.finddevguides.demo です。 より良い理解のためにここに示されているコードを観察します-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

残りのエンドポイントを書く

Spring Boot Applicationメインクラスファイル自体に単純なHello World Restエンドポイントを書くには、以下に示す手順に従ってください-

  • まず、クラスの上部に @ RestController 注釈を追加します。
  • 次に、 @ RequestMapping アノテーションを使用してリクエストURIメソッドを記述します。
  • 次に、Request URIメソッドは Hello World 文字列を返す必要があります。

さて、あなたのメインのSpring Boot Applicationクラスファイルは、以下のコードに示すようになります-

package com.finddevguides.demo;

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

@SpringBootApplication
@RestController

public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String hello() {
      return "Hello World";
   }
}

実行可能JARを作成する

以下に示すように、コマンドプロンプトでMavenおよびGradleコマンドを使用して、Spring Bootアプリケーションを実行する実行可能JARファイルを作成します

以下に示すように、Mavenコマンドmvn clean installを使用します-

コマンドMVNクリーンインストール

コマンドを実行した後、以下に示すように、コマンドプロンプトで BUILD SUCCESS メッセージを見ることができます-

ビルド成功メッセージ

以下に示すように、Gradleコマンド gradle clean build を使用します-

Gradle Clean Build

コマンドを実行した後、以下に示すように、コマンドプロンプトで BUILD SUCCESSFUL メッセージを見ることができます-

コマンドプロンプトのBUILD SUCCESSFULメッセージ

JavaでHello Worldを実行する

実行可能なJARファイルを作成すると、次のディレクトリにあります。

Mavenの場合、以下に示すように、ターゲットディレクトリの下にJARファイルを見つけることができます-

Maven JARファイルターゲットディレクトリ

Gradleの場合、以下に示すように build/libs ディレクトリの下にJARファイルを見つけることができます-

ビルドLibsディレクトリの下のJARファイル

ここで、コマンド java –jar <JARFILE> を使用してJARファイルを実行します。 上記の例では、JARファイルの名前は demo-0.0.1-SNAPSHOT.jar であることに注意してください。

JAR File Named Demo SNAPSHOT

jarファイルを実行すると、以下に示すようにコンソールウィンドウに出力を見ることができます-

コンソールウィンドウでの出力

次に、コンソールを見てください。Tomcatはポート8080(http)で起動しました。 今、Webブラウザに移動し、URL http://localhost:8080/ をヒットすると、以下に示すように出力を見ることができます-

Tomcatはポート8080(http)で開始されました。

Spring Boot-Tomcatの展開

Spring Bootアプリケーションを使用することにより、warファイルを作成してWebサーバーにデプロイできます。 この章では、WARファイルを作成し、Tomcat WebサーバーにSpring Bootアプリケーションをデプロイする方法を学習します。

Spring Boot Servlet Initializer

従来の展開方法では、Spring Boot Application @ SpringBootApplication クラスで SpringBootServletInitializer クラスを拡張します。 Spring Boot Servlet Initializerクラスファイルを使用すると、サーブレットコンテナを使用して起動時にアプリケーションを構成できます。

JARファイルの展開のためのSpring Boot Applicationクラスファイルのコードは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

クラス SpringBootServletInitializer を拡張して、WARファイルの展開をサポートする必要があります。 Spring Boot Applicationクラスファイルのコードは次のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class DemoApplication  extends SpringBootServletInitializer {
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(DemoApplication.class);
   }
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

メインクラスの設定

Spring Bootでは、ビルドファイルで開始するメインクラスを指定する必要があります。 この目的のために、次のコードを使用できます-

Mavenの場合、以下に示すように pom.xml プロパティに開始クラスを追加します-

<start-class>com.finddevguides.demo.DemoApplication</start-class>

Gradleの場合、以下に示すようにbuild.gradleにメインクラス名を追加します-

mainClassName="com.finddevguides.demo.DemoApplication"

パッケージングJARをWARに更新する

次のコードを使用して、パッケージングJARをWARに更新する必要があります-

Mavenの場合、以下に示すように pom.xml にWARとしてパッケージを追加します-

<packaging>war</packaging>

Gradleの場合、以下に示すように build.gradle にアプリケーションプラグインとwarプラグインを追加します-

apply plugin: ‘war’
apply plugin: ‘application’

次に、文字列「Hello World from Tomcat」を返す単純なRest Endpointを作成しましょう。 Restエンドポイントを作成するには、ビルドファイルにSpring Boot Webスターターの依存関係を追加する必要があります。

Mavenの場合、以下に示すコードを使用してpom.xmlにSpring Bootスターター依存関係を追加します-

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Gradleの場合、以下に示すコードを使用して build.gradle にSpring Bootスターターの依存関係を追加します-

dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
}

次に、以下に示すコードを使用して、Spring Boot Applicationクラスファイルに単純なRESTエンドポイントを記述します-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication  extends SpringBootServletInitializer {
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(DemoApplication.class);
   }
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @RequestMapping(value = "/")
   public String hello() {
      return "Hello World from Tomcat";
   }
}

アプリケーションのパッケージ化

次に、以下に示すようにアプリケーションをパッケージ化するためのMavenおよびGradleコマンドを使用して、TomcatサーバーにデプロイするWARファイルを作成します-

Mavenの場合、 mvn package コマンドを使用して、アプリケーションをパッケージ化します。 次に、WARファイルが作成され、以下のスクリーンショットに示すように、ターゲットディレクトリで見つけることができます-

Maven MVNパッケージ

Mavenパッケージングアプリケーションターゲットディレクトリ

Gradleの場合、アプリケーションをパッケージ化するには、コマンド gradle clean build を使用します。 次に、WARファイルが作成され、 build/libs ディレクトリの下で見つけることができます。 より良い理解のためにここで与えられたスクリーンショットを観察します-

Gradle Clean Buildコマンド

Mavenパッケージングアプリケーションターゲットディレクトリ

Tomcatにデプロイする

次に、Tomcatサーバーを実行し、 webapps ディレクトリの下にWARファイルをデプロイします。 より良い理解のためにここに示されているスクリーンショットを観察します-

Tomcat Web Application Maneger

webAppsディレクトリ

展開が正常に完了したら、WebブラウザでURL http://localhost:8080/demo-0.0.1-SNAPSHOT/*にアクセスし、以下のスクリーンショットに示すように出力が表示されることを確認します-

Successful Deployment Screenshot

この目的の完全なコードを以下に示します。

*pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>war</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <start-class>com.finddevguides.demo.DemoApplication</start-class>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
apply plugin: 'application'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
mainClassName = "com.finddevguides.demo.DemoApplication"

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication  extends SpringBootServletInitializer {
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(DemoApplication.class);
   }
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @RequestMapping(value = "/")
   public String hello() {
      return "Hello World from Tomcat";
   }
}

Spring Boot-ビルドシステム

Spring Bootでは、ビルドシステムの選択は重要なタスクです。 MavenまたはGradleは、依存関係管理を適切にサポートするため、お勧めします。 Springは他のビルドシステムをうまくサポートしていません。

依存関係管理

Spring Bootチームは、リリースごとにSpring Bootバージョンをサポートする依存関係のリストを提供します。 ビルド構成ファイルで依存関係のバージョンを提供する必要はありません。 Spring Bootは、リリースに基づいて依存関係バージョンを自動的に構成します。 Spring Bootバージョンをアップグレードすると、依存関係も自動的にアップグレードされることに注意してください。

注意-依存関係のバージョンを指定する場合は、構成ファイルで指定できます。 ただし、Spring Bootチームは、依存関係のバージョンを指定する必要がないことを強くお勧めします。

メーベン依存

Maven構成の場合、Spring Boot Starterの親プロジェクトを継承して、Spring Boot Startersの依存関係を管理する必要があります。 このため、以下に示すように、 pom.xml ファイルでスターター親を単純に継承できます。

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.5.8.RELEASE</version>
</parent>

Spring Boot Parent Starter依存関係のバージョン番号を指定する必要があります。 その後、他のスターター依存関係については、Spring Bootバージョン番号を指定する必要はありません。 以下のコードを確認してください-

<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies>

Gradle依存関係

Spring Boot Startersの依存関係を build.gradle ファイルに直接インポートできます。 Maven for GradleのようなSpring Boot Start Parentの依存関係は必要ありません。 以下のコードを確認してください-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

同様に、Gradleでは、依存関係のSpring Bootバージョン番号を指定する必要はありません。 Spring Bootは、バージョンに基づいて依存関係を自動的に構成します。

dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
}

Spring Boot-コード構造

Spring Bootには、使用するコードレイアウトがありません。 ただし、いくつかのベストプラクティスが役立ちます。 この章では、それらについて詳しく説明します。

デフォルトのパッケージ

パッケージ宣言を持たないクラスは、*デフォルトパッケージ*と見なされます。 通常、デフォルトのパッケージ宣言は推奨されないことに注意してください。 既定のパッケージを使用すると、Spring Bootは自動構成やコンポーネントスキャンの誤動作などの問題を引き起こします。

-Javaが推奨するパッケージ宣言の命名規則は、逆ドメイン名です。 例- com.finddevguides.myproject

典型的なレイアウト

Spring Bootアプリケーションの典型的なレイアウトは、以下の画像に示されています-

Spring Bootアプリケーションの典型的なレイアウト

Application.javaファイルは、@ SpringBootApplicationとともにmainメソッドを宣言する必要があります。 理解を深めるために、以下のコードを観察してください-

package com.finddevguides.myproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Beanと依存関係の注入

Spring Bootでは、Spring Frameworkを使用して、Beanとその依存性注入を定義できます。 @ ComponentScan アノテーションは、Beanと @ Autowired アノテーションが挿入された対応するものを見つけるために使用されます。

Spring Bootの一般的なレイアウトに従った場合、 @ ComponentScan アノテーションに引数を指定する必要はありません。 すべてのコンポーネントクラスファイルは、Spring Beanに自動的に登録されます。

次の例は、Rest Templateオブジェクトの自動配線と、同じBeanの作成に関するアイデアを提供します-

@Bean
public RestTemplate getRestTemplate() {
   return new RestTemplate();
}

次のコードは、メインのSpring Boot Applicationクラスファイル内の自動配線されたRest TemplateオブジェクトとBean作成オブジェクトのコードを示しています-

package com.finddevguides.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class DemoApplication {
@Autowired
   RestTemplate restTemplate;

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public RestTemplate getRestTemplate() {
      return new RestTemplate();
   }
}

春のブーツ-ランナー

Application Runner and Command Line Runner interfaces lets you to execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions immediately after the application has started. This chapter talks about them in detail.

アプリケーションランナー

Application Runnerは、Spring Bootアプリケーションの起動後にコードを実行するために使用されるインターフェイスです。 以下の例は、メインクラスファイルにApplication Runnerインターフェースを実装する方法を示しています。

package com.finddevguides.demo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Override
   public void run(ApplicationArguments arg0) throws Exception {
      System.out.println("Hello World from Application Runner");
   }
}

ここで、* Application Runnerの Hello World の下のコンソールウィンドウを観察すると、Tomcatの起動後にprintlnステートメントが実行されます。 次のスクリーンショットは関連していますか?

Hello World From Application Runner

コマンドラインランナー

コマンドラインランナーはインターフェースです。 Spring Bootアプリケーションの起動後にコードを実行するために使用されます。 以下の例は、メインクラスファイルにコマンドラインランナーインターフェイスを実装する方法を示しています。

package com.finddevguides.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Override
   public void run(String... arg0) throws Exception {
      System.out.println("Hello world from Command Line Runner");
   }
}

Tomcatの起動後にprintlnステートメントが実行される「コマンドラインランナーのHello world」の下のコンソールウィンドウを見てください。

コマンドラインランナー

Spring Boot-アプリケーションのプロパティ

アプリケーションプロパティは、さまざまな環境での作業をサポートします。 この章では、Spring Bootアプリケーションのプロパティを設定および指定する方法を学習します。

コマンドラインのプロパティ

Spring Bootアプリケーションは、コマンドラインプロパティをSpring Boot Environmentプロパティに変換します。 コマンドラインプロパティは、他のプロパティソースよりも優先されます。 デフォルトでは、Spring Bootは8080ポート番号を使用してTomcatを起動します。 コマンドラインプロパティを使用してポート番号を変更する方法を学びましょう。

ステップ1 *-実行可能なJARファイルを作成した後、コマンド *java –jar <JARFILE> を使用して実行します。

  • ステップ2 *-コマンドラインプロパティを使用して、Spring Bootアプリケーションのポート番号を変更するには、以下のスクリーンショットに示されているコマンドを使用します。

コマンドラインプロパティJARFILE

-区切り文字-を使用して、複数のアプリケーションプロパティを指定できます。

プロパティファイル

プロパティファイルは、1つのファイルに「N」個のプロパティを保持して、異なる環境でアプリケーションを実行するために使用されます。 Spring Bootでは、プロパティはクラスパスの下の application.properties ファイルに保持されます。

application.propertiesファイルは、 src/main/resources ディレクトリにあります。 サンプル application.properties ファイルのコードは以下のとおりです-

server.port = 9090
spring.application.name = demoservice

上記のコードでは、Spring Bootアプリケーションのデモサービスがポート9090で開始されることに注意してください。

YAMLファイル

Spring Bootは、アプリケーションを実行するためのYAMLベースのプロパティ設定をサポートしています。 application.properties の代わりに、 application.yml ファイルを使用できます。 このYAMLファイルもクラスパス内に保持する必要があります。 サンプル application.yml ファイルは以下のとおりです-

spring:
   application:
      name: demoservice
   server:
port: 9090

外部化されたプロパティ

プロパティファイルをクラスパスの下に保持する代わりに、プロパティを別の場所またはパスに保持できます。 JARファイルの実行中に、プロパティファイルのパスを指定できます。 次のコマンドを使用して、JARの実行中にプロパティファイルの場所を指定できます-

-Dspring.config.location = C:\application.properties

外部化されたプロパティ

@Valueアノテーションの使用

@Valueアノテーションは、Javaコードで環境またはアプリケーションのプロパティ値を読み取るために使用されます。 プロパティ値を読み取るための構文は以下に示されています-

@Value("${property_key_name}")

@Valueアノテーションを使用してJava変数の spring.application.name プロパティ値を読み取る構文を示す次の例を見てください。

@Value("${spring.application.name}")

理解を深めるために、以下のコードを観察してください-

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {
   @Value("${spring.application.name}")
   private String name;
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String name() {
      return name;
   }
}

注意-アプリケーションの実行中にプロパティが見つからない場合、Spring BootはIllegal Argument例外をスローします*値 "$ \ {spring.application.name}" *のプレースホルダー 'spring.application.name’を解決できませんでした。

プレースホルダーの問題を解決するには、以下に示すthr構文を使用してプロパティのデフォルト値を設定できます-

@Value("${property_key_name:default_value}")

@Value("${spring.application.name:demoservice}")

スプリングブートアクティブプロファイル

Spring Bootは、Springアクティブプロファイルに基づいてさまざまなプロパティをサポートしています。 たとえば、Spring Bootアプリケーションを実行するために、開発用と本番用の2つのファイルを別々に保持できます。

application.propertiesのSpringアクティブプロファイル

application.propertiesでSpringアクティブプロファイルを持つ方法を理解しましょう。 デフォルトでは、アプリケーション。 プロパティは、Spring Bootアプリケーションの実行に使用されます。 プロファイルベースのプロパティを使用する場合は、以下に示すように、プロファイルごとに個別のプロパティファイルを保持できます-

*application.properties*
server.port = 8080
spring.application.name = demoservice
*application-dev.properties*
server.port = 9090
spring.application.name = demoservice
*application-prod.properties*
server.port = 4431
spring.application.name = demoservice

JARファイルの実行中に、各プロパティファイルに基づいてスプリングアクティブプロファイルを指定する必要があります。 デフォルトでは、Spring Bootアプリケーションはapplication.propertiesファイルを使用します。 スプリングアクティブプロファイルを設定するコマンドは以下に示されています-

Prod.Properties Active Dev

以下に示すように、コンソールログでアクティブなプロファイル名を確認できます-

2017-11-26 08:13:16.322  INFO 14028 --- [
   main] com.finddevguides.demo.DemoApplication  :
   The following profiles are active: dev

これで、Tomcatは以下に示すようにポート9090(http)で開始されました-

2017-11-26 08:13:20.185  INFO 14028 --- [
   main] s.b.c.e.t.TomcatEmbeddedServletContainer :
   Tomcat started on port(s): 9090 (http)

以下に示すように、プロダクションアクティブプロファイルを設定できます-

Production Active Profile

以下に示すように、コンソールログでアクティブなプロファイル名を確認できます-

2017-11-26 08:13:16.322  INFO 14028 --- [
   main] com.finddevguides.demo.DemoApplication  :
   The following profiles are active: prod

次に、Tomcatは以下に示すようにポート4431(http)で開始しました-

2017-11-26 08:13:20.185  INFO 14028 --- [
   main] s.b.c.e.t.TomcatEmbeddedServletContainer :
   Tomcat started on port(s): 4431 (http)

application.ymlのSpringアクティブプロファイル

application.ymlのSpringアクティブプロファイルを保持する方法を理解しましょう。 Springのアクティブなプロファイルプロパティを単一の application.yml ファイルに保持できます。 application.propertiesのような個別のファイルを使用する必要はありません。

以下は、application.ymlファイルでSpringのアクティブなプロファイルを保持するコードの例です。 application.ymlファイルの各プロファイルを区切るために区切り文字(---)が使用されていることに注意してください。

spring:
   application:
      name: demoservice
server:
   port: 8080

---
spring:
   profiles: dev
   application:
      name: demoservice
server:
   port: 9090

---
spring:
   profiles: prod
   application:
      name: demoservice
server:
   port: 4431

開発のアクティブなプロファイルを設定するコマンドを以下に示します-

Prod.Properties Active Dev

以下に示すように、コンソールログでアクティブなプロファイル名を確認できます-

2017-11-26 08:41:37.202  INFO 14104 --- [
   main] com.finddevguides.demo.DemoApplication  :
   The following profiles are active: dev

これで、Tomcatは以下に示すようにポート9090(http)で開始されました-

2017-11-26 08:41:46.650  INFO 14104 --- [
   main] s.b.c.e.t.TomcatEmbeddedServletContainer :
   Tomcat started on port(s): 9090 (http)

実稼働アクティブプロファイルを設定するコマンドは以下のとおりです-

Production Active Profile

以下に示すように、コンソールログでアクティブなプロファイル名を確認できます-

2017-11-26 08:43:10.743  INFO 13400 --- [
   main] com.finddevguides.demo.DemoApplication  :
   The following profiles are active: prod

これにより、以下に示すようにポート4431(http)でTomcatが起動します。

2017-11-26 08:43:14.473  INFO 13400 --- [
   main] s.b.c.e.t.TomcatEmbeddedServletContainer :
   Tomcat started on port(s): 4431 (http)

Spring Boot-ロギング

Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s default configurations provides a support for the use of Java Util Logging, Log4j2, and Logback. Using these, we can configure the console logging as well as file logging.

Spring Boot Startersを使用している場合、Logbackはログの適切なサポートを提供します。 また、Logbackは、Common Logging、Util Logging、Log4J、およびSLF4Jの適切なサポートの使用も提供します。

ログ形式

デフォルトのSpring Boot Log形式は、以下のスクリーンショットに示されています。

Spring Boot Log Format

あなたに次の情報を提供します-

  • ログの日付と時刻を示す*日付*および*時刻*
  • *ログレベル*はINFO、ERRORまたはWARNを表示します
  • *プロセスID *
  • ---セパレーター
  • *スレッド名*は角括弧[]で囲まれています
  • Sourceクラス名を示す Logger Name
  • ログメッセージ

コンソールログ出力

デフォルトのログメッセージはコンソールウィンドウに出力されます。 デフォルトでは、「INFO」、「ERROR」、および「WARN」のログメッセージがログファイルに出力されます。

デバッグレベルログを有効にする必要がある場合は、以下に示すコマンドを使用して、アプリケーションの起動時にデバッグフラグを追加します-

java –jar demo.jar --debug

ここに示すように、application.propertiesファイルにデバッグモードを追加することもできます-

debug = true

ファイルログ出力

デフォルトでは、すべてのログはファイルではなくコンソールウィンドウに出力されます。 ファイル内のログを印刷する場合は、application.propertiesファイルでプロパティ logging.file または logging.path を設定する必要があります。

以下に示すプロパティを使用して、ログファイルのパスを指定できます。 ログファイル名はspring.logであることに注意してください。

logging.path =/var/tmp/

以下に示すプロパティを使用して、独自のログファイル名を指定できます-

logging.file =/var/tmp/mylog.log

-サイズが10 MBに達すると、ファイルは自動的に回転します。

ログレベル

Spring Bootは、「TRACE」、「DEBUG」、「INFO」、「WARN」、「ERROR」、「FATAL」、「OFF」などのすべてのロガーレベルをサポートしています。 以下に示すように、application.propertiesファイルでルートロガーを定義できます-

logging.level.root = WARN

注意-ログバックは「致命的な」レベルのログをサポートしていません。 「エラー」レベルのログにマッピングされます。

ログバックを構成する

Logbackは、Spring Boot Log構成を処理するXMLベースの構成をサポートしています。 ロギング構成の詳細は、 logback.xml ファイルで構成されます。 logback.xmlファイルは、クラスパスの下に配置する必要があります。

以下に示すコードを使用して、Logback.xmlファイルでROOTレベルのログを構成できます-

<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
   <root level = "INFO">
   </root>
</configuration>

以下に示すLogback.xmlファイルでコンソールアペンダーを構成できます。

<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
   <appender name = "STDOUT" class = "ch.qos.logback.core.ConsoleAppender"></appender>
   <root level = "INFO">
      <appender-ref ref = "STDOUT"/>
   </root>
</configuration>

以下に示すコードを使用して、Logback.xmlファイルでファイルアペンダーを構成できます。 ファイルアペンダー内のログファイルパスを指定する必要があることに注意してください。

<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
   <appender name = "FILE" class = "ch.qos.logback.core.FileAppender">
      <File>/var/tmp/mylog.log</File>
   </appender>
   <root level = "INFO">
      <appender-ref ref = "FILE"/>
   </root>
</configuration>

以下に示すコードを使用して、 logback.xml ファイルでログパターンを定義できます。 また、以下に示すコードを使用して、コンソールまたはファイルログアペンダー内でサポートされるログパターンのセットを定義することもできます-

<pattern>[%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n</pattern>

完全なlogback.xmlファイルのコードを以下に示します。 これをクラスパスに配置する必要があります。

<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
   <appender name = "STDOUT" class = "ch.qos.logback.core.ConsoleAppender">
      <encoder>
         <pattern>[%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n</pattern>
      </encoder>
   </appender>

   <appender name = "FILE" class = "ch.qos.logback.core.FileAppender">
      <File>/var/tmp/mylog.log</File>
      <encoder>
         <pattern>[%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p] %m%n</pattern>
      </encoder>
   </appender>

   <root level = "INFO">
      <appender-ref ref = "FILE"/>
      <appender-ref ref = "STDOUT"/>
   </root>
</configuration>

以下のコードは、Spring Bootメインクラスファイルにslf4jロガーを追加する方法を示しています。

package com.finddevguides.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);

   public static void main(String[] args) {
      logger.info("this is a info message");
      logger.warn("this is a warn message");
      logger.error("this is a error message");
      SpringApplication.run(DemoApplication.class, args);
   }
}

あなたがコンソールウィンドウで見ることができる出力はここに示されています-

Logger Console Window

あなたがログファイルで見ることができる出力はここに示されています-

ログ出力

Spring Boot-RESTful Webサービスの構築

Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot.

-RESTful Webサービスを構築するには、Spring Boot Starter Web依存関係をビルド構成ファイルに追加する必要があります。

Mavenユーザーの場合、次のコードを使用して、 pom.xml ファイルに以下の依存関係を追加します-

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Gradleユーザーの場合、次のコードを使用して、 build.gradle ファイルに以下の依存関係を追加します。

compile('org.springframework.boot:spring-boot-starter-web')

完全なビルド構成ファイル Mavenビルドのコード– pom.xml は以下のとおりです-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

完全なビルド構成ファイル Gradle Build – build.gradle のコードを以下に示します-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

RESTful Webサービスの構築に進む前に、次の注釈の知識があることが推奨されます-

レストコントローラー

@RestControllerアノテーションは、RESTful Webサービスを定義するために使用されます。 JSON、XML、カスタムレスポンスを提供します。 その構文は以下に示されています-

@RestController
public class ProductServiceController {
}

リクエストマッピング

@RequestMappingアノテーションは、RESTエンドポイントにアクセスするためのリクエストURIを定義するために使用されます。 Requestメソッドを定義して、オブジェクトを消費および生成できます。 デフォルトの要求方法はGETです。

@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }

リクエスト本文

@RequestBody注釈は、リクエスト本文のコンテンツタイプを定義するために使用されます。

public ResponseEntity<Object> createProduct(@RequestBody Product product) {
}

パス変数

@PathVariableアノテーションは、カスタムまたは動的なリクエストURIを定義するために使用されます。 要求URIのPath変数は、以下に示すように中括弧\ {}として定義されます-

public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {
}

リクエストパラメータ

@RequestParamアノテーションは、リクエストURLからリクエストパラメータを読み取るために使用されます。 デフォルトでは、これは必須パラメーターです。 ここに示すように、リクエストパラメータのデフォルト値を設定することもできます-

public ResponseEntity<Object> getProduct(
   @RequestParam(value = "name", required = false, defaultValue = "honey") String name) {
}

GET API

デフォルトのHTTP要求メソッドはGETです。 このメソッドには、リクエストボディは必要ありません。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。

HTTP GETリクエストメソッドを定義するサンプルコードを以下に示します。 この例では、HashMapを使用して製品を保存しました。 格納する製品としてPOJOクラスを使用したことに注意してください。

ここでは、リクエストURIは /products であり、HashMapリポジトリから製品のリストを返します。 GETメソッドRESTエンドポイントを含むコントローラークラスファイルを以下に示します。

package com.finddevguides.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.finddevguides.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);

      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);
   }
   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
   }
}

POST API

HTTP POSTリクエストは、リソースを作成するために使用されます。 このメソッドにはリクエストボディが含まれます。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。

次の例は、HTTP POST要求メソッドを定義するサンプルコードを示しています。 この例では、HashMapを使用して製品を保存しました。製品はPOJOクラスです。

ここでは、リクエストURIは /products であり、製品をHashMapリポジトリに保存した後にStringを返します。

package com.finddevguides.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.finddevguides.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();

   @RequestMapping(value = "/products", method = RequestMethod.POST)
   public ResponseEntity<Object> createProduct(@RequestBody Product product) {
      productRepo.put(product.getId(), product);
      return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
   }
}

PUT API

HTTP PUT要求は、既存のリソースを更新するために使用されます。 このメソッドにはリクエストボディが含まれます。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。

以下の例は、HTTP PUT要求メソッドを定義する方法を示しています。 この例では、HashMapを使用して既存の製品を更新しました。製品はPOJOクラスです。

ここで、リクエストURIは /products/\ {id} であり、製品の後にHashMapリポジトリに文字列を返します。 更新が必要な製品IDを定義するPath変数 \ {id} を使用したことに注意してください。

package com.finddevguides.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.finddevguides.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();

   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      productRepo.remove(id);
      product.setId(id);
      productRepo.put(id, product);
      return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
   }
}

DELETE API

HTTP削除リクエストは、既存のリソースを削除するために使用されます。 このメソッドには、リクエストボディは含まれていません。 リクエストパラメータとパス変数を送信して、カスタムURLまたは動的URLを定義できます。

以下の例は、HTTP DELETE要求メソッドを定義する方法を示しています。 この例では、HashMapを使用して、POJOクラスである既存の製品を削除しました。

リクエストURIは /products/\ {id} であり、HashMapリポジトリから製品を削除した後に文字列を返します。 削除する必要がある製品IDを定義するPath変数 \ {id} を使用しました。

package com.finddevguides.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.finddevguides.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();

   @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
   public ResponseEntity<Object> delete(@PathVariable("id") String id) {
      productRepo.remove(id);
      return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
   }
}

このセクションでは、ソースコードの完全なセットを提供します。 それぞれの機能について次のコードを確認してください-

*Spring Bootメインアプリケーションクラス– DemoApplication.java*
package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}
*POJOクラス– Product.java*
package com.finddevguides.demo.model;

public class Product {
   private String id;
   private String name;

   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
*Rest Controllerクラス– ProductServiceController.java*
package com.finddevguides.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.finddevguides.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);

      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);
   }

   @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
   public ResponseEntity<Object> delete(@PathVariable("id") String id) {
      productRepo.remove(id);
      return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
   }

   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      productRepo.remove(id);
      product.setId(id);
      productRepo.put(id, product);
      return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
   }

   @RequestMapping(value = "/products", method = RequestMethod.POST)
   public ResponseEntity<Object> createProduct(@RequestBody Product product) {
      productRepo.put(product.getId(), product);
      return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
   }

   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
   }
}

あなたは、実行可能なJARファイルを作成し、示されているように以下のMavenまたはGradleコマンドを使用してスプリングブートアプリケーションを実行することができます

Mavenの場合、以下に示すコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

以下に示すコマンドを使用して、JARファイルを実行できます-

java –jar <JARFILE>

これは、以下に示すようにTomcatポート8080でアプリケーションを開始します-

Tomcat Port8080で開始されたアプリケーション

次に、POSTMANアプリケーションで次のURLにアクセスして、出力を確認します。

GET API URLは: http://localhost:8080/products

POSTMAN Application Get API URL

POST API URL: http://localhost:8080/products

POSTMAN Application Post API URL

PUT API URL: http://localhost:8080/products/3

POSTMAN Application Put API URL

DELETE API URL: http://localhost:8080/products/3

POSTMANアプリケーション削除API URL

Spring Boot-例外処理

APIで例外とエラーを処理し、クライアントに適切な応答を送信することは、エンタープライズアプリケーションに適しています。 この章では、Spring Bootで例外を処理する方法を学びます。

例外処理に進む前に、次の注釈について理解しましょう。

コントローラーのアドバイス

@ControllerAdviceは、例外をグローバルに処理するための注釈です。

例外ハンドラー

@ExceptionHandlerは、特定の例外を処理し、カスタム応答をクライアントに送信するために使用される注釈です。

次のコードを使用して@ControllerAdviceクラスを作成し、例外をグローバルに処理できます-

package com.finddevguides.demo.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;

@ControllerAdvice
   public class ProductExceptionController {
}

RuntimeExceptionクラスを拡張するクラスを定義します。

package com.finddevguides.demo.exception;

public class ProductNotfoundException extends RuntimeException {
   private static final long serialVersionUID = 1L;
}

示されているように、@ ExceptionHandlerメソッドを定義して例外を処理できます。 このメソッドは、Controller Adviceクラスファイルの作成に使用する必要があります。

@ExceptionHandler(value = ProductNotfoundException.class)

public ResponseEntity<Object> exception(ProductNotfoundException exception) {
}

次に、以下のコードを使用して、APIから例外をスローします。

@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> updateProduct() {
   throw new ProductNotfoundException();
}

例外を処理する完全なコードを以下に示します。 この例では、PUT APIを使用して製品を更新しました。 ここで、製品の更新中に製品が見つからない場合は、「製品が見つかりません」という応答エラーメッセージを返します。 ProductNotFoundException 例外クラスは RuntimeException を拡張する必要があることに注意してください。

package com.finddevguides.demo.exception;
public class ProductNotfoundException extends RuntimeException {
   private static final long serialVersionUID = 1L;
}

例外をグローバルに処理するController Adviceクラスを以下に示します。 このクラスファイルで例外ハンドラメソッドを定義できます。

package com.finddevguides.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ProductExceptionController {
   @ExceptionHandler(value = ProductNotfoundException.class)
   public ResponseEntity<Object> exception(ProductNotfoundException exception) {
      return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
   }
}

製品を更新するためのProduct Service APIコントローラーファイルを以下に示します。 製品が見つからない場合、 ProductNotFoundException クラスがスローされます。

package com.finddevguides.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.finddevguides.demo.exception.ProductNotfoundException;
import com.finddevguides.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);

      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);
   }

   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      if(!productRepo.containsKey(id))throw new ProductNotfoundException();
      productRepo.remove(id);
      product.setId(id);
      productRepo.put(id, product);
      return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK);
   }
}

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

製品の* POJOクラス*のコードは以下のとおりです-

package com.finddevguides.demo.model;
public class Product {
   private String id;
   private String name;

   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
*Mavenビルドのコード– pom.xml* を以下に示します-
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle Build – build.gradle* のコードを以下に示します-
buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

あなたは、実行可能なJARファイルを作成し、MavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行することができます-

Mavenの場合、次のコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次のコマンドを使用してJARファイルを実行できます-

java –jar <JARFILE>

これは、以下に示すようにTomcatポート8080でアプリケーションを開始します-

開始したTomcatアプリケーションの例外処理

今、POSTMANアプリケーションで以下のURLをヒットし、以下に示すように出力を見ることができます-

更新URL:http://localhost:8080/products/3

Postmanアプリケーション更新URL

スプリングブート-インターセプター

あなたは、スプリングブートでインターセプターを使用して、次の状況下で操作を実行することができます-

  • リクエストをコントローラーに送信する前に
  • 応答をクライアントに送信する前に

例えば、インターセプターを使用して、コントローラーに要求を送信する前に要求ヘッダーを追加し、クライアントに応答を送信する前に応答ヘッダーを追加できます。

インターセプターを使用するには、それをサポートする @ Component クラスを作成する必要があり、 HandlerInterceptor インターフェースを実装する必要があります。

以下は、インターセプターでの作業中に知っておくべき3つの方法です-

  • * preHandle()*メソッド-要求をコントローラに送信する前に操作を実行するために使用されます。 このメソッドは、クライアントに応答を返すためにtrueを返す必要があります。
  • * postHandle()*メソッド-これは、クライアントに応答を送信する前に操作を実行するために使用されます。
  • * afterCompletion()*メソッド-これは、要求と応答の完了後に操作を実行するために使用されます。

より良い理解のために次のコードを観察します-

@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

      return true;
   }
   @Override
   public void postHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {}

   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception exception) throws Exception {}
}

以下に示すように、 WebMvcConfigurerAdapter を使用して InterceptorRegistry でこのインターセプターを登録する必要があります-

@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
   @Autowired
   ProductServiceInterceptor productServiceInterceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(productServiceInterceptor);
   }
}

以下に示す例では、GET products APIを使用して、以下に示す出力を提供します-

インターセプタークラスProductServiceInterceptor.javaのコードは以下のとおりです-

package com.finddevguides.demo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle
      (HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

      System.out.println("Pre Handle method is Calling");
      return true;
   }
   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler, ModelAndView modelAndView) throws Exception {

      System.out.println("Post Handle method is Calling");
   }
   @Override
   public void afterCompletion
      (HttpServletRequest request, HttpServletResponse response, Object
      handler, Exception exception) throws Exception {

      System.out.println("Request and Response is completed");
   }
}

インターセプターをインターセプターレジストリに登録するアプリケーション構成クラスファイルのコード– ProductServiceInterceptorAppConfig.javaを以下に示します-

package com.finddevguides.demo.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
   @Autowired
   ProductServiceInterceptor productServiceInterceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(productServiceInterceptor);
   }
}

ControllerクラスファイルProductServiceController.javaのコードは以下のとおりです-

package com.finddevguides.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.finddevguides.demo.exception.ProductNotfoundException;
import com.finddevguides.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);
      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);
   }
   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
   }
}

Product.javaのPOJOクラスのコードは次のとおりです-

package com.finddevguides.demo.model;

public class Product {
   private String id;
   private String name;

   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

メインのSpring Bootアプリケーションクラスファイル DemoApplication.java のコードは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Mavenビルドのコード- pom.xml を以下に示します-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "
   http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle Build build.gradle のコードは次のとおりです-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

以下のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、以下に示すようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すようにコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次のコマンドを使用してJARファイルを実行できます-

java –jar <JARFILE>

これで、アプリケーションは以下に示すようにTomcatポート8080で開始されました-

Tomcatポート8080で開始されたアプリケーション

ここで、POSTMANアプリケーションで以下のURLにアクセスすると、以下に示すような出力が表示されます-

GET API: http://localhost:8080/products

POSTMAN Application Get API URL

コンソールウィンドウで、以下のスクリーンショットに示すように、インターセプターに追加されたSystem.out.printlnステートメントを確認できます-

インターセプター出力コンソールウィンドウ

Spring Boot-サーブレットフィルター

フィルターは、アプリケーションのHTTP要求と応答をインターセプトするために使用されるオブジェクトです。 フィルターを使用することにより、2つのインスタンスで2つの操作を実行できます-

  • リクエストをコントローラーに送信する前に
  • クライアントに応答を送信する前。

次のコードは、@ Componentアノテーションを使用したServlet Filter実装クラスのサンプルコードを示しています。

@Component
public class SimpleFilter implements Filter {
   @Override
   public void destroy() {}

   @Override
   public void doFilter
      (ServletRequest request, ServletResponse response, FilterChain filterchain)
      throws IOException, ServletException {}

   @Override
   public void init(FilterConfig filterconfig) throws ServletException {}
}

次の例は、リクエストをコントローラに送信する前に、ServletRequestオブジェクトからリモートホストとリモートアドレスを読み取るためのコードを示しています。

doFilter()メソッドに、リモートホストとリモートアドレスを出力するSystem.out.printlnステートメントを追加しました。

package com.finddevguides.demo;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.stereotype.Component;

@Component
public class SimpleFilter implements Filter {
   @Override
   public void destroy() {}

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain)
      throws IOException, ServletException {

      System.out.println("Remote Host:"+request.getRemoteHost());
      System.out.println("Remote Address:"+request.getRemoteAddr());
      filterchain.doFilter(request, response);
   }

   @Override
   public void init(FilterConfig filterconfig) throws ServletException {}
}

Spring Bootのメインアプリケーションクラスファイルに、「Hello World」文字列を返す簡単なRESTエンドポイントを追加しました。

package com.finddevguides.demo;

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

@SpringBootApplication
@RestController
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String hello() {
      return "Hello World";
   }
}

Mavenビルドのコード- pom.xml を以下に示します-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "
   http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle Buildのコード– build.gradleを以下に示します-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

あなたは、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行することができます-

Mavenの場合、以下に示すようにコマンドを使用します-

mvn clean install

BUILD SUCCESSの後、JARファイルはターゲットディレクトリの下にあります。

Gradleの場合、以下に示すようにコマンドを使用します-

gradle clean build

BUILD SUCCESSFULの後、build/libsディレクトリの下にJARファイルがあります。

次に、次のコマンドを使用してJARファイルを実行します

java –jar <JARFILE>

Tomcatポート8080でアプリケーションが開始されたことがわかります。

URL http://localhost:8080/ にアクセスして、出力Hello Worldを確認します。 以下に示すようになります-

Tomcatはポート8080 HTTPで開始

次に、以下に示すように、コンソールログでリモートホストとリモートアドレスを見ることができます-

コンソールログのリモートホストリモートアドレス

Spring Boot-Tomcatポート番号

Spring Bootでは、異なるポート番号で同じアプリケーションを複数回実行できます。 この章では、これについて詳細に学習します。 デフォルトのポート番号8080に注意してください。

カスタムポート

*application.properties* ファイルでは、プロパティserver.portにカスタムポート番号を設定できます
server.port = 9090
*application.yml* ファイルでは、次のように見つけることができます-
server:
   port: 9090

ランダムポート

*application.properties* ファイルでは、プロパティserver.portにランダムなポート番号を設定できます
server.port = 0
*application.yml* ファイルでは、次のように見つけることができます-
server:
   port: 0

注意-Spring Bootアプリケーションの起動時に server.port 番号が0の場合、Tomcatはランダムなポート番号を使用します。

春のブーツ-残りのテンプレート

RESTテンプレートは、RESTful Webサービスを使用するアプリケーションを作成するために使用されます。 * exchange()*メソッドを使用して、すべてのHTTPメソッドのWebサービスを使用できます。 以下に示すコードは、RESTテンプレートのBeanを作成して、RESTテンプレートオブジェクトを自動配線する方法を示しています。

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public RestTemplate getRestTemplate() {
      return new RestTemplate();
   }
}

GET

  • RESTTemplate-exchange()メソッドを使用してGET APIを使用する *

このURL* http://localhost:8080/products *は次のJSONを返し、次のコードを使用してRESTテンプレートを使用してこのAPI応答を使用すると想定します-

[
   {
      "id": "1",
      "name": "Honey"
   },
   {
      "id": "2",
      "name": "Almond"
   }
]

APIを使用するには、指定されたポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。
  • Exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products")
   public String getProductList() {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity <String> entity = new HttpEntity<String>(headers);

      return restTemplate.exchange("
         http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
   }
}

POST

  • RestTemplateを使用したPOST APIの使用-exchange()メソッド *

このURL* http://localhost:8080/products *が以下に示す応答を返すと想定します。Restテンプレートを使用してこのAPI応答を使用します。

以下に示すコードは、リクエストの本文です-

{
   "id":"3",
   "name":"Ginger"
}

以下に示すコードは、応答本文です-

Product is created successfully

APIを使用するには、以下のポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。 ここでは、Productオブジェクトをラップしてリクエスト本文に送信します。
  • exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products", method = RequestMethod.POST)
   public String createProducts(@RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
   }
}

PUT

  • RestTemplateを使用したPUT APIの使用-exchange()メソッド *

このURL* http://localhost:8080/products/3 *が以下の応答を返し、Rest Templateを使用してこのAPI応答を使用すると仮定します。

以下に示すコードはリクエスト本文です-

{
   "name":"Indian Ginger"
}

以下に示すコードは、応答本文です-

Product is updated successfully

APIを使用するには、以下のポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。 ここでは、Productオブジェクトをラップしてリクエスト本文に送信します。
  • exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.PUT)
   public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
   }
}

DELETE

  • RestTemplateを使用したDELETE APIの使用-exchange()メソッド *

このURL* http://localhost:8080/products/3 *が以下に示す応答を返し、Rest Templateを使用してこのAPI応答を使用すると仮定します。

以下に示すコードのこの行は、応答本文です-

Product is deleted successfully

APIを使用するには、以下に示すポイントに従う必要があります-

  • Restテンプレートオブジェクトを自動配線しました。
  • HttpHeadersを使用して、リクエストヘッダーを設定します。
  • HttpEntityを使用して、要求オブジェクトをラップします。
  • exchange()メソッドのURL、HttpMethod、およびReturn型を指定します。
@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.DELETE)
   public String deleteProduct(@PathVariable("id") String id) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
   }
}

完全なRest Template Controllerクラスファイルは以下のとおりです-

package com.finddevguides.demo.controller;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.finddevguides.demo.model.Product;

@RestController
public class ConsumeWebService {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/template/products")
   public String getProductList() {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<String> entity = new HttpEntity<String>(headers);

      return restTemplate.exchange(
         "http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
   }
   @RequestMapping(value = "/template/products", method = RequestMethod.POST)
   public String createProducts(@RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
   }
   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.PUT)
   public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
   }
   @RequestMapping(value = "/template/products/{id}", method = RequestMethod.DELETE)
   public String deleteProduct(@PathVariable("id") String id) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<Product> entity = new HttpEntity<Product>(headers);

      return restTemplate.exchange(
         "http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
   }
}

Spring Boot Application Classのコード-DemoApplication.javaは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Mavenビルドのコード– pom.xmlは以下のとおりです-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle Buildのコード– build.gradleを以下に示します-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、以下に示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後に、build/libsディレクトリの下にJARファイルがあります。

今、次のコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、アプリケーションはTomcatポート8080で開始されました。

Tomcat Port_8080で開始されたアプリケーション

次に、POSTMANアプリケーションで以下のURLにアクセスすると、出力を確認できます。

Restテンプレートによる製品の取得- http://localhost:8080/template/products

RESTテンプレートで製品を取得

製品の作成POST- http://localhost:8080/template/products

製品POSTの作成

製品PUTの更新- http://localhost:8080/template/products/3

製品の更新POST

製品の削除- http://localhost:8080/template/products/3

商品の削除POST

Spring Boot-ファイル処理

この章では、Webサービスを使用してファイルをアップロードおよびダウンロードする方法を学習します。

ファイルアップロード

ファイルをアップロードするには、 MultipartFile を要求パラメーターとして使用できます。このAPIはマルチパートフォームデータ値を使用する必要があります。 以下のコードを確認してください-

@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

public String fileUpload(@RequestParam("file") MultipartFile file) {
   return null;
}

同じための完全なコードは以下のとおりです-

package com.finddevguides.demo.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileUploadController {
   @RequestMapping(value = "/upload", method = RequestMethod.POST,
      consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

   public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
      File convertFile = new File("/var/tmp/"+file.getOriginalFilename());
      convertFile.createNewFile();
      FileOutputStream fout = new FileOutputStream(convertFile);
      fout.write(file.getBytes());
      fout.close();
      return "File is upload successfully";
   }
}

ファイルのダウンロード

ファイルのダウンロードでは、ファイルのダウンロードにInputStreamResourceを使用する必要があります。 ResponseでHttpHeader Content-Disposition を設定し、アプリケーションの応答メディアタイプを指定する必要があります。

-次の例では、アプリケーションが実行されている指定されたパスでファイルが使用可能である必要があります。

@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<Object> downloadFile() throws IOException  {
   String filename = "/var/tmp/mysql.png";
   File file = new File(filename);
   InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
   HttpHeaders headers = new HttpHeaders();

   headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
   headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
   headers.add("Pragma", "no-cache");
   headers.add("Expires", "0");

   ResponseEntity<Object>
   responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(
      MediaType.parseMediaType("application/txt")).body(resource);

   return responseEntity;
}

同じための完全なコードは以下のとおりです-

package com.finddevguides.demo.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FileDownloadController {
   @RequestMapping(value = "/download", method = RequestMethod.GET)
   public ResponseEntity<Object> downloadFile() throws IOException  {
      String filename = "/var/tmp/mysql.png";
      File file = new File(filename);
      InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
      HttpHeaders headers = new HttpHeaders();

      headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
      headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
      headers.add("Pragma", "no-cache");
      headers.add("Expires", "0");

      ResponseEntity<Object>
      responseEntity = ResponseEntity.ok().headers(headers).contentLength(
         file.length()).contentType(MediaType.parseMediaType("application/txt")).body(resource);

      return responseEntity;
   }
}

メインのSpring Bootアプリケーションは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Mavenビルドのコード– pom.xmlは以下のとおりです-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle Buildのコード– build.gradleを以下に示します-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

これで、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行できます-

Mavenの場合、以下のコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用できます-

sgradle clean build

「BUILD SUCCESSFUL」の後に、build/libsディレクトリの下にJARファイルがあります。

今、次のコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これは、以下に示すようにTomcatポート8080でアプリケーションを開始します-

POSTMANアプリケーション

今、POSTMANアプリケーションで以下のURLを押すと、以下に示すように出力を見ることができます-

ファイルのアップロード- http://localhost:8080/upload

POSTMANアプリケーションファイルのアップロード

ファイルのダウンロード- http://localhost:8080/upload

Spring Boot-サービスコンポーネント

サービスコンポーネントは、@ Serviceアノテーションを含むクラスファイルです。 これらのクラスファイルは、@ RestControllerクラスファイルとは別のレイヤーにビジネスロジックを記述するために使用されます。 サービスコンポーネントクラスファイルを作成するためのロジックはここに示されています-

public interface ProductService {
}

@Service注釈付きのインターフェイスを実装するクラスは次のとおりです-

@Service
public class ProductServiceImpl implements ProductService {
}

このチュートリアルでは、製品の保存、取得、更新、削除に Product Service API を使用していることに注意してください。 @RestControllerクラスファイル自体にビジネスロジックを記述しました。 次に、ビジネスロジックコードをコントローラーからサービスコンポーネントに移動します。

以下に示すコードを使用して、追加、編集、取得、および削除メソッドを含むインターフェイスを作成できます-

package com.finddevguides.demo.service;

import java.util.Collection;
import com.finddevguides.demo.model.Product;

public interface ProductService {
   public abstract void createProduct(Product product);
   public abstract void updateProduct(String id, Product product);
   public abstract void deleteProduct(String id);
   public abstract Collection<Product> getProducts();
}

次のコードを使用すると、@ Serviceアノテーションを使用してProductServiceインターフェースを実装するクラスを作成し、製品を保存、取得、削除、更新するビジネスロジックを記述できます。

package com.finddevguides.demo.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.finddevguides.demo.model.Product;

@Service
public class ProductServiceImpl implements ProductService {
   private static Map<String, Product> productRepo = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);

      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);
   }
   @Override
   public void createProduct(Product product) {
      productRepo.put(product.getId(), product);
   }
   @Override
   public void updateProduct(String id, Product product) {
      productRepo.remove(id);
      product.setId(id);
      productRepo.put(id, product);
   }
   @Override
   public void deleteProduct(String id) {
      productRepo.remove(id);

   }
   @Override
   public Collection<Product> getProducts() {
      return productRepo.values();
   }
}

ここのコードはRest Controllerクラスファイルを示しています。ここでは、ProductServiceインターフェイスを@Autowiredし、メソッドを呼び出しています。

package com.finddevguides.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.finddevguides.demo.model.Product;
import com.finddevguides.demo.service.ProductService;

@RestController
public class ProductServiceController {
   @Autowired
   ProductService productService;

   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(productService.getProducts(), HttpStatus.OK);
   }
   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object>
      updateProduct(@PathVariable("id") String id, @RequestBody Product product) {

      productService.updateProduct(id, product);
      return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
   }
   @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
   public ResponseEntity<Object> delete(@PathVariable("id") String id) {
      productService.deleteProduct(id);
      return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
   }
   @RequestMapping(value = "/products", method = RequestMethod.POST)
   public ResponseEntity<Object> createProduct(@RequestBody Product product) {
      productService.createProduct(product);
      return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
   }
}

POJOクラスのコード-Product.javaはここに示されています-

package com.finddevguides.demo.model;

public class Product {
   private String id;
   private String name;

   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

メインのSpring Bootアプリケーションは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Mavenビルドのコード– pom.xmlを以下に示します-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle Buildのコード– build.gradleを以下に示します-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

あなたは、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行することができます-

Mavenの場合、以下に示すようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後に、build/libsディレクトリの下にJARファイルがあります。

以下のコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、以下の画像に示すように、アプリケーションはTomcatポート8080で開始されました-

BUILD SUCCESSFUL

今、POSTMANアプリケーションで以下のURLを押すと、以下に示すように出力を見ることができます-

GET API URLは− http://localhost:8080/products

Postman Application GET API URL

POST API URLは- http://localhost:8080/products

Postman Application POST API URL

PUT API URLは- http://localhost:8080/products/3 です

Postman Application PUT API URL

DELETE API URLは- http://localhost:8080/products/3 です

Postman Application DELETE API URL

春のブーツ-タイムリーフ

Thymeleafは、Webアプリケーションの作成に使用されるJavaベースのライブラリです。 WebアプリケーションでXHTML/HTML5を提供するための優れたサポートを提供します。 この章では、Thymeleafについて詳しく学習します。

Thymeleafテンプレート

Thymeleafは、ファイルを整形式のXMLファイルに変換します。 それは以下に示すようにテンプレートの6種類が含まれています-

  • XML
  • 有効なXML
  • XHTML
  • 有効なXHTML
  • HTML5
  • レガシーHTML5

レガシーHTML5を除くすべてのテンプレートは、整形式の有効なXMLファイルを参照しています。 レガシーHTML5では、閉じていないタグを含むWebページでHTML5タグをレンダリングできます。

ウェブアプリケーション

Thymeleafテンプレートを使用して、Spring BootでWebアプリケーションを作成できます。 Thymeleafを使用してSpring BootでWebアプリケーションを作成するには、次の手順に従う必要があります。

次のコードを使用して、リクエストURIをHTMLファイルにリダイレクトする@Controllerクラスファイルを作成します-

package com.finddevguides.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebController {
   @RequestMapping(value = "/index")
   public String index() {
      return "index";
   }
}

上記の例では、リクエストURIは /index であり、コントロールはindexlファイルにリダイレクトされます。 indexlファイルはテンプレートディレクトリの下に配置し、すべてのJSおよびCSSファイルはクラスパスの静的ディレクトリの下に配置する必要があります。 示された例では、CSSファイルを使用してテキストの色を変更しました。

次のコードを使用して、別のフォルダー css にCSSファイルを作成し、ファイルにstyles.cssという名前を付けることができます-

h4 {
   color: red;
}

indexlファイルのコードを以下に示します-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1"/>
      <link href = "css/styles.css" rel = "stylesheet"/>
      <title>Spring Boot Application</title>
   </head>
   <body>
      <h4>Welcome to Thymeleaf Spring Boot web application</h4>
   </body>
</html>

プロジェクトエクスプローラは、以下のスクリーンショットに示されています-

プロジェクトエクスプローラーのスクリーンショット

ここで、Spring Boot Starter Thymeleaf依存関係をビルド構成ファイルに追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます-

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます-

compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Mavenのコード– pom.xmlは以下のとおりです-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradleのコード-build.gradleは以下のとおりです-

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、スプリングブートアプリケーションを実行できます-

Mavenの場合、以下に示すようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すようにコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

ここで指定されたコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、アプリケーションは以下に示すようにTomcatポート8080で開始されました-

Tomcat Port_8080で開始されたアプリケーション

今、あなたのウェブブラウザでURLを打つと、次のように出力を見ることができます-

*http://localhost:8080/index*

Spring Boot Thymleaf Webアプリケーション

RESTful Webサービスの使用

この章では、jQuery AJAXを使用したRESTful Webサービスの使用について詳しく説明します。

簡単なSpring Boot Webアプリケーションを作成し、HTMLファイルにリダイレクトしてRESTful Webサービスを使用するために使用されるコントローラークラスファイルを記述します。

ビルド構成ファイルにSpring BootスターターThymeleafおよびWeb依存関係を追加する必要があります。

Mavenユーザーの場合、pom.xmlファイルに以下の依存関係を追加します。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Gradleユーザーの場合、以下の依存関係をbuild.gradleファイルに追加します-

compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-thymeleaf’
compile(‘org.springframework.boot:spring-boot-starter-web’)

@Controllerクラスファイルのコードは以下のとおりです-

@Controller
public class ViewController {
}

以下に示すように、HTMLファイルにリダイレクトするリクエストURIメソッドを定義できます-

@RequestMapping(“/view-products”)
public String viewProducts() {
   return “view-products”;
}
@RequestMapping(“/add-products”)
public String addProducts() {
   return “add-products”;
}

このAPI http://localhost:9090/products は、以下に示すように、応答として以下のJSONを返す必要があります-

[
   {
      "id": "1",
      "name": "Honey"
   },
   {
      "id": "2",
      "name": "Almond"
   }
]

次に、クラスパスのテンプレートディレクトリの下にview-productslファイルを作成します。

HTMLファイルに、jQueryライブラリを追加し、ページのロード時にRESTful Webサービスを使用するコードを記述しました。

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
   $.getJSON("http://localhost:9090/products", function(result){
      $.each(result, function(key,value) {
         $("#productsJson").append(value.id+" "+value.name+" ");
      });
   });
});
</script>

POSTメソッドとこのURL http://localhost:9090/products には、以下の要求本文と応答本文が含まれている必要があります。

リクエスト本文のコードは以下のとおりです-

{
   "id":"3",
   "name":"Ginger"
}

応答本文のコードは以下のとおりです-

Product is created successfully

次に、クラスパスのテンプレートディレクトリの下にadd-productslファイルを作成します。

HTMLファイルにjQueryライブラリを追加し、ボタンをクリックするとフォームをRESTful Webサービスに送信するコードを記述しました。

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function() {
         var productmodel = {
            id : "3",
            name : "Ginger"
         };
         var requestJSON = JSON.stringify(productmodel);
         $.ajax({
            type : "POST",
            url : "http://localhost:9090/products",
            headers : {
               "Content-Type" : "application/json"
            },
            data : requestJSON,
            success : function(data) {
               alert(data);
            },
            error : function(data) {
            }
         });
      });
   });
</script>

完全なコードは以下の通りです。

Maven – pom.xmlファイル

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradleのコード-build.gradleは以下のとおりです-

buildscript {
   ext {
      springBootVersion = ‘1.5.8.RELEASE’
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: ‘java’
apply plugin: ‘eclipse’
apply plugin: ‘org.springframework.boot’

group = ‘com.finddevguides’
version = ‘0.0.1-SNAPSHOT’
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}

dependencies {
   compile(‘org.springframework.boot:spring-boot-starter-web’)
   compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-thymeleaf’
   testCompile(‘org.springframework.boot:spring-boot-starter-test’)
}

以下に示すコントローラクラスファイル– ViewController.javaは以下に示します-

package com.finddevguides.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ViewController {
   @RequestMapping(“/view-products”)
   public String viewProducts() {
      return “view-products”;
   }
   @RequestMapping(“/add-products”)
   public String addProducts() {
      return “add-products”;
   }
}

以下はview-productslファイルです-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1"/>
      <title>View Products</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

      <script>
         $(document).ready(function(){
            $.getJSON("http://localhost:9090/products", function(result){
               $.each(result, function(key,value) {
                  $("#productsJson").append(value.id+" "+value.name+" ");
               });
            });
         });
      </script>
   </head>

   <body>
      <div id = "productsJson"> </div>
   </body>
</html>

add-productslファイルを以下に示します-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1"/>
      <title>Add Products</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

      <script>
         $(document).ready(function() {
            $("button").click(function() {
               var productmodel = {
                  id : "3",
                  name : "Ginger"
               };
               var requestJSON = JSON.stringify(productmodel);
               $.ajax({
                  type : "POST",
                  url : "http://localhost:9090/products",
                  headers : {
                     "Content-Type" : "application/json"
                  },
                  data : requestJSON,
                  success : function(data) {
                     alert(data);
                  },
                  error : function(data) {
                  }
               });
            });
         });
      </script>
   </head>

   <body>
      <button>Click here to submit the form</button>
   </body>
</html>

メインのSpring Boot Applicationクラスファイルは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

これで、次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、以下のコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下のコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次のコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、アプリケーションはTomcatポート8080で開始されました。

Tomcat Port_8080で開始されたアプリケーション

今、あなたのウェブブラウザでURLを打つと、次のように出力を見ることができます-

http://localhost:8080/view-products

1Honey_2Almond

http://localhost:8080/add-products

フォームスプリングブートの送信

今、ボタンをクリックして*フォームを送信するには*ここをクリックして、あなたが示すように結果を見ることができます-

フォームスプリングブート出力ウィンドウの送信

次に、製品の表示URLを押して、作成された製品を確認します。

*http://localhost:8080/view-products*

1Honey 2Almond 3Ginger

Angular JS

Angular JSを使用してAPIを使用するには、以下に示す例を使用できます-

次のコードを使用してAngular JS Controllerを作成し、GET APIを使用します- http://localhost:9090/products -

angular.module('demo', [])
.controller('Hello', function($scope, $http) {
   $http.get('http://localhost:9090/products').
   then(function(response) {
      $scope.products = response.data;
   });
});

次のコードを使用してAngular JS Controllerを作成し、POST APIを使用します- http://localhost:9090/products -

angular.module('demo', [])
.controller('Hello', function($scope, $http) {
   $http.post('http://localhost:9090/products',data).
   then(function(response) {
      console.log("Product created successfully");
   });
});

-Postメソッドデータは、製品を作成するためのJSON形式のリクエスト本文を表します。

Spring Boot-CORSサポート

Cross-Origin Resource Sharing(CORS)は、Webブラウザーに実装されたリソースを制限できるセキュリティ概念です。 異なるオリジンに対してリクエストを生成または消費するJavaScriptコードを防ぎます。

たとえば、Webアプリケーションが8080ポートで実行されており、JavaScriptを使用して9090ポートからRESTful Webサービスを使用しようとしています。 このような状況では、Webブラウザーでクロスオリジンリソース共有のセキュリティ問題に直面します。

この問題を処理するには2つの要件が必要です-

  • RESTful Webサービスは、クロスオリジンリソース共有をサポートする必要があります。
  • RESTful Webサービスアプリケーションは、8080ポートからAPIへのアクセスを許可する必要があります。

この章では、RESTful Webサービスアプリケーションのクロスオリジンリクエストを有効にする方法について詳しく学習します。

コントローラーメソッドでCORSを有効にする

コントローラーメソッドに @ CrossOrigin アノテーションを使用して、RESTful Webサービスの起点を設定する必要があります。 この@CrossOrigin注釈は、アプリケーション全体ではなく、特定のREST APIをサポートしています。

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {
   return null;
}

グローバルCORS設定

表示された@Bean構成を定義して、CORS構成サポートをSpring Bootアプリケーションにグローバルに設定する必要があります。

@Bean
public WebMvcConfigurer corsConfigurer() {
   return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/products").allowedOrigins("http://localhost:9000");
      }
   };
}

メインのSpring BootアプリケーションでCORS構成をグローバルに設定するコードを以下に示します。

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/products").allowedOrigins("http://localhost:8080");
         }
      };
   }
}

これで、8080ポートで実行されるSpring Boot Webアプリケーションと、9090ポートで実行できるRESTful Webサービスアプリケーションを作成できます。 RESTful Webサービスに関する実装の詳細については、このチュートリアルの Consuming RESTful Web Services というタイトルの章を参照してください。

Spring Boot-国際化

国際化とは、ソースコードを工学的に変更することなく、アプリケーションをさまざまな言語や地域に適応させるプロセスです。 言い換えれば、国際化はローカライズの準備ができていることです。

この章では、Spring Bootで国際化を実装する方法について詳しく学習します。

依存関係

Spring BootでWebアプリケーションを開発するには、Spring Boot Starter WebとSpring Boot Starter Thymeleafの依存関係が必要です。

メーベン

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Gradle

compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

LocaleResolver

アプリケーションのデフォルトのロケールを決定する必要があります。 Spring BootアプリケーションにLocaleResolver Beanを追加する必要があります。

@Bean
public LocaleResolver localeResolver() {
   SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
   sessionLocaleResolver.setDefaultLocale(Locale.US);
   return sessionLocaleResolver;
}

LocaleChangeInterceptor

LocaleChangeInterceptorは、要求に追加された言語パラメーターの値に基づいて新しいロケールを変更するために使用されます。

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
   LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
   localeChangeInterceptor.setParamName("language");
   return localeChangeInterceptor;
}

この効果を得るには、アプリケーションのレジストリインターセプターにLocaleChangeInterceptorを追加する必要があります。 構成クラスは、WebMvcConfigurerAdapterクラスを拡張し、addInterceptors()メソッドをオーバーライドする必要があります。

@Override
public void addInterceptors(InterceptorRegistry registry) {
   registry.addInterceptor(localeChangeInterceptor());
}

メッセージソース

Spring Bootアプリケーションはデフォルトで、クラスパスの下の src/main/resources フォルダーからメッセージソースを取得します。 デフォルトのロケールメッセージファイル名は message.properties であり、各ロケールのファイルは messages_XX.properties である必要があります。 「XX」はロケールコードを表します。

すべてのメッセージプロパティをキーペア値として使用する必要があります。 ロケールでプロパティが見つからない場合、アプリケーションはmessages.propertiesファイルのデフォルトプロパティを使用します。

デフォルトのmessages.propertiesは次のようになります-

welcome.text=Hi Welcome to Everyone

フランス語のmessages_fr.propertiesは次のようになります-

welcome.text=Salut Bienvenue à tous

注意-メッセージのソースファイルは「UTF-8」ファイル形式で保存する必要があります。

HTMLファイル

HTMLファイルで、構文*#\ {key} *を使用して、プロパティファイルからのメッセージを表示します。

<h1 th:text = "#{welcome.text}"></h1>

完全なコードは以下の通りです

Maven – pom.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/>
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

Gradle – build.gradle

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

メインのSpring Bootアプリケーションクラスファイルは以下のとおりです-

package com.finddevguides.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

コントローラクラスファイルは以下のとおりです-

package com.finddevguides.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ViewController {
   @RequestMapping("/locale")
   public String locale() {
      return "locale";
   }
}

国際化をサポートする構成クラス

package com.finddevguides.demo;

import java.util.Locale;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Configuration
public class Internationalization extends WebMvcConfigurerAdapter {
   @Bean
   public LocaleResolver localeResolver() {
      SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
      sessionLocaleResolver.setDefaultLocale(Locale.US);
      return sessionLocaleResolver;
   }
   @Bean
   public LocaleChangeInterceptor localeChangeInterceptor() {
      LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
      localeChangeInterceptor.setParamName("language");
      return localeChangeInterceptor;
   }
   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(localeChangeInterceptor());
   }
}

メッセージソース-messages.propertiesは次のとおりです-

welcome.text = Hi Welcome to Everyone

メッセージソース-message_fr.propertiesは次のとおりです-

welcome.text = Salut Bienvenue à tous

HTMLファイルlocalelは、次のようにクラスパスのテンプレートディレクトリの下に配置する必要があります-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1"/>
      <title>Internationalization</title>
   </head>
   <body>
      <h1 th:text = "#{welcome.text}"></h1>
   </body>
</html>

次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Springブートアプリケーションを実行できます-

Mavenの場合、次のコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

今、示されているようにコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

Tomcatポート8080でアプリケーションが開始されていることがわかります。

Tomcat Port_8080で開始されたアプリケーション

今すぐあなたのWebブラウザでURL http://localhost:8080/locale をヒットすると、次の出力を見ることができます-

Webブラウザーの出力

URL http://localhost:8080/locale?language = fr は、次のような出力を提供します-

WebブラウザSalut Bienvenueを出力

スプリングブート-スケジューリング

スケジューリングは、特定の期間のタスクを実行するプロセスです。 Spring Bootは、Springアプリケーションでスケジューラーを作成するための優れたサポートを提供します。

Java Cron式

Java Cron式は、org.quartz.TriggerのサブクラスであるCronTriggerのインスタンスを構成するために使用されます。 Java cron式の詳細については、このリンクを参照できます-

https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions

@EnableSchedulingアノテーションは、アプリケーションのスケジューラーを有効にするために使用されます。 この注釈は、Spring Bootアプリケーションのメインクラスファイルに追加する必要があります。

@SpringBootApplication
@EnableScheduling

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

@Scheduledアノテーションは、特定の期間スケジューラーをトリガーするために使用されます。

@Scheduled(cron = "0 *9*  *?")
public void cronJobSch() throws Exception {
}

以下は、毎日午前9:00から午前9:59にタスクを毎分実行する方法を示すサンプルコードです。

package com.finddevguides.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(cron = "0* 9 * * ?")
   public void cronJobSch() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Java cron job expression:: " + strDate);
   }
}

次のスクリーンショットは、アプリケーションが09:03:23に開始され、cronジョブスケジューラタスクがその時点から1分ごとに実行されたことを示しています。

cronジョブスケジューラ

固定料金

固定レートスケジューラは、特定の時間にタスクを実行するために使用されます。 前のタスクの完了を待ちません。 値はミリ秒単位である必要があります。 サンプルコードはここに示されています-

@Scheduled(fixedRate = 1000)
public void fixedRateSch() {
}

アプリケーションの起動から毎秒にタスクを実行するためのサンプルコードはここに示されています-

package com.finddevguides.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(fixedRate = 1000)
   public void fixedRateSch() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Fixed Rate scheduler:: " + strDate);
   }
}

09:12:00に開始され、その後2秒ごとに固定レートスケジューラータスクが実行されたアプリケーションを示す次のスクリーンショットを確認してください。

実行される固定レートスケジューラタスク

固定遅延

固定遅延スケジューラは、特定の時間にタスクを実行するために使用されます。 前のタスクの完了を待つ必要があります。 値はミリ秒単位である必要があります。 サンプルコードはここに示されています-

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void fixedDelaySch() {
}

ここで、initialDelayは、初期遅延値の後、タスクが最初に実行されるまでの時間です。

アプリケーションの起動から3秒が完了した後、毎秒タスクを実行する例を以下に示します-

package com.finddevguides.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(fixedDelay = 1000, initialDelay = 3000)
   public void fixedDelaySch() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Fixed Delay scheduler:: " + strDate);
   }
}

09:18:39に開始され、3秒ごとに、固定遅延スケジューラタスクが毎秒実行されるアプリケーションを示す次のスクリーンショットを確認してください。

実行された固定遅延スケジューラタスク

Spring Boot-HTTPSを有効にする

デフォルトでは、Spring Bootアプリケーションは、アプリケーションの起動時にHTTP 8080ポートを使用します。

Tomcat port_8080で開始されたアプリケーション

あなたは、Spring BootアプリケーションでHTTPSとポート443を設定するために、以下に示す手順に従う必要があります-

  • SSL証明書の取得-自己署名証明書を作成するか、認証局から取得します
  • HTTPSおよび443ポートを有効にする

自己署名証明書

自己署名証明書を作成するために、Javaランタイム環境には証明書管理ユーティリティのキーツールがバンドルされています。 このユーティリティツールは、自己署名証明書を作成するために使用されます。 それはここで与えられたコードに示されています-

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
Enter keystore password:
   Re-enter new password:
   What is your first and last name?
   [Unknown]:
   What is the name of your organizational unit?
   [Unknown]:
   What is the name of your organization?
   [Unknown]:
   What is the name of your City or Locality?
   [Unknown]:
   What is the name of your State or Province?
   [Unknown]:
   What is the two-letter country code for this unit?
   [Unknown]:
   Is CN = Unknown, OU=Unknown, O = Unknown, L = Unknown, ST = Unknown, C = Unknown correct?
   [no]: yes

このコードは、keystore.p12という名前のPKCS12キーストアファイルを生成し、証明書のエイリアス名はtomcatです。

HTTPSを構成する

サーバーポートを443、キーストアファイルパス、キーストアパスワード、キーストアタイプ、およびキーエイリアス名としてapplication.propertiesファイルに提供する必要があります。 ここで与えられたコードを観察します-

server.port: 443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: springboot
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

YAMLプロパティを使用している場合、application.ymlの下で次のコードを使用できます-

server:
   port: 443
   ssl:
      key-store: keystore.p12
      key-store-password: springboot
      keyStoreType: PKCS12
      keyAlias: tomcat

次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、次のコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のコマンドを使用できます

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

今、次のコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

さて、アプリケーションは示されているようにhttpsでTomcatポート443で開始されました-

Tomcatポート443で開始されたアプリケーション

Spring Boot-Eureka Server

Eureka Serverは、すべてのクライアントサービスアプリケーションに関する情報を保持するアプリケーションです。 すべてのマイクロサービスはEurekaサーバーに登録され、Eurekaサーバーは各ポートとIPアドレスで実行されているすべてのクライアントアプリケーションを認識します。 Eureka ServerはDiscovery Serverとしても知られています。

この章では、Eurekaサーバーの構築方法について詳しく学習します。

Eurekaサーバーの構築

Eureka Serverには、Spring Cloudのバンドルが付属しています。 そのためには、Eurekaサーバーを開発し、デフォルトのポート8761で実行する必要があります。

Spring Initializerのホームページhttps://start.spring.io/にアクセスして、Eurekaサーバーに依存するSpring Bootプロジェクトをダウンロードします。 以下のスクリーンショットに示されています-

Eurekaサーバーの構築

メインのSpring Boot Applicationクラスファイルにプロジェクトをダウンロードした後、@ EnableEurekaServerアノテーションを追加する必要があります。 @EnableEurekaServerアノテーションは、Spring BootアプリケーションをEureka Serverとして機能させるために使用されます。

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaserverApplication {
   public static void main(String[] args) {
      SpringApplication.run(EurekaserverApplication.class, args);
   }
}

Spring cloud Eurekaサーバーの依存関係がビルド構成ファイルに追加されていることを確認してください。

Mavenユーザー依存関係のコードを以下に示します-

<dependency>
<groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

Gradleユーザー依存関係のコードは以下のとおりです-

compile('org.springframework.cloud:spring-cloud-starter-eureka-server')

完全なビルド構成ファイルは以下のとおりです-

*Maven pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>eurekaserver</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>eurekaserver</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-eureka-server</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

デフォルトでは、Eureka Serverは自身をディスカバリーに登録します。 下記の設定をapplication.propertiesファイルまたはapplication.ymlファイルに追加する必要があります。

application.propertiesファイルは以下のとおりです-

eureka.client.registerWithEureka = false
eureka.client.fetchRegistry = false
server.port = 8761

application.ymlファイルは以下のとおりです-

eureka:
   client:
      registerWithEureka: false
      fetchRegistry: false
server:
   port: 8761

これで、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行できます-

Mavenの場合、以下に示すようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

今、次のコマンドを使用してJARファイルを実行します-

 java –jar <JARFILE>

以下に示すように、アプリケーションはTomcatポート8761で開始されていることがわかります-

Tomcatポート8761で開始されたアプリケーション

今、あなたのウェブブラウザでURL http://localhost:8761/ を打つと、以下に示すようにポート8761で実行されているユーレカサーバーを見つけることができます-

ポート8761で実行されているEurekaサーバー

ユーレカでのサービス登録

この章では、Spring Boot MicroサービスアプリケーションをEureka Serverに登録する方法について詳しく学習します。 アプリケーションを登録する前に、Eureka Serverがポート8761で実行されていることを確認するか、最初にEureka Serverをビルドして実行してください。 Eurekaサーバーの構築の詳細については、前の章を参照してください。

まず、ビルド構成ファイルに次の依存関係を追加して、マイクロサービスをEurekaサーバーに登録する必要があります。

Mavenユーザーは、次の依存関係を pom.xml ファイルに追加できます-

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

Gradleユーザーは、次の依存関係を build.gradle ファイルに追加できます-

compile('org.springframework.cloud:spring-cloud-starter-eureka')

次に、メインのSpring Bootアプリケーションクラスファイルに@EnableEurekaClientアノテーションを追加する必要があります。 @EnableEurekaClientアノテーションは、Spring BootアプリケーションをEurekaクライアントとして機能させます。

メインのSpring Bootアプリケーションは以下のとおりです-

package com.finddevguides.eurekaclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class EurekaclientApplication {
   public static void main(String[] args) {
      SpringApplication.run(EurekaclientApplication.class, args);
   }
}

Spring BootアプリケーションをEureka Serverに登録するには、application.propertiesファイルまたはapplication.ymlファイルに次の構成を追加し、構成にEureka Server URLを指定する必要があります。

application.ymlファイルのコードは以下のとおりです-

eureka:
   client:
      serviceUrl:
         defaultZone: http://localhost:8761/eureka
      instance:
      preferIpAddress: true
spring:
   application:
      name: eurekaclient

application.propertiesファイルのコードは以下のとおりです-

eureka.client.serviceUrl.defaultZone  = http://localhost:8761/eureka
eureka.client.instance.preferIpAddress = true
spring.application.name = eurekaclient

ここで、Rest Endpointを追加して、メインのSpring BootアプリケーションにStringを返し、ビルド構成ファイルにSpring Boot Starter Web依存関係を追加します。 以下のコードを確認してください-

package com.finddevguides.eurekaclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaclientApplication {
   public static void main(String[] args) {
      SpringApplication.run(EurekaclientApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String home() {
      return "Eureka Client application";
   }
}

構成ファイル全体を以下に示します。

*Mavenユーザーの場合-pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>eurekaclient</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>eurekaclient</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-eureka</artifactId>
      </dependency>
      <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>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</projecta>
*Gradleユーザーの場合– build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-starter-eureka')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   compile('org.springframework.boot:spring-boot-starter-web')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、次のコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

今、示されているようにコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、アプリケーションはTomcatポート8080で開始され、以下に示すようにEurekaクライアントアプリケーションがEurekaサーバーに登録されます-

Tomcatポートで開始されたアプリケーション

WebブラウザでURL http://localhost:8761/にアクセスすると、Eureka ClientアプリケーションがEureka Serverに登録されていることがわかります。

Eurekaクライアントアプリケーション

ここで、WebブラウザでURL http://localhost:8080/ にアクセスし、Rest Endpointの出力を確認します。

Eurekaクライアントアプリケーション出力

Spring Boot-Zuulプロキシサーバーとルーティング

Zuul Serverは、すべての要求を処理し、マイクロサービスアプリケーションの動的ルーティングを行うゲートウェイアプリケーションです。 Zuulサーバーは、エッジサーバーとも呼ばれます。

たとえば、 /api/user はユーザーサービスにマッピングされ、/api/productsは製品サービスにマッピングされ、Zuul Serverはリクエストをそれぞれのバックエンドアプリケーションに動的にルーティングします。

この章では、Spring BootでZuul Serverアプリケーションを作成する方法を詳細に説明します。

Zuulサーバーアプリケーションの作成

Zuul Serverは、Spring Cloud依存関係にバンドルされています。 Spring Bootプロジェクトは、Spring Initializerページhttps://start.spring.io/からダウンロードして、Zuulサーバーの依存関係を選択できます。

Zuulサーバーアプリケーションの作成

メインのSpring Bootアプリケーションに@EnableZuulProxyアノテーションを追加します。 @EnableZuulProxyアノテーションは、Spring BootアプリケーションをZuulプロキシサーバーとして機能させるために使用されます。

package com.finddevguides.zuulserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableZuulProxy
public class ZuulserverApplication {
   public static void main(String[] args) {
      SpringApplication.run(ZuulserverApplication.class, args);
   }
}

ビルド構成ファイルにSpring Cloud Starter Zuul依存関係を追加する必要があります。

Mavenユーザーは、 pom.xml ファイルに次の依存関係を追加する必要があります-

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>

Gradleユーザーの場合、build.gradleファイルに以下の依存関係を追加します

compile('org.springframework.cloud:spring-cloud-starter-zuul')

Zuulルーティングの場合、application.propertiesファイルまたはapplication.ymlファイルに以下のプロパティを追加します。

spring.application.name = zuulserver
zuul.routes.products.path =/api/demo/**
zuul.routes.products.url = http://localhost:8080/
server.port = 8111

これは、http//api/demo/ への呼び出しが製品サービスに転送されることを意味します。 たとえば、 /api/demo/products/products に転送されます。

yamlファイルのユーザーは、以下に示すapplication.ymlファイルを使用できます-

server:
   port: 8111
spring:
   application:
      name: zuulserver
zuul:

routes:
   products:
      path:/api/demo/**
      url: http://localhost:8080/

注意-Zuulプロキシ経由でルーティングする前に、 http://localhost:8080/ アプリケーションが既に実行されている必要があります。

完全なビルド構成ファイルを以下に示します。

Mavenユーザーは、以下に示すpom.xmlファイルを使用できます-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>zuulserver</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>zuulserver</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-zuul</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

Gradleユーザーは、以下に示すbuild.gradleファイルを使用できます-

buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-starter-zuul')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

あなたは、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行することができます-

Mavenの場合、以下に示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次に、以下に示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

以下に示すように、Tomcatポート8111でアプリケーションが開始されていることがわかります。

Tomcat Port_8111で開始されたアプリケーション

ここで、WebブラウザでURL http://localhost:8111/api/demo/products にアクセスすると、以下に示すように /products RESTエンドポイントの出力を確認できます-

製品RESTエンドポイント

Spring Boot-クラウド構成サーバー

Spring Cloud Configuration Serverは、すべてのアプリケーション関連の構成プロパティを管理する集中化されたアプリケーションです。 この章では、Spring Cloud Configurationサーバーの作成方法について詳しく学習します。

Spring Cloud構成サーバーの作成

最初に、Spring InitializerページからSpring Bootプロジェクトをダウンロードし、Spring Cloud Config Server依存関係を選択します。 以下のスクリーンショットを確認してください-

Spring Cloud構成サーバーの作成

次に、以下に説明するように、ビルド構成ファイルにSpring Cloud Configサーバーの依存関係を追加します-

Mavenユーザーは、以下の依存関係をpom.xmlファイルに追加できます。

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-config-server</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに以下の依存関係を追加できます。

compile('org.springframework.cloud:spring-cloud-config-server')

次に、メインのSpring Bootアプリケーションクラスファイルに@EnableConfigServerアノテーションを追加します。 @EnableConfigServerアノテーションは、Spring Bootアプリケーションを構成サーバーとして機能させます。

メインのSpring Bootアプリケーションクラスファイルは以下のとおりです-

package com.finddevguides.configserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class ConfigserverApplication {
   public static void main(String[] args) {
      SpringApplication.run(ConfigserverApplication.class, args);
   }
}

次に、以下の構成をプロパティファイルに追加し、application.propertiesファイルをbootstrap.propertiesファイルに置き換えます。 以下のコードを確認してください-

server.port = 8888
spring.cloud.config.server.native.searchLocations=file:///C:/configprop/
SPRING_PROFILES_ACTIVE=native

構成サーバーはTomcatポート8888で実行され、アプリケーション構成プロパティはネイティブ検索場所からロードされます。

次に、 file:///C:/configprop/ に、クライアントアプリケーション-application.propertiesファイルを配置します。 たとえば、クライアントアプリケーションの名前は config-client で、application.propertiesファイルの名前を config-client.properties に変更し、プロパティファイルをパス file:///C:/configprop/ に配置します。

config-clientプロパティファイルのコードは次のとおりです-

welcome.message = Welcome to Spring cloud config server

完全なビルド構成ファイルは以下のとおりです-

Mavenユーザーは、以下に示す pom.xml を使用できます-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>configserver</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>configserver</name>
   <description>Demo project for Spring Boot</description>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-config-server</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradleユーザーは、以下に示すbuild.gradleファイルを使用できます-

<scope>import</scope>
</dependency>
</dependencies>
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-config-server')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

今、実行可能なJARファイルを作成し、次のMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行します-

Mavenの場合、以下のコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次のコマンドを使用してJARファイルを実行します-

 java –jar <JARFILE>

さて、ここに示すように、アプリケーションはTomcatポート8888で開始されました-

Tomcatポート8888出力

ここで、WebブラウザでURL http://localhost:8888/config-client/default/master にアクセスすると、次のようにconfig-clientアプリケーションの構成プロパティが表示されます。

Config-Client Application

Spring Boot-クラウド構成クライアント

アプリケーションによっては、変更が必要な構成プロパティが必要な場合があり、開発者はそれらを削除するか、これを実行するためにアプリケーションを再起動する必要があります。 ただし、これにより、実稼働環境でのダウンタイムやアプリケーションの再起動が必要になる場合があります。 開発者は、Spring Cloud Configuration Serverを使用して、アプリケーションを再起動したりダウンタイムしたりすることなく、新しい構成プロパティをロードできます。

Spring Cloud Configuration Serverの使用

まず、https://start.spring.io/からSpring Bootプロジェクトをダウンロードし、Spring Cloud Config Client依存関係を選択します。 次に、ビルド構成ファイルにSpring Cloud Starter Config依存関係を追加します。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

Gradleユーザーは、次の依存関係を build.gradle ファイルに追加できます。

compile('org.springframework.cloud:spring-cloud-starter-config')

次に、@ RefreshScopeアノテーションをメインのSpring Bootアプリケーションに追加する必要があります。 @RefreshScopeアノテーションは、構成サーバーから構成プロパティー値をロードするために使用されます。

package com.example.configclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;

@SpringBootApplication
@RefreshScope
public class ConfigclientApplication {
   public static void main(String[] args) {
      SpringApplication.run(ConfigclientApplication.class, args);
   }
}

ここで、application.propertiesファイルに構成サーバーのURLを追加し、アプリケーション名を指定します。

注意-設定クライアントアプリケーションを起動する前に、http://localhost:8888設定サーバーを実行する必要があります。

spring.application.name = config-client
spring.cloud.config.uri = http://localhost:8888

構成サーバーからウェルカムメッセージを読み取るための単純なRESTエンドポイントを記述するためのコードを以下に示します-

package com.example.configclient;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RefreshScope
@RestController
public class ConfigclientApplication {
   @Value("${welcome.message}")
   String welcomeText;

   public static void main(String[] args) {
      SpringApplication.run(ConfigclientApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String welcomeText() {
      return welcomeText;
   }
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、以下に示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次に、次のコマンドを使用してJARファイルを実行します。

java –jar <JARFILE>

さて、アプリケーションはここに示すようにTomcatポート8080で開始されました-

Tomcatポート8080で開始されたアプリケーション

コンソールウィンドウでログを確認できます。 config-clientアプリケーションは、 [[2]] から構成を取得しています

2017-12-08 12:41:57.682  INFO 1104 --- [
   main] c.c.c.ConfigServicePropertySourceLocator :
   Fetching config from server at: http://localhost:8888

ここでURLにアクセスすると、 http://localhost:8080/ ウェルカムメッセージが構成サーバーから読み込まれます。

Spring Cloud Config Server

次に、構成サーバーでプロパティ値を変更し、アクチュエーターのエンドポイントPOST URL http://localhost:8080/refresh にアクセスして、URL http://localhost:8080/ の新しい構成プロパティ値を確認します。

スプリングブート-アクチュエータ

Spring Boot Actuatorは、Spring Bootアプリケーションを監視および管理するための安全なエンドポイントを提供します。 デフォルトでは、すべてのアクチュエータエンドポイントが保護されています。 この章では、アプリケーションに対してSpring Bootアクチュエータを有効にする方法について詳しく学習します。

Spring Bootアクチュエータを有効にする

Spring BootアプリケーションのSpring Bootアクチュエータエンドポイントを有効にするには、ビルド構成ファイルにSpring Boot Starterアクチュエータの依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに以下の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに以下の依存関係を追加できます。

compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'

application.propertiesファイルで、アクチュエータエンドポイントのセキュリティを無効にする必要があります。

management.security.enabled = false

YAMLファイルユーザーは、application.ymlファイルに次のプロパティを追加できます。

management:
   security:
      enabled: false

Springブートアクチュエータエンドポイントへのアクセスに別のポート番号を使用する場合は、application.propertiesファイルに管理ポート番号を追加します。

management.port = 9000

YAMLファイルユーザーは、application.ymlファイルに次のプロパティを追加できます。

management:
   port: 9000

これで、次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、次のコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

これで、次のコマンドを使用してJARファイルを実行できます-

java –jar <JARFILE>

これで、アプリケーションはTomcatポート8080で開始されました。 管理ポート番号を指定した場合、同じアプリケーションが2つの異なるポート番号で実行されていることに注意してください。

TomcatポートのStartedcアプリケーション

いくつかの重要なSpring Boot Actuatorエンドポイントを以下に示します。 Webブラウザに入力して、アプリケーションの動作を監視できます。

ENDPOINTS USAGE
/metrics To view the application metrics such as memory used, memory free, threads, classes, system uptime etc.
/env To view the list of Environment variables used in the application.
/beans To view the Spring beans and its types, scopes and dependency.
/health To view the application health
/info To view the information about the Spring Boot application.
/trace To view the list of Traces of your Rest endpoints.

Spring Boot-管理サーバー

Spring Boot Actuator Endpointを使用してアプリケーションを監視するのは少し困難です。 なぜなら、「n」個のアプリケーションがある場合、すべてのアプリケーションには個別のアクチュエータエンドポイントがあるため、監視が困難になるからです。 Spring Boot Admin Serverは、Microserviceアプリケーションの管理と監視に使用されるアプリケーションです。

このような状況に対処するために、CodeCentricチームは、Spring Boot Admin UIを提供して、すべてのSpring BootアプリケーションActuatorエンドポイントを1か所で管理および監視します。

Spring Boot Admin Serverを構築するには、ビルド構成ファイルに以下の依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに以下の依存関係を追加できます-

<dependency>
   <groupId>de.codecentric</groupId>
   <artifactId>spring-boot-admin-server</artifactId>
   <version>1.5.5</version>
</dependency>
<dependency>
   <groupId>de.codecentric</groupId>
   <artifactId>spring-boot-admin-server-ui</artifactId>
   <version>1.5.5</version>
</dependency>

Gradleユーザーは、build.gradleファイルに以下の依存関係を追加できます-

compile group: 'de.codecentric', name: 'spring-boot-admin-server', version: '1.5.5'
compile group: 'de.codecentric', name: 'spring-boot-admin-server-ui', version: '1.5.5'

メインのSpring Bootアプリケーションクラスファイルに@EnableAdminServerアノテーションを追加します。 @EnableAdminServerアノテーションは、管理サーバーとして他のすべてのマイクロサービスを監視するために使用されます。

package com.finddevguides.adminserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import de.codecentric.boot.admin.config.EnableAdminServer;

@SpringBootApplication
@EnableAdminServer
public class AdminserverApplication {
   public static void main(String[] args) {
      SpringApplication.run(AdminserverApplication.class, args);
   }
}

今、示されているapplication.propertiesファイルでserver.portとアプリケーション名を定義します-

server.port = 9090
spring.application.name = adminserver

YAMLユーザーの場合、次のプロパティを使用してapplication.ymlファイルでポート番号とアプリケーション名を定義します。

server:
   port: 9090
spring:
   application:
      name: adminserver

ビルド構成ファイルを以下に示します。

*Mavenユーザーの場合– pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>adminserver</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>adminserver</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>

      <dependency>
         <groupId>de.codecentric</groupId>
         <artifactId>spring-boot-admin-server</artifactId>
         <version>1.5.5</version>
      </dependency>

      <dependency>
         <groupId>de.codecentric</groupId>
         <artifactId>spring-boot-admin-server-ui</artifactId>
         <version>1.5.5</version>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
  • Gradleユーザー向け– build.gradleファイル*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   compile group: 'de.codecentric', name: 'spring-boot-admin-server', version: '1.5.5'
   compile group: 'de.codecentric', name: 'spring-boot-admin-server-ui', version: '1.5.5'
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、ここに示すコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、ここに示すコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後に、build/libsディレクトリの下にJARファイルがあります。

次に、以下に示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

ここで、アプリケーションはここに示すようにTomcatポート9090で開始されました-

Tomcatポート9090出力

Webブラウザから以下のURLにアクセスして、管理サーバーUIを確認してください。

*http://localhost:9090/*

Webブラウザー管理サーバーUI

Spring Boot-管理クライアント

Spring Boot Admin Server経由でマイクロサービスアプリケーションを監視および管理するには、Spring Boot Adminスタータークライアントの依存関係を追加し、管理サーバーURIをアプリケーションプロパティファイルに指定する必要があります。

-アプリケーションを監視するには、MicroserviceアプリケーションのSpring Boot Actuator Endpointsを有効にする必要があります。

まず、ビルド構成ファイルに次のSpring Boot Adminスタータークライアント依存関係とSpring Bootスターターアクチュエーター依存関係を追加します。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます-

<dependency>
   <groupId>de.codecentric</groupId>
   <artifactId>spring-boot-admin-starter-client</artifactId>
   <version>1.5.5</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile group: 'de.codecentric', name: 'spring-boot-admin-starter-client', version: '1.5.5'
compile('org.springframework.boot:spring-boot-starter-actuator')

次に、Spring Boot Admin Server URLをアプリケーションプロパティファイルに追加します。

プロパティファイルユーザーの場合、application.propertiesファイルに次のプロパティを追加します。

spring.boot.admin.url = http://localhost:9090/

YAMLユーザーの場合、application.ymlファイルに次のプロパティを追加します。

spring:
   boot:
      admin:
         url: http://localhost:9000/

ここで、実行可能なJARファイルを作成し、次のMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行します。

Mavenの場合、次のようにコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

今、示されているコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

今、アプリケーションは示されているようにTomcatポート9090で開始しました-

Tomcatポート9090出力

次に、Webブラウザから次のURLにアクセスして、Spring BootアプリケーションがSpring Boot Admin Serverに登録されていることを確認します。

*http://localhost:9090/*

Spring Boot Admin Server

次に、*詳細*ボタンをクリックして、管理サーバーUIでアクチュエータエンドポイントを確認します。

管理サーバーUIのアクチュエータエンドポイント

Spring Boot-Swagger2の有効化

Swagger2は、RESTful Webサービス用のREST APIドキュメントを生成するために使用されるオープンソースプロジェクトです。 Webブラウザーを介してRESTful Webサービスにアクセスするためのユーザーインターフェイスを提供します。

Spring BootアプリケーションでSwagger2を有効にするには、ビルド構成ファイルに次の依存関係を追加する必要があります。

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.7.0</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.7.0</version>
</dependency>

Gradleユーザーの場合、build.gradleファイルに次の依存関係を追加します。

compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'

次に、メインのSpring Bootアプリケーションに@ EnableSwagger2アノテーションを追加します。 @ EnableSwagger2アノテーションは、Spring BootアプリケーションでSwagger2を有効にするために使用されます。

メインのSpring Bootアプリケーションのコードを以下に示します-

package com.finddevguides.swaggerdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(SwaggerDemoApplication.class, args);
   }
}

次に、Docket Beanを作成して、Spring Bootアプリケーション用にSwagger2を構成します。 Swagger2のREST APIを構成するには、基本パッケージを定義する必要があります。

@Bean
   public Docket productApi() {
      return new Docket(DocumentationType.SWAGGER_2).select()
         .apis(RequestHandlerSelectors.basePackage("com.finddevguides.swaggerdemo")).build();
   }

今、メインのSpring Bootアプリケーションクラスファイル自体にこのBeanを追加すると、メインのSpring Bootアプリケーションクラスは以下のようになります-

package com.finddevguides.swaggerdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(SwaggerDemoApplication.class, args);
   }
   @Bean
   public Docket productApi() {
      return new Docket(DocumentationType.SWAGGER_2).select()
         .apis(RequestHandlerSelectors.basePackage("com.finddevguides.swaggerdemo")).build();
   }
}

次に、ビルド構成ファイルに以下のSpring Boot Starter Web依存関係を追加して、以下に示すようにRESTエンドポイントを記述します-

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます-

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます-

compile('org.springframework.boot:spring-boot-starter-web')

さて、Rest Controllerファイルに2つのシンプルなRESTful WebサービスGETとPOSTを構築するコードをここに示します-

package com.finddevguides.swaggerdemo;

import java.util.ArrayList;
import java.util.List;

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

@RestController
public class SwaggerAPIController {
   @RequestMapping(value = "/products", method = RequestMethod.GET)
   public List<String> getProducts() {
      List<String> productsList = new ArrayList<>();
      productsList.add("Honey");
      productsList.add("Almond");
      return productsList;
   }
   @RequestMapping(value = "/products", method = RequestMethod.POST)
   public String createProduct() {
      return "Product is saved successfully";
   }
}

完全なビルド構成ファイルは以下のとおりです-

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.finddevguides</groupId>
   <artifactId>swagger-demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>swagger-demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>

      <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger2</artifactId>
         <version>2.7.0</version>
      </dependency>

      <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger-ui</artifactId>
         <version>2.7.0</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
} dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
   compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
}

次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、ここに示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、ここに示すようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

さて、ここに示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

今、アプリケーションは示されているようにTomcatポート8080で起動します-

Tomcatポート8080で開始されたアプリケーション

次に、WebブラウザーでURLにアクセスして、Swagger APIの機能を確認します。

*http://localhost:8080/swagger-uil*

Swagger API機能

Spring Boot-Dockerイメージの作成

Dockerは、構築と展開を容易にするコンテナー管理サービスです。 あなたがDockerの初心者であれば、このリンクで詳細を学ぶことができます-リンク:/docker/index [https://www.finddevguides.com/docker/index]

この章では、Spring BootアプリケーションにMavenとGradleの依存関係を使用してDockerイメージを作成する方法を説明します。

Dockerfileを作成する

まず、ディレクトリ src/main/docker の下に Dockerfile という名前のファイルを作成し、その内容を以下に示します。 このファイルは、Dockerイメージを作成するために重要であることに注意してください。

FROM java:8
VOLUME/tmp
ADD dockerapp-0.0.1-SNAPSHOT.jar app.jar
RUN bash -c 'touch/app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

メーベン

Mavenの場合、ビルド構成ファイル pom.xml にDocker Mavenプラグインを追加します

<properties>
   <docker.image.prefix>spring-boot-finddevguides</docker.image.prefix>
</properties>

<build>
   <plugins>
      <plugin>
         <groupId>com.spotify</groupId>
         <artifactId>docker-maven-plugin</artifactId>
         <version>1.0.0</version>

         <configuration>
            <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
            <dockerDirectory>src/main/docker</dockerDirectory>
            <resources>
               <resource>
                  <directory>${project.build.directory}</directory>
                  <include>${project.build.finalName}.jar</include>
               </resource>
            </resources>
         </configuration>
      </plugin>

      <plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
   </plugins>

</build>

完全なpom.xmlファイルは以下のとおりです-

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>dockerapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>dockerapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <docker.image.prefix>spring-boot-finddevguides</docker.image.prefix>
   </properties>

   <dependencies>
      <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>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>1.0.0</version>

            <configuration>
               <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
               <dockerDirectory>src/main/docker</dockerDirectory>
               <resources>
                  <resource>
                     <directory>${project.build.directory}</directory>
                     <include>${project.build.finalName}.jar</include>
                  </resource>
               </resources>
            </configuration>
         </plugin>

         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

これで、Mavenコマンド mvn package docker:build を使用してアプリケーションを実行できます。

MVNパッケージDockerビルド

注意-TLSなしで tcp://localhost:2375 で公開デーモンを有効にします。

ビルドが成功すると、以下に示すようにコンソールに出力が表示されます-

MVNパッケージDocker出力

次に、Dockerイメージを使用するコマンドでDockerイメージを確認し、コンソールでイメージ情報を確認します。

Docker Imagesコマンド

Gradle

Gradleビルド構成を使用してDockerイメージをビルドするには、 docker プラグインを追加し、タスク buildDocker を作成してDockerイメージを作成する必要があります。

Gradle Docker構成のコードを以下に示します。

buildscript {
   .....
   dependencies {
      .....
      classpath('se.transmode.gradle:gradle-docker:1.2')
   }
}

group = 'spring-boot-finddevguides'

.....
apply plugin: 'docker'

task buildDocker(type: Docker, dependsOn: build) {
   applicationName = jar.baseName
   dockerfile = file('src/main/docker/Dockerfile')
   doFirst {
      copy {
         from jar
         into stageDir
      }
   }
}

完全なbuild.gradleファイルを以下に示します。

buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
      classpath('se.transmode.gradle:gradle-docker:1.2')
   }
}

group = 'spring-boot-finddevguides'

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'docker'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
task buildDocker(type: Docker, dependsOn: build) {
   applicationName = jar.baseName
   dockerfile = file('src/main/docker/Dockerfile')
   doFirst {
      copy {
         from jar
         into stageDir
      }
   }
}

次に、以下に示すコマンドを使用してDockerイメージを作成します-

gradle build buildDocker

Gradle Build Docker

コマンドを実行すると、コンソールウィンドウにBUILD SUCCESSFULログが表示されます。

Dockerビルド成功

次に、 docker images を使用したコマンドでDockerイメージを表示し、コンソールでイメージの情報を確認します。

DockerImagesを使用して画像情報を取得

Spring Boot-マイクロサービスログのトレース

ほとんどの開発者は、問題が発生した場合、ログのトレースが困難になります。 これは、Spring Bootアプリケーション用のSpring Cloud SleuthとZipKinサーバーによって解決できます。

春のクラウドスルース

春のクラウドスルースログは、次の形式で印刷されます-

[application-name,traceid,spanid,zipkin-export]

どこで、

  • アプリケーション名=アプリケーションの名前
  • Traceid =同じサービスまたは1つのサービスを別のサービスに呼び出す場合、各要求と応答のtraceidは同じです。
  • Spanid = Span IdはTrace Idと一緒に印刷されます。 スパンIDは、1つのサービスを別のサービスに呼び出す要求と応答ごとに異なります。
  • Zipkin-export =デフォルトではfalseです。 trueの場合、ログはZipkinサーバーにエクスポートされます。

さて、次のようにビルド構成ファイルにSpring Cloud Starter Sleuth依存関係を追加します-

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます-

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます-

compile('org.springframework.cloud:spring-cloud-starter-sleuth')

ここで、ここに示すように、ログをSpring BootアプリケーションRest Controllerクラスファイルに追加します-

package com.finddevguides.sleuthapp;

import java.util.logging.Level;
import java.util.logging.Logger;

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

@SpringBootApplication
@RestController
public class SleuthappApplication {
   private static final Logger LOG = Logger.getLogger(SleuthappApplication.class.getName());
   public static void main(String[] args) {
      SpringApplication.run(SleuthappApplication.class, args);
   }
   @RequestMapping("/")
   public String index() {
      LOG.log(Level.INFO, "Index API is calling");
      return "Welcome Sleuth!";
   }
}

次に、示されているようにapplication.propertiesファイルにアプリケーション名を追加します-

spring.application.name = tracinglogs

ビルド構成ファイルの完全なコードは以下のとおりです-

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>sleuthapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>sleuthapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-sleuth</artifactId>
      </dependency>
      <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>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-starter-sleuth')
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、次のコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

さて、ここに示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、アプリケーションはTomcatポート8080で開始されました。

Tomcatポート8080で開始されたアプリケーション

次に、WebブラウザーでURLにアクセスし、コンソールログで出力を確認します。

*http://localhost:8080/*

ウェルカムスルースを出力

コンソールウィンドウで次のログを確認できます。 ログが次の形式で出力されることを確認します[アプリケーション名、traceid、spanid、zipkin-export]

ログが印刷されます

Zipkinサーバー

Zipkinは、Spring BootアプリケーションのSpring Cloud Sleuthログを監視および管理するアプリケーションです。 Zipkinサーバーを構築するには、ビルド構成ファイルにZipkin UIおよびZipkinサーバーの依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます-

<dependency>
   <groupId>io.zipkin.java</groupId>
   <artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
   <groupId>io.zipkin.java</groupId>
   <artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに以下の依存関係を追加できます-

compile('io.zipkin.java:zipkin-autoconfigure-ui')
compile('io.zipkin.java:zipkin-server')

次に、アプリケーションプロパティファイルでserver.port = 9411を構成します。

プロパティファイルユーザーの場合、application.propertiesファイルに以下のプロパティを追加します。

server.port = 9411

YAMLユーザーの場合、application.ymlファイルに以下のプロパティを追加します。

server:
   port: 9411

メインのSpring Bootアプリケーションクラスファイルに@EnableZipkinServerアノテーションを追加します。 @EnableZipkinServerアノテーションは、アプリケーションがZipkinサーバーとして機能できるようにするために使用されます。

package com.finddevguides.zipkinapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import zipkin.server.EnableZipkinServer;

@SpringBootApplication
@EnableZipkinServer
public class ZipkinappApplication {
   public static void main(String[] args) {
      SpringApplication.run(ZipkinappApplication.class, args);
   }
}

完全なビルド構成ファイルのコードを以下に示します。

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>zipkinapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>zipkinapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>io.zipkin.java</groupId>
         <artifactId>zipkin-server</artifactId>
      </dependency>
      <dependency>
         <groupId>io.zipkin.java</groupId>
         <artifactId>zipkin-autoconfigure-ui</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('io.zipkin.java:zipkin-autoconfigure-ui')
   compile('io.zipkin.java:zipkin-server')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

あなたは、実行可能なJARファイルを作成し、以下のMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行することができます-

Mavenの場合、以下のコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、以下に示すコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

示されているコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、以下に示すように、アプリケーションはTomcatポート9411で開始されました-

出力Tomcatポート9411

次に、以下のURLにアクセスして、ZipkinサーバーUIを確認します。

*http://localhost:9411/zipkin/*

ZipkinサーバーUI

次に、クライアントサービスアプリケーションに次の依存関係を追加し、ZipkinサーバーURLを指定して、Zipkin UIを介してマイクロサービスログをトレースします。

次に、次のように、ビルド構成ファイルにSpring Cloud Starter Zipkin依存関係を追加します-

Mavenユーザーはpom.xmlファイルに次の依存関係を追加できます-

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに以下の依存関係を追加できます-

compile('org.springframework.cloud:spring-cloud-sleuth-zipkin')

次に、Spring Bootアプリケーションに Always Sampler Bean を追加して、ログをZipkinサーバーにエクスポートします。

@Bean
public AlwaysSampler defaultSampler() {
   return new AlwaysSampler();
}

AlwaysSampler Beanを追加すると、自動的にSpring Sleuth Zipkin Exportオプションがfalseからtrueに変更されます。

次に、クライアントサービスのapplication.propertiesファイルでZipkinサーバーのベースURLを構成します。

spring.zipkin.baseUrl = http://localhost:9411/zipkin/

次に、トレースIDを指定して、Zipkin UIでトレースを見つけます。

*http://localhost:9411/zipkin/traces/\ {traceid}/*

Spring Boot-Flywayデータベース

Flywayは、すべてのインスタンスにわたってデータベーススキーマを簡単かつ確実に進化させるバージョン管理アプリケーションです。 Flywayの詳細については、https://flywaydb.org/[www.flywaydb.org]のリンクを使用できます。

多くのソフトウェアプロジェクトはリレーショナルデータベースを使用します。 これには、多くの場合スキーマ移行とも呼ばれるデータベース移行の処理が必要です。

この章では、Spring BootアプリケーションでFlywayデータベースを構成する方法について詳しく学習します。

Flywayデータベースの構成

まず、Spring Initializerページhttps://start.spring.io/[www.start.spring.io]からSpring Bootプロジェクトをダウンロードし、次の依存関係を選択します-

  • Spring Boot Starter Web
  • フライウェイ
  • MySQL
  • JDBC

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.flywaydb</groupId>
   <artifactId>flyway-core</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile('org.flywaydb:flyway-core')
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('org.springframework.boot:spring-boot-starter-web')
compile('mysql:mysql-connector-java')

アプリケーションプロパティでは、DataSourceを作成するためのデータベースプロパティと、アプリケーションプロパティで構成する必要があるフライウェイプロパティを構成する必要があります。

プロパティファイルユーザーの場合、application.propertiesファイルに以下のプロパティを追加します。

spring.application.name = flywayapp

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testOnBorrow = true
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.minEvictableIdleTimeMillis = 30000
spring.datasource.validationQuery = SELECT 1
spring.datasource.max-active = 15
spring.datasource.max-idle = 10
spring.datasource.max-wait = 8000

flyway.url = jdbc:mysql://localhost:3306/mysql
flyway.schemas = USERSERVICE
flyway.user = root
flyway.password = root

YAMLユーザーはapplication.ymlファイルに次のプロパティを追加できます。

spring:
   application:
      name: flywayapp
   datasource:
      driverClassName: com.mysql.jdbc.Driver
      url: "jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true"
      password: "root"
      username: "root"
      testOnBorrow: true
      testWhileIdle: true
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 30000
      validationQuery: SELECT 1
      max-active: 15
      max-idle: 10
      max-wait: 8000
flyway:
   url: jdbc:mysql://localhost:3306/mysql
   schemas: USERSERVICE
   user: "root"
   password: "root"

次に、 src/main/resources/db/migration ディレクトリの下にSQLファイルを作成します。 SQLファイルに「V1__Initial.sql」という名前を付けます

CREATE TABLE USERS (ID INT AUTO_INCREMENT PRIMARY KEY, USERID VARCHAR(45));
INSERT INTO USERS (ID, USERID) VALUES (1, 'finddevguides.com');

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.flywayapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

完全なビルド構成ファイルを以下に示します。

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>flywayapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>flywayapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.flywaydb</groupId>
         <artifactId>flyway-core</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-jdbc</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.flywaydb:flyway-core')
   compile('org.springframework.boot:spring-boot-starter-jdbc')
   compile('org.springframework.boot:spring-boot-starter-web')
   compile('mysql:mysql-connector-java')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

あなたは、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行することができます-

Mavenの場合、ここに示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、ここに示すコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

今、次のコマンドを使用してJARファイルを実行します-

 java –jar <JARFILE>

これで、Tomcatがポート8080で起動し、コンソールウィンドウに次のようにフライウェイデータベースログが表示されます。

フライウェイデータベースログ

これで、データベースにアクセスして選択クエリを実行できます。

データベースとクエリの選択

Spring Boot-メールの送信

Spring Boot RESTful Webサービスを使用すると、Gmail Transport Layer Securityでメールを送信できます。 この章では、この機能の使用方法を詳細に理解します。

まず、ビルド構成ファイルにSpring Boot Starter Mail依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

 compile('org.springframework.boot:spring-boot-starter-mail')

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.emailapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

図に示すように、Rest Controllerクラスファイルで簡単なRest APIを記述して電子メールに送信できます。

package com.finddevguides.emailapp;

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

@RestController
public class EmailController {
   @RequestMapping(value = "/sendemail")
   public String sendEmail() {
      return "Email sent successfully";
   }
}

Attachmentを使用して電子メールを送信するメソッドを作成できます。 mail.smtpプロパティを定義し、PasswordAuthenticationを使用します。

private void sendmail() throws AddressException, MessagingException, IOException {
   Properties props = new Properties();
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtp.host", "smtp.gmail.com");
   props.put("mail.smtp.port", "587");

   Session session = Session.getInstance(props, new javax.mail.Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
         return new PasswordAuthentication("[email protected]", "<your password>");
      }
   });
   Message msg = new MimeMessage(session);
   msg.setFrom(new InternetAddress("[email protected]", false));

   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
   msg.setSubject("Tutorials point email");
   msg.setContent("Tutorials point email", "text/html");
   msg.setSentDate(new Date());

   MimeBodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setContent("Tutorials point email", "text/html");

   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(messageBodyPart);
   MimeBodyPart attachPart = new MimeBodyPart();

   attachPart.attachFile("/var/tmp/image19.png");
   multipart.addBodyPart(attachPart);
   msg.setContent(multipart);
   Transport.send(msg);
}

次に、上記のようにRest APIから上記のsendmail()メソッドを呼び出します-

@RequestMapping(value = "/sendemail")
public String sendEmail() throws AddressException, MessagingException, IOException {
   sendmail();
   return "Email sent successfully";
}

注意-メールを送信する前に、Gmailアカウント設定で安全性の低いアプリを許可するをオンにしてください。

完全なビルド構成ファイルを以下に示します。

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>emailapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>emailapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
   <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-mail</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   compile('org.springframework.boot:spring-boot-starter-mail')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

これで、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行できます-

Mavenの場合、次のようにコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次に、以下に示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

Tomcatポート8080でアプリケーションが開始されたことがわかります。

Tomcatポート8080アプリケーション出力

Webブラウザから次のURLにアクセスすると、メールが届きます。

*http://localhost:8080/sendemail*

メール送信成功ブラウザウィンドウ

メールが正常に送信されました

スプリングブーツ-Hystrix

HystrixはNetflixのライブラリです。 Hystrixは、サービス間のアクセスポイントを分離し、サービス間の連鎖的な障害を停止し、フォールバックオプションを提供します。

たとえば、サードパーティのアプリケーションを呼び出している場合、応答を送信するのに時間がかかります。 そのため、その時点で、コントロールはフォールバックメソッドに進み、カスタム応答をアプリケーションに返します。

この章では、HystrixをSpring Bootアプリケーションに実装する方法について説明します。

まず、ビルド構成ファイルにSpring Cloud Starter Hystrix依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます-

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます-

compile('org.springframework.cloud:spring-cloud-starter-hystrix')

次に、@ EnableHystrixアノテーションをメインのSpring Bootアプリケーションクラスファイルに追加します。 @EnableHystrixアノテーションは、Hystrix機能をSpring Bootアプリケーションで有効にするために使用されます。

メインのSpring Bootアプリケーションクラスファイルのコードは以下のとおりです-

package com.finddevguides.hystrixapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;

@SpringBootApplication
@EnableHystrix
public class HystrixappApplication {
   public static void main(String[] args) {
      SpringApplication.run(HystrixappApplication.class, args);
   }
}

ここで、要求された時間から3秒後に文字列を返すような単純なRest Controllerを作成します。

@RequestMapping(value = "/")
public String hello() throws InterruptedException {
   Thread.sleep(3000);
   return "Welcome Hystrix";
}

次に、REST APIに@Hystrixコマンドと@HystrixPropertyを追加し、ミリ秒値でタイムアウトを定義します。

@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
   @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})

次に、リクエストの応答に時間がかかる場合、フォールバックメソッドfallback_hello()を定義します。

private String fallback_hello() {
   return "Request fails. It takes long time to response";
}

REST APIとHystrixプロパティを含む完全なRest Controllerクラスファイルはここに示されています-

@RequestMapping(value = "/")
@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
   @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})
public String hello() throws InterruptedException {
   Thread.sleep(3000);
   return "Welcome Hystrix";
}
private String fallback_hello() {
   return "Request fails. It takes long time to response";
}

この例では、メインのSpring Bootアプリケーションクラスファイル自体に記述されたREST API。

package com.finddevguides.hystrixapp;

import org.springframework.boot.SpringApplication;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@SpringBootApplication
@EnableHystrix
@RestController
public class HystrixappApplication {
   public static void main(String[] args) {
      SpringApplication.run(HystrixappApplication.class, args);
   }
   @RequestMapping(value = "/")
   @HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
      @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
   })
   public String hello() throws InterruptedException {
      Thread.sleep(3000);
      return "Welcome Hystrix";
   }
   private String fallback_hello() {
      return "Request fails. It takes long time to response";
   }
}

完全なビルド構成ファイルを以下に示します。

  • Maven – pom.xmlファイル*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>hystrixapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>hystrixapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-hystrix</artifactId>
      </dependency>
      <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>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
ext {
   springCloudVersion = 'Edgware.RELEASE'
}
dependencies {
   compile('org.springframework.cloud:spring-cloud-starter-hystrix')
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
   imports {
      mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
   }
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、次のようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次に、以下に示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これは、以下に示すようにTomcatポート8080でアプリケーションを開始します-

Tomcatアプリケーションコマンドプロンプト

ここで、WebブラウザからURL http://localhost:8080/ にアクセスし、Hystrixの応答を確認します。 APIの応答には3秒かかりますが、Hystrixタイムアウトは1秒です。

Request Fail Hystrix Timeout

スプリングブート-Webソケット

この章では、WebソケットでSpring Bootを使用してインタラクティブなWebアプリケーションを構築する方法を理解しましょう。

Webソケットを使用してSpring BootでインタラクティブなWebアプリケーションを構築するには、次の依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加する必要があります。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>sockjs-client</artifactId>
   <version>1.0.2</version>
</dependency>

<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>stomp-websocket</artifactId>
   <version>2.3.3</version>
</dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>3.3.7</version>        </dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>jquery</artifactId>
   <version>3.1.0</version>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます-

compile("org.springframework.boot:spring-boot-starter-websocket")
compile("org.webjars:webjars-locator")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")
compile("org.webjars:bootstrap:3.3.7")
compile("org.webjars:jquery:3.1.0")

STOMPメッセージングで動作するメッセージ処理コントローラーを作成しましょう。 STOMPメッセージは、@ Controllerクラスファイルにルーティングできます。 たとえば、GreetingControllerは、宛先「/hello」へのメッセージを処理するためにマップされます。

package com.finddevguides.websocketapp;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {
   @MessageMapping("/hello")
   @SendTo("/topic/greetings")
   public Greeting greeting(HelloMessage message) throws Exception {
      Thread.sleep(1000);//simulated delay
      return new Greeting("Hello, " + message.getName() + "!");
   }
}

次に、STOMPメッセージング用にSpringを構成します。 以下に示すように、AbstractWebSocketMessageBrokerConfigurerクラスを拡張するWebSocketConfigクラスファイルを記述します。

package com.finddevguides.websocketapp;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
   @Override
   public void configureMessageBroker(MessageBrokerRegistry config) {
      config.enableSimpleBroker("/topic");
      config.setApplicationDestinationPrefixes("/app");
   }
   @Override
   public void registerStompEndpoints(StompEndpointRegistry registry) {
      registry.addEndpoint("/finddevguides-websocket").withSockJS();
   }
}

@EnableWebSocketMessageBrokerアノテーションは、STOMPエンドポイントを作成するようにWebソケットメッセージブローカーを構成するために使用されます。

次のように、src/main/resources/static/indexlの下にブラウザクライアントファイルを作成できます-

<!DOCTYPE html>
<html>
   <head>
      <title>Hello WebSocket</title>
      <link href = "/webjars/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <link href = "/main.css" rel = "stylesheet">
      <script src = "/webjars/jquery/jquery.min.js"></script>
      <script src = "/webjars/sockjs-client/sockjs.min.js"></script>
      <script src = "/webjars/stomp-websocket/stomp.min.js"></script>
      <script src = "/app.js"></script>
   </head>

   <body>
      <noscript>
         <h2 style = "color: #ff0000">
            Seems your browser doesn't support Javascript! Websocket relies on Javascript being
            enabled. Please enable Javascript and reload this page!
         </h2>
      </noscript>
      <div id = "main-content" class = "container">
         <div class = "row">
            <div class = "col-md-6">
               <form class = "form-inline">
                  <div class = "form-group">
                     <label for = "connect">WebSocket connection:</label>
                     <button id = "connect" class = "btn btn-default" type = "submit">Connect</button>
                     <button id = "disconnect" class = "btn btn-default" type = "submit" disabled = "disabled">Disconnect
                     </button>
                  </div>
               </form>
            </div>

            <div class = "col-md-6">
               <form class = "form-inline">
                  <div class = "form-group">
                     <label for = "name">What is your name?</label>
                     <input type = "text" id = "name" class = "form-control" placeholder = "Your name here...">
                  </div>
                  <button id = "send" class = "btn btn-default" type = "submit">Send</button>
               </form>
            </div>
         </div>

         <div class  =  "row">
            <div class  =  "col-md-12">
               <table id  =  "conversation" class = "table table-striped">
                  <thead>
                     <tr>
                        <th>Greetings</th>
                     </tr>
                  </thead>
                  <tbody id  =  "greetings"></tbody>
               </table>
            </div>
         </div>
      </div>
   </body>
</html>

STOMPを使用してメッセージを消費および生成するapp.jsファイルを作成しましょう。

var stompClient = null;

function setConnected(connected) {
   $("#connect").prop("disabled", connected);
   $("#disconnect").prop("disabled", !connected);

   if (connected) {
      $("#conversation").show();
   } else {
      $("#conversation").hide();
   }
   $("#greetings")l("");
}

function connect() {
   var socket = new SockJS('/finddevguides-websocket');
   stompClient = Stomp.over(socket);
   stompClient.connect({}, function (frame) {
      setConnected(true);
      console.log('Connected: ' + frame);
      stompClient.subscribe('/topic/greetings', function (greeting) {
         showGreeting(JSON.parse(greeting.body).content);
      });
   });
}
function disconnect() {
   if (stompClient !== null) {
      stompClient.disconnect();
   }
   setConnected(false);
   console.log("Disconnected");
}
function sendName() {
   stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
   $("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
   $( "form" ).on('submit', function (e) {e.preventDefault();});
   $( "#connect" ).click(function() { connect(); });
   $( "#disconnect" ).click(function() { disconnect(); });
   $( "#send" ).click(function() { sendName(); });
});

メインのSpring Bootアプリケーションのコードを以下に示します。

package com.finddevguides.websocketapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

完全なビルド構成ファイルを以下に示します。

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>websocketapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>websocketapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
   </parent>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-websocket</artifactId>
      </dependency>
      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>webjars-locator</artifactId>
      </dependency>
      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>sockjs-client</artifactId>
         <version>1.0.2</version>
      </dependency>

      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>stomp-websocket</artifactId>
         <version>2.3.3</version>
      </dependency>
      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>bootstrap</artifactId>
         <version>3.3.7</version>
      </dependency>

      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>jquery</artifactId>
         <version>3.1.0</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

jar {
   baseName = 'websocketapp'
   version =  '0.1.0'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile("org.springframework.boot:spring-boot-starter-websocket")
   compile("org.webjars:webjars-locator")
   compile("org.webjars:sockjs-client:1.0.2")
   compile("org.webjars:stomp-websocket:2.3.3")
   compile("org.webjars:bootstrap:3.3.7")
   compile("org.webjars:jquery:3.1.0")

   testCompile("org.springframework.boot:spring-boot-starter-test")
}

スプリングブート-バッチサービス

以下に示すように、MavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、Spring Bootアプリケーションを実行できます-

Mavenの場合、以下に示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

ここで指定されたコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、示されているように、アプリケーションはTomcatポート8080で開始されました。

Tomcatポートで開始されたバッチサービスアプリケーション

ここで、WebブラウザでURL http://localhost:8080/ にアクセスし、Webソケットに接続して挨拶を送信し、メッセージを受信します。

Webソケットの送受信メッセージ

Batch Serviceは、1つのタスクで複数のコマンドを実行するプロセスです。 この章では、Spring Bootアプリケーションでバッチサービスを作成する方法を学習します。

CSVファイルのコンテンツをHSQLDBに保存する例を考えてみましょう。

Batch Serviceプログラムを作成するには、ビルド構成ファイルにSpring Boot Starter Batch依存関係とHSQLDB依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.hsqldb:hsqldb")

次に、クラスパスリソースの下に単純なCSVデータファイルを追加します– src/main/resourcesと、ファイルに示されているようにfile.csvという名前を付けます-

William,John
Mike, Sebastian
Lawarance, Lime

次に、クラスパスリソースディレクトリの下にあるHSQLDBのSQLスクリプトを作成します- request_fail_hystrix_timeout

DROP TABLE USERS IF EXISTS;
CREATE TABLE USERS  (
   user_id BIGINT IDENTITY NOT NULL PRIMARY KEY,
   first_name VARCHAR(20),
   last_name VARCHAR(20)
);

示されているようにUSERSモデルのPOJOクラスを作成します-

package com.finddevguides.batchservicedemo;
public class User {
   private String lastName;
   private String firstName;

   public User() {
   }
   public User(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   @Override
   public String toString() {
      return "firstName: " + firstName + ", lastName: " + lastName;
   }
}

ここで、CSVファイルからデータを読み込んだ後、データをSQLに書き込む前に、中間プロセッサを作成して操作を行います。

package com.finddevguides.batchservicedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;

public class UserItemProcessor implements ItemProcessor<User, User> {
   private static final Logger log = LoggerFactory.getLogger(UserItemProcessor.class);

   @Override
   public User process(final User user) throws Exception {
      final String firstName = user.getFirstName().toUpperCase();
      final String lastName = user.getLastName().toUpperCase();
      final User transformedPerson = new User(firstName, lastName);

      log.info("Converting (" + user + ") into (" + transformedPerson + ")");
      return transformedPerson;
   }
}

以下に示すように、CSVからデータを読み取り、SQLファイルに書き込むために、バッチ構成ファイルを作成します。 構成クラスファイルに@EnableBatchProcessingアノテーションを追加する必要があります。 @EnableBatchProcessingアノテーションは、Spring Bootアプリケーションのバッチ操作を有効にするために使用されます。

package com.finddevguides.batchservicedemo;

import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
   @Autowired
   public JobBuilderFactory jobBuilderFactory;

   @Autowired
   public StepBuilderFactory stepBuilderFactory;

   @Autowired
   public DataSource dataSource;

   @Bean
   public FlatFileItemReader<User> reader() {
      FlatFileItemReader<User> reader = new FlatFileItemReader<User>();
      reader.setResource(new ClassPathResource("file.csv"));
      reader.setLineMapper(new DefaultLineMapper<User>() {
         {
            setLineTokenizer(new DelimitedLineTokenizer() {
               {
                  setNames(new String[] { "firstName", "lastName" });
               }
            });
            setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() {
               {
                  setTargetType(User.class);
               }
            });
         }
      });
      return reader;
   }
   @Bean
   public UserItemProcessor processor() {
      return new UserItemProcessor();
   }
   @Bean
   public JdbcBatchItemWriter<User> writer() {
      JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<User>();
      writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<User>());
      writer.setSql("INSERT INTO USERS (first_name, last_name) VALUES (:firstName, :lastName)");
      writer.setDataSource(dataSource);
      return writer;
   }
   @Bean
   public Job importUserJob(JobCompletionNotificationListener listener) {
      return jobBuilderFactory.get("importUserJob").incrementer(
         new RunIdIncrementer()).listener(listener).flow(step1()).end().build();
   }
   @Bean
   public Step step1() {
      return stepBuilderFactory.get("step1").<User, User>chunk(10).reader(reader()).processor(processor()).writer(writer()).build();
   }
}
  • reader()*メソッドはCSVファイルからデータを読み取るために使用され、writer()メソッドはSQLにデータを書き込むために使用されます。

次に、ジョブ完了通知リスナークラスを作成する必要があります。これは、ジョブ完了後に通知するために使用されます。

package com.finddevguides.batchservicedemo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
   private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class);
   private final JdbcTemplate jdbcTemplate;

   @Autowired
   public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) {
      this.jdbcTemplate = jdbcTemplate;
   }
   @Override
   public void afterJob(JobExecution jobExecution) {
      if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
         log.info("!!! JOB FINISHED !! It's time to verify the results!!");

         List<User> results = jdbcTemplate.query(
            "SELECT first_name, last_name FROM USERS", new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int row) throws SQLException {
               return new User(rs.getString(1), rs.getString(2));
            }
         });

         for (User person : results) {
            log.info("Found <" + person + "> in the database.");
         }
      }
   }
}

ここで、実行可能なJARファイルを作成し、次のMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行します。

Mavenの場合、次のようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

ここで指定されたコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

あなたが示すように、コンソールウィンドウに出力を見ることができます-

コンソールウィンドウでのバッチサービス出力

スプリングブート-Apache Kafka

Apache Kafkaは、フォールトトレラントメッセージングシステムに基づいてメッセージを公開および購読するために使用されるオープンソースプロジェクトです。 これは、高速でスケーラブルであり、設計により配布されています。 あなたがカフカの初心者であるか、それについてよりよく理解したいなら、このリンクを参照してください-リンク:/apache_kafka/index [www.finddevguides.com/apache_kafka/]

この章では、Apache KafkaをSpring Bootアプリケーションに実装する方法を説明します。

まず、ビルド構成ファイルにSpring Kafka依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.kafka</groupId>
   <artifactId>spring-kafka</artifactId>
   <version>2.1.0.RELEASE</version>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.1.0.RELEASE'

メッセージの作成

Apache Kafkaにメッセージを生成するには、次のようにProducer構成の構成クラスを定義する必要があります-

package com.finddevguides.kafkademo;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

@Configuration
public class KafkaProducerConfig {
   @Bean
   public ProducerFactory<String, String> producerFactory() {
      Map<String, Object> configProps = new HashMap<>();
      configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
      configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
      configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
      return new DefaultKafkaProducerFactory<>(configProps);
   }
   @Bean
   public KafkaTemplate<String, String> kafkaTemplate() {
      return new KafkaTemplate<>(producerFactory());
   }
}

メッセージを公開するには、Kafkaテンプレートオブジェクトを自動接続し、図のようにメッセージを生成します。

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;

public void sendMessage(String msg) {
   kafkaTemplate.send(topicName, msg);
}

メッセージを消費する

メッセージを消費するには、次に示すようにConsumer構成クラスファイルを記述する必要があります。

package com.finddevguides.kafkademo;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;

@EnableKafka
@Configuration
public class KafkaConsumerConfig {
   @Bean
   public ConsumerFactory<String, String> consumerFactory() {
      Map<String, Object> props = new HashMap<>();
      props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:2181");
      props.put(ConsumerConfig.GROUP_ID_CONFIG, "group-id");
      props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
      props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
      return new DefaultKafkaConsumerFactory<>(props);
   }
   @Bean
   public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
      ConcurrentKafkaListenerContainerFactory<String, String>
      factory = new ConcurrentKafkaListenerContainerFactory<>();
      factory.setConsumerFactory(consumerFactory());
      return factory;
   }
}

次に、メッセージをリッスンするリスナーを作成します。

@KafkaListener(topics = "finddevguides", groupId = "group-id")
public void listen(String message) {
   System.out.println("Received Messasge in group - group-id: " + message);
}

メインのSpring BootアプリケーションクラスファイルからApplicationRunnerクラスrunメソッドからsendMessage()メソッドを呼び出し、同じクラスファイルからメッセージを消費しましょう。

あなたのメインのSpring Bootアプリケーションのクラスファイルのコードは以下のとおりです-

package com.finddevguides.kafkademo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;

@SpringBootApplication
public class KafkaDemoApplication implements ApplicationRunner {
   @Autowired
   private KafkaTemplate<String, String> kafkaTemplate;

   public void sendMessage(String msg) {
      kafkaTemplate.send("finddevguides", msg);
   }
   public static void main(String[] args) {
      SpringApplication.run(KafkaDemoApplication.class, args);
   }
   @KafkaListener(topics = "finddevguides", groupId = "group-id")
   public void listen(String message) {
      System.out.println("Received Messasge in group - group-id: " + message);
   }
   @Override
   public void run(ApplicationArguments args) throws Exception {
      sendMessage("Hi Welcome to Spring For Apache Kafka");
   }
}

完全なビルド構成ファイルのコードを以下に示します。

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>kafka-demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>kafka-demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.kafka</groupId>
         <artifactId>spring-kafka</artifactId>
         <version>2.1.0.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.1.0.RELEASE'
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

さて、実行可能なJARファイルを作成し、以下に示すようにMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行します-

Mavenの場合、次のようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

ここで指定されたコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

コンソールウィンドウで出力を確認できます。

スプリングブート-Twilio

Twilioは、SMSを送信し、アプリケーションから音声通話を行うために使用されるサードパーティアプリケーションです。 SMSを送信し、プログラムで音声通話を行うことができます。

この章では、TwilioでSpring Bootを使用して、SMSの送信および音声通話の実装を実装する方法を学習します。

-TwilioのTrailアカウントを使用してSMSを送信し、音声通話を発信しました。 Twilioの詳細については、https://www.twilio.com/[www.twilio.com]をご覧ください。

まず、ビルド構成ファイルにTwilioの依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>com.twilio.sdk</groupId>
   <artifactId>twilio</artifactId>
   <version>7.16.1</version>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile group: "com.twilio.sdk", name:"twilio", version: "7.16.1"

次に、示されているように、静的ブロックのACCOUNT_SIDとAUTH_IDでTwilioアカウントを初期化します-

static {
   Twilio.init(ACCOUNT_SID, AUTH_ID);
}

SMSを送信する

SMSを送信するには、Message.create()メソッドにfrom-numberとto-numberを提供する必要があります。 メッセージ本文の内容も、示されているようにメソッドMessage.creator()に提供する必要があります-

Message.creator(new PhoneNumber("to-number"), new PhoneNumber("from-number"),
   "Message from Spring Boot Application").create();

メインのSpring Bootアプリケーションクラスファイルは次のとおりです。

package com.finddevguides.smsdemo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

@SpringBootApplication
public class SmsdemoApplication implements ApplicationRunner {
   private final static String ACCOUNT_SID = "<your-account-sid>";
   private final static String AUTH_ID = "<your-auth-id>";

   static {
      Twilio.init(ACCOUNT_SID, AUTH_ID);
   }
   public static void main(String[] args) {
      SpringApplication.run(SmsdemoApplication.class, args);
   }
   @Override
   public void run(ApplicationArguments arg0) throws Exception {
      Message.creator(new PhoneNumber("to-number"), new PhoneNumber("from-number"),
         "Message from Spring Boot Application").create();
   }
}

構成ファイルを構築するための完全なコードは以下のとおりです-

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>smsdemo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>smsdemo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>com.twilio.sdk</groupId>
         <artifactId>twilio</artifactId>
         <version>7.16.1</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   compile group: "com.twilio.sdk", name:"twilio", version: "7.11.+"
}

次のMavenまたはGradleコマンドを使用して、実行可能なJARファイルを作成し、スプリングブートアプリケーションを実行できます-

Mavenの場合、次のようにコマンドを使用します-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

以下のコマンドを使用して、JARファイルを実行します-

java –jar <JARFILE>

これで、「to-number」へのSMSを受け取ります。

「to-number」に受信したメッセージ。

Sent from your Twilio trail account
- Message from Spring Boot Application

-この例では、Trailアカウントを使用しました。 そのため、SMSを送信する前に番号を確認する必要があります。

音声通話

Twilioを使用して音声通話を行うには、Call.creator()メソッドを呼び出す必要があります。 この方法では、ここに示すように、to-number、from-number、およびvoice-noteを提供する必要があります。

Call.creator(new PhoneNumber("<to-number>"), new PhoneNumber("<from-number>"),
   new URI("http://demo.twilio.com/docs/voice.xml")).create();

メインのSpring Bootアプリケーションクラスファイルのコードを以下に示します。

package com.finddevguides.smsdemo;

import java.net.URI;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.type.PhoneNumber;

@SpringBootApplication
public class SmsdemoApplication implements ApplicationRunner {
   private final static String ACCOUNT_SID = "<ACCOUNT-SID>";
   private final static String AUTH_ID = "AUTH-ID";

   static {
      Twilio.init(ACCOUNT_SID, AUTH_ID);
   }
   public static void main(String[] args) {
      SpringApplication.run(SmsdemoApplication.class, args);
   }
   @Override
   public void run(ApplicationArguments arg0) throws Exception {
      Call.creator(new PhoneNumber("<to-number>"), new PhoneNumber("<from-number>"),
         new URI("http://demo.twilio.com/docs/voice.xml")).create();
   }
}

完全なビルド構成ファイルのコードは次のとおりです-

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>smsdemo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>smsdemo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>com.twilio.sdk</groupId>
         <artifactId>twilio</artifactId>
         <version>7.16.1</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   compile group: "com.twilio.sdk", name:"twilio", version: "7.11.+"
}

次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、次のようにコマンドを使用します-

 mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用します-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

ここで、ここで指定されたコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

これで、Twilioから「to-number」への呼び出しを受信します。

通話に参加した後、任意のキーを押すと、https://demo.twilio.com/docs/voice.xmlから音声メモが聞こえます

-この例では、Trailアカウントを使用しました。 したがって、電話をかける前に番号を確認する必要があります。

スプリングブート-ユニットテストケース

Unit Testing is a one of the testing done by the developers to make sure individual unit or component functionalities are working fine.

このチュートリアルでは、MockitoとWeb Controllerを使用してユニットテストケースを作成する方法を説明します。

モッキート

Mockito MocksをSpring Beanに注入するには、ビルド構成ファイルにMockito-core依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-core</artifactId>
   <version>2.13.0</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
testCompile('org.springframework.boot:spring-boot-starter-test')

String値を返すメソッドを含むServiceクラスを記述するコードは、ここに示されています。

package com.finddevguides.mockitodemo;

import org.springframework.stereotype.Service;

@Service
public class ProductService {
   public String getProductName() {
      return "Honey";
   }
}

次に、示されているように、ProductServiceクラスを別のServiceクラスファイルに挿入します。

package com.finddevguides.mockitodemo;

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

@Service
public class OrderService {
   @Autowired
   ProductService productService;

   public OrderService(ProductService productService) {
      this.productService = productService;
   }
   public String getProductName() {
      return productService.getProductName();
   }
}

メインのSpring Bootアプリケーションクラスファイルは以下のとおりです-

package com.finddevguides.mockitodemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

次に、テストのアプリケーションコンテキストを構成します。 @Profile(“ test”)注釈は、テストケースの実行時にクラスを構成するために使用されます。

package com.finddevguides.mockitodemo;

import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;

@Profile("test")
@Configuration
public class ProductServiceTestConfiguration {
   @Bean
   @Primary
   public ProductService productService() {
      return Mockito.mock(ProductService.class);
   }
}

これで、 src/test/resources パッケージの下に注文サービスの単体テストケースを作成できます。

package com.finddevguides.mockitodemo;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockitoDemoApplicationTests {
   @Autowired
   private OrderService orderService;

   @Autowired
   private ProductService productService;

   @Test
   public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
      Mockito.when(productService.getProductName()).thenReturn("Mock Product Name");
      String testName = orderService.getProductName();
      Assert.assertEquals("Mock Product Name", testName);
   }
}

ビルド構成ファイルの完全なコードを以下に示します。

*Maven – pom.xml*
<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>mockito-demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>mockito-demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.mockito</groupId>
         <artifactId>mockito-core</artifactId>
         <version>2.13.0</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

次のMavenまたはGradle1コマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、次のようにコマンドを使用できます-

mvn clean install

テスト結果はコンソールウィンドウで確認できます。

コンソールウィンドウでのテスト結果

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

残りの結果はコンソールウィンドウで確認できます。

コンソールウィンドウの残りの結果

スプリングブート-レストコントローラーユニットテスト

Spring Boot provides an easy way to write a Unit Test for Rest Controller file. With the help of SpringJUnit4ClassRunner and MockMvc, we can create a web application context to write Unit Test for Rest Controller file.

ユニットテストは src/test/java ディレクトリの下に記述し、テストを記述するクラスパスリソースは src/test/resources ディレクトリの下に配置する必要があります。

単体テストを作成するには、以下に示すように、ビルド構成ファイルにSpring Boot Starter Test依存関係を追加する必要があります。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

testCompile('org.springframework.boot:spring-boot-starter-test')

テストケースを作成する前に、まずRESTful Webサービスを構築する必要があります。 RESTful Webサービスの構築の詳細については、このチュートリアルで与えられているものに関する章を参照してください。

RESTコントローラーの単体テストの作成

このセクションでは、RESTコントローラーの単体テストの作成方法を見てみましょう。

まず、MockMvcを使用してWebアプリケーションコンテキストを作成するために使用する抽象クラスファイルを作成し、mapToJson()およびmapFromJson()メソッドを定義してJavaオブジェクトをJSON文字列に変換し、JSON文字列をJavaオブジェクトに変換する必要があります。

package com.finddevguides.demo;

import java.io.IOException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
@WebAppConfiguration
public abstract class AbstractTest {
   protected MockMvc mvc;
   @Autowired
   WebApplicationContext webApplicationContext;

   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {

      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
}

次に、AbstractTestクラスを拡張するクラスファイルを記述し、GET、POST、PUT、DELETEなどの各メソッドの単体テストを記述します。

GET APIテストケースのコードを以下に示します。 このAPIは、製品のリストを表示するためのものです。

@Test
public void getProductsList() throws Exception {
   String uri = "/products";
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
      .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();

   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   Product[] productlist = super.mapFromJson(content, Product[].class);
   assertTrue(productlist.length > 0);
}

POST APIテストケースのコードを以下に示します。 このAPIは製品を作成するためのものです。

@Test
public void createProduct() throws Exception {
   String uri = "/products";
   Product product = new Product();
   product.setId("3");
   product.setName("Ginger");

   String inputJson = super.mapToJson(product);
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
      .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();

   int status = mvcResult.getResponse().getStatus();
   assertEquals(201, status);
   String content = mvcResult.getResponse().getContentAsString();
   assertEquals(content, "Product is created successfully");
}

PUT APIテストケースのコードを以下に示します。 このAPIは、既存の製品を更新するためのものです。

@Test
public void updateProduct() throws Exception {
   String uri = "/products/2";
   Product product = new Product();
   product.setName("Lemon");

   String inputJson = super.mapToJson(product);
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)
      .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();

   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   assertEquals(content, "Product is updated successsfully");
}

Delete APIテストケースのコードを以下に示します。 このAPIは、既存の製品を削除します。

@Test
public void deleteProduct() throws Exception {
   String uri = "/products/2";
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();
   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   assertEquals(content, "Product is deleted successsfully");
}

完全なコントローラテストクラスファイルは以下のとおりです-

package com.finddevguides.demo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.finddevguides.demo.model.Product;

public class ProductServiceControllerTest extends AbstractTest {
   @Override
   @Before
   public void setUp() {
      super.setUp();
   }
   @Test
   public void getProductsList() throws Exception {
      String uri = "/products";
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
         .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();

      int status = mvcResult.getResponse().getStatus();
      assertEquals(200, status);
      String content = mvcResult.getResponse().getContentAsString();
      Product[] productlist = super.mapFromJson(content, Product[].class);
      assertTrue(productlist.length > 0);
   }
   @Test
   public void createProduct() throws Exception {
      String uri = "/products";
      Product product = new Product();
      product.setId("3");
      product.setName("Ginger");
      String inputJson = super.mapToJson(product);
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
         .contentType(MediaType.APPLICATION_JSON_VALUE)
         .content(inputJson)).andReturn();

      int status = mvcResult.getResponse().getStatus();
      assertEquals(201, status);
      String content = mvcResult.getResponse().getContentAsString();
      assertEquals(content, "Product is created successfully");
   }
   @Test
   public void updateProduct() throws Exception {
      String uri = "/products/2";
      Product product = new Product();
      product.setName("Lemon");
      String inputJson = super.mapToJson(product);
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)
         .contentType(MediaType.APPLICATION_JSON_VALUE)
         .content(inputJson)).andReturn();

      int status = mvcResult.getResponse().getStatus();
      assertEquals(200, status);
      String content = mvcResult.getResponse().getContentAsString();
      assertEquals(content, "Product is updated successsfully");
   }
   @Test
   public void deleteProduct() throws Exception {
      String uri = "/products/2";
      MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();
      int status = mvcResult.getResponse().getStatus();
      assertEquals(200, status);
      String content = mvcResult.getResponse().getContentAsString();
      assertEquals(content, "Product is deleted successsfully");
   }
}

あなたは、実行可能なJARファイルを作成し、以下に示すMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行することができます-

Mavenの場合、以下に示すコマンドを使用できます-

mvn clean install

これで、コンソールウィンドウにテスト結果を表示できます。

コンソールウィンドウでのテスト結果

Gradleの場合、以下に示すようにコマンドを使用できます-

gradle clean build

以下に示すように、コンソールウィンドウで残りの結果を確認できます。

コンソールウィンドウの残りの結果

Spring Boot-データベース処理

Spring Bootは、データベースのDataSourceを作成するための非常に優れたサポートを提供します。 Spring BootでDataSourceを作成するために追加のコードを記述する必要はありません。 依存関係を追加し、構成の詳細を実行するだけで、DataSourceを作成してデータベースに接続できます。

この章では、Spring Boot JDBCドライバー接続を使用してデータベースに接続します。

まず、ビルド構成ファイルにSpring Boot Starter JDBC依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile('org.springframework.boot:spring-boot-starter-jdbc')

H2データベースに接続する

H2データベースに接続するには、ビルド構成ファイルにH2データベースの依存関係を追加する必要があります。

Mavenユーザーの場合、pom.xmlファイルに以下の依存関係を追加します。

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
</dependency>

Gradleユーザーの場合、build.gradleファイルに以下の依存関係を追加します。

compile('com.h2database:h2')

H2データベースに接続するには、classpath src/main/resourcesディレクトリの下にschema.sqlファイルとdata.sqlファイルを作成する必要があります。

schema.sqlファイルを以下に示します。

CREATE TABLE PRODUCT (ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(25));

data.sqlファイルを以下に示します。

INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (1,'Honey');
INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (2,'Almond');

MySQLを接続する

MySQLデータベースに接続するには、MySQL依存関係をビルド構成ファイルに追加する必要があります。

Mavenユーザーの場合、pom.xmlファイルに次の依存関係を追加します。

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
</dependency>

Gradleユーザーの場合、build.gradleファイルに次の依存関係を追加します。

compile('mysql:mysql-connector-java')

次に、示されているようにMySQLでデータベースとテーブルを作成します-

MySQLのデータベースとテーブル

プロパティファイルユーザーの場合、application.propertiesファイルに次のプロパティを追加します。

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testOnBorrow = true
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.minEvictableIdleTimeMillis = 30000
spring.datasource.validationQuery = SELECT 1
spring.datasource.max-active = 15
spring.datasource.max-idle = 10
spring.datasource.max-wait = 8000

YAMLユーザーの場合、application.ymlファイルに次のプロパティを追加します。

spring:
   datasource:
      driverClassName: com.mysql.jdbc.Driver
      url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true"
      username: "root"
      password: "root"
      testOnBorrow: true
      testWhileIdle: true
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 30000
      validationQuery: SELECT 1
      max-active: 15
      max-idle: 10
      max-wait: 8000

Redisを接続する

Redisは、メモリ内のデータ構造を格納するために使用されるオープンソースデータベースです。 Spring BootアプリケーションでRedisデータベースに接続するには、ビルド構成ファイルにRedis依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加する必要があります。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加する必要があります。

compile('org.springframework.boot:spring-boot-starter-data-redis')

Redis接続の場合、RedisTemplateを使用する必要があります。 RedisTemplateの場合、JedisConnectionFactoryの詳細を提供する必要があります。

@Bean
JedisConnectionFactory jedisConnectionFactory() {
   JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();
   jedisConFactory.setHostName("localhost");
   jedisConFactory.setPort(6000);
   jedisConFactory.setUsePool(true);
   return jedisConFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
   RedisTemplate<String, Object> template = new RedisTemplate<>();
   template.setConnectionFactory(jedisConnectionFactory());
   template.setKeySerializer(new StringRedisSerializer());
   template.setHashKeySerializer(new StringRedisSerializer());
   template.setHashValueSerializer(new StringRedisSerializer());
   template.setValueSerializer(new StringRedisSerializer());
   return template;
}

RedisTemplateクラスを自動配線し、Redisデータベースのデータにアクセスします。

@Autowired

RedisTemplate<String, Object> redis;
Map<Object,Object> datalist = redis.opsForHash().entries(“Redis_code_index_key”);

JDBCTemplate

Spring BootアプリケーションでJdbcTemplateを使用してリレーショナルデータベースにアクセスするには、Spring Boot Starter JDBC依存関係をビルド構成ファイルに追加する必要があります。

次に、JdbcTemplateクラスを@Autowiredした場合、Spring Bootは自動的にデータベースに接続し、JdbcTemplateオブジェクトのデータソースを設定します。

@Autowired
JdbcTemplate jdbcTemplate;
Collection<Map<String, Object>> rows = jdbc.queryForList("SELECT QUERY");

@Repositoryアノテーションをクラスファイルに追加する必要があります。 @Repositoryアノテーションは、Spring Bootアプリケーションのデータベースリポジトリを作成するために使用されます。

@Repository
public class ProductServiceDAO {
}

複数のデータソース

1つのSpring Bootアプリケーションに「n」個のデータソースを保持できます。 ここに示す例は、Spring Bootアプリケーションで複数のデータソースを作成する方法を示しています。 次に、アプリケーションプロパティファイルに2つのデータソース構成の詳細を追加します。

プロパティファイルユーザーの場合、次のプロパティをapplication.propertiesファイルに追加します。

spring.dbProductService.driverClassName = com.mysql.jdbc.Driver
spring.dbProductService.url = jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect = true
spring.dbProductService.username = root
spring.dbProductService.password = root
spring.dbProductService.testOnBorrow = true
spring.dbProductService.testWhileIdle = true
spring.dbProductService.timeBetweenEvictionRunsMillis = 60000
spring.dbProductService.minEvictableIdleTimeMillis = 30000
spring.dbProductService.validationQuery = SELECT 1
spring.dbProductService.max-active = 15
spring.dbProductService.max-idle = 10
spring.dbProductService.max-wait = 8000

spring.dbUserService.driverClassName = com.mysql.jdbc.Driver
spring.dbUserService.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect = true
spring.dbUserService.username = root
spring.dbUserService.password = root
spring.dbUserService.testOnBorrow = true
spring.dbUserService.testWhileIdle = true
spring.dbUserService.timeBetweenEvictionRunsMillis = 60000
spring.dbUserService.minEvictableIdleTimeMillis = 30000
spring.dbUserService.validationQuery = SELECT 1
spring.dbUserService.max-active = 15
spring.dbUserService.max-idle = 10
spring.dbUserService.max-wait = 8000

Yamlユーザーは、application.ymlファイルに次のプロパティを追加する必要があります。

spring:
   dbProductService:
      driverClassName: com.mysql.jdbc.Driver
      url: "jdbc:mysql://localhost:3306/PRODUCTSERVICE?autoreconnect=true"
      password: "root"
      username: "root"
      testOnBorrow: true
      testWhileIdle: true
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 30000
      validationQuery: SELECT 1
      max-active: 15
      max-idle: 10
      max-wait: 8000
   dbUserService:
      driverClassName: com.mysql.jdbc.Driver
      url: "jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true"
      password: "root"
      username: "root"
      testOnBorrow: true
      testWhileIdle: true
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 30000
      validationQuery: SELECT 1
      max-active: 15
      max-idle: 10
      max-wait: 8000

次に、Configurationクラスを作成して、複数のデータソースのDataSourceとJdbcTemplateを作成します。

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DatabaseConfig {
   @Bean(name = "dbProductService")
   @ConfigurationProperties(prefix = "spring.dbProductService")
   @Primary
   public DataSource createProductServiceDataSource() {
      return DataSourceBuilder.create().build();
   }
   @Bean(name = "dbUserService")
   @ConfigurationProperties(prefix = "spring.dbUserService")
   public DataSource createUserServiceDataSource() {
      return DataSourceBuilder.create().build();
   }
   @Bean(name = "jdbcProductService")
   @Autowired
   public JdbcTemplate createJdbcTemplate_ProductService(@Qualifier("dbProductService") DataSource productServiceDS) {
      return new JdbcTemplate(productServiceDS);
   }
   @Bean(name = "jdbcUserService")
   @Autowired
   public JdbcTemplate createJdbcTemplate_UserService(@Qualifier("dbUserService") DataSource userServiceDS) {
      return new JdbcTemplate(userServiceDS);
   }
}

次に、@ Qualifierアノテーションを使用してJDBCTemplateオブジェクトを自動配線します。

@Qualifier("jdbcProductService")
@Autowired
JdbcTemplate jdbcTemplate;

@Qualifier("jdbcUserService")
@Autowired
JdbcTemplate jdbcTemplate;

Spring Boot-Webアプリケーションの保護

If a Spring Boot Security dependency is added on the classpath, Spring Boot application automatically requires the Basic Authentication for all HTTP Endpoints. The Endpoint “/” and “/home” does not require any authentication. All other Endpoints require authentication.

Spring BootアプリケーションにSpring Boot Securityを追加するには、ビルド構成ファイルにSpring Boot Starter Security依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile("org.springframework.boot:spring-boot-starter-security")

Webアプリケーションの保護

まず、Thymeleafテンプレートを使用して、安全でないWebアプリケーションを作成します。

次に、 src/main/resources/templates ディレクトリの下にhomelファイルを作成します。

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:th = "http://www.thymeleaf.org"
   xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

   <head>
      <title>Spring Security Example</title>
   </head>
   <body>
      <h1>Welcome!</h1>
      <p>Click <a th:href = "@{/hello}">here</a> to see a greeting.</p>
   </body>

</html>

Thymeleafテンプレートを使用してHTMLファイルで定義された単純なビュー /hello

次に、 src/main/resources/templates ディレクトリの下にhellolを作成します。

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
   xmlns:th = "http://www.thymeleaf.org"
   xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

   <head>
      <title>Hello World!</title>
   </head>
   <body>
      <h1>Hello world!</h1>
   </body>

</html>

次に、Spring MVC – HomeビューとHelloビューのViewコントローラーをセットアップする必要があります。

このために、WebMvcConfigurerAdapterを拡張するMVC構成ファイルを作成します。

package com.finddevguides.websecuritydemo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/home").setViewName("home");
      registry.addViewController("/").setViewName("home");
      registry.addViewController("/hello").setViewName("hello");
      registry.addViewController("/login").setViewName("login");
   }
}

次に、Spring Boot Starterのセキュリティ依存関係をビルド構成ファイルに追加します。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile("org.springframework.boot:spring-boot-starter-security")

次に、基本認証を使用してHTTPエンドポイントにアクセスするようにアプリケーションを保護するために使用されるWebセキュリティ構成ファイルを作成します。

package com.finddevguides.websecuritydemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http
         .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
            .and()
         .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
   }
   @Autowired
   public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth
         .inMemoryAuthentication()
         .withUser("user").password("password").roles("USER");
   }
}

次に、 src/main/resources ディレクトリの下にloginlファイルを作成して、ユーザーがログイン画面からHTTPエンドポイントにアクセスできるようにします。

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org"
   xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

   <head>
      <title>Spring Security Example </title>
   </head>
   <body>
      <div th:if = "${param.error}">
         Invalid username and password.
      </div>
      <div th:if = "${param.logout}">
         You have been logged out.
      </div>

      <form th:action = "@{/login}" method = "post">
         <div>
            <label> User Name : <input type = "text" name = "username"/> </label>
         </div>
         <div>
            <label> Password: <input type = "password" name = "password"/> </label>
         </div>
         <div>
            <input type = "submit" value = "Sign In"/>
         </div>
      </form>

   </body>
</html>

最後に、hellolファイルを更新します。ユーザーがアプリケーションからサインアウトして、以下に示すように現在のユーザー名を表示できるようにします-

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org"
   xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

   <head>
      <title>Hello World!</title>
   </head>
   <body>
      <h1 th:inline = "text">Hello [[httpServletRequest.remoteUser}]]!</h1>
      <form th:action = "@{/logout}" method = "post">
         <input type = "submit" value = "Sign Out"/>
      </form>
   </body>

</html>

メインのSpring Bootアプリケーションのコードは以下のとおりです-

package com.finddevguides.websecuritydemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

ビルド構成ファイルの完全なコードを以下に示します。

*Maven – pom.xml*
<?xml version  =  "1.0" encoding  =  "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>websecurity-demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>websecurity-demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>

      <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>

      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-security')
   compile('org.springframework.boot:spring-boot-starter-thymeleaf')
   compile('org.springframework.boot:spring-boot-starter-web')

   testCompile('org.springframework.boot:spring-boot-starter-test')
   testCompile('org.springframework.security:spring-security-test')
}

ここで、実行可能なJARファイルを作成し、次のMavenまたはGradleコマンドを使用してSpring Bootアプリケーションを実行します。

Mavenユーザーは以下のコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleユーザーは次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

次に、以下に示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

WebブラウザでURL http://localhost:8080/ にアクセスします。 次のように出力を確認できます。

Webブラウザーのリンクをクリックして出力

ログインページの出力

出力サインアウトページ

ログアウトした出力

無効なユーザー名パスワード

Spring Boot-JWTを使用したOAuth2

この章では、Spring Boot SecurityメカニズムとJWTを使用したOAuth2について詳しく学習します。

認可サーバー

承認サーバーは、Web APIセキュリティの最高のアーキテクチャコンポーネントです。 承認サーバーは、アプリとHTTPエンドポイントがアプリケーションの機能を識別できるようにする集中認証ポイントとして機能します。

リソースサーバー

リソースサーバーは、クライアントにアクセストークンを提供して、リソースサーバーのHTTPエンドポイントにアクセスするアプリケーションです。 HTTPエンドポイント、静的リソース、および動的Webページを含むライブラリのコレクションです。

OAuth2

OAuth2は、アプリケーションWebセキュリティがクライアントからリソースにアクセスできるようにする承認フレームワークです。 OAuth2アプリケーションを構築するには、許可タイプ(認証コード)、クライアントID、およびクライアントシークレットに焦点を合わせる必要があります。

JWTトークン

JWTトークンはJSON Webトークンであり、2者間で保護されたクレームを表すために使用されます。 JWTトークンについて詳しくは、https://jwt.io/[www.jwt.io/]をご覧ください。

次に、JWTトークンを使用して、承認サーバー、リソースサーバーの使用を可能にするOAuth2アプリケーションを構築します。

以下の手順を使用して、データベースにアクセスすることにより、JWTトークンでSpring Boot Securityを実装できます。

まず、ビルド構成ファイルに次の依存関係を追加する必要があります。

Mavenユーザーは、pom.xmlファイルに次の依存関係を追加できます。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.security.oauth</groupId>
   <artifactId>spring-security-oauth2</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-jwt</artifactId>
</dependency>

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-test</artifactId>
   <scope>test</scope>
</dependency>

Gradleユーザーは、build.gradleファイルに次の依存関係を追加できます。

compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.security:spring-security-test')

compile("org.springframework.security.oauth:spring-security-oauth2")
compile('org.springframework.security:spring-security-jwt')
compile("org.springframework.boot:spring-boot-starter-jdbc")
compile("com.h2database:h2:1.4.191")

どこで、

  • Spring Boot Starter Security -Spring Securityを実装します
  • Spring Security OAuth2 -OAUTH2構造を実装して、承認サーバーとリソースサーバーを有効にします。
  • Spring Security JWT -Webセキュリティ用のJWTトークンを生成
  • Spring Boot Starter JDBC -データベースにアクセスして、ユーザーが利用可能かどうかを確認します。
  • Spring Boot Starter Web -HTTPエンドポイントを書き込みます。
  • * H2データベース*-認証および承認のためのユーザー情報を保存します。

完全なビルド構成ファイルを以下に示します。

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>websecurityapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>websecurityapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-jdbc</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.security.oauth</groupId>
         <artifactId>spring-security-oauth2</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-jwt</artifactId>
      </dependency>

      <dependency>
         <groupId>com.h2database</groupId>
         <artifactId>h2</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>
*Gradle – build.gradle*
buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}

dependencies {
   compile('org.springframework.boot:spring-boot-starter-security')
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   testCompile('org.springframework.security:spring-security-test')
   compile("org.springframework.security.oauth:spring-security-oauth2")
   compile('org.springframework.security:spring-security-jwt')
   compile("org.springframework.boot:spring-boot-starter-jdbc")
   compile("com.h2database:h2:1.4.191")
}

次に、メインのSpring Bootアプリケーションで、@ EnableAuthorizationServerアノテーションと@EnableResourceServerアノテーションを追加して、同じアプリケーションで認証サーバーとリソースサーバーとして機能するようにします。

また、次のコードを使用して単純なHTTPエンドポイントを記述し、JWTトークンを使用してSpring SecurityでAPIにアクセスできます。

package com.finddevguides.websecurityapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableAuthorizationServer
@EnableResourceServer
@RestController
public class WebsecurityappApplication {
   public static void main(String[] args) {
      SpringApplication.run(WebsecurityappApplication.class, args);
   }
   @RequestMapping(value = "/products")
   public String getProductName() {
      return "Honey";
   }
}

次のコードを使用して、認証用のユーザー情報を保存するPOJOクラスを定義します。

package com.finddevguides.websecurityapp;

import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;

public class UserEntity {
   private String username;
   private String password;
   private Collection<GrantedAuthority> grantedAuthoritiesList = new ArrayList<>();

   public String getPassword() {
      return password;
   }
   public void setPassword(String password) {
      this.password = password;
   }
   public Collection<GrantedAuthority> getGrantedAuthoritiesList() {
      return grantedAuthoritiesList;
   }
   public void setGrantedAuthoritiesList(Collection<GrantedAuthority> grantedAuthoritiesList) {
      this.grantedAuthoritiesList = grantedAuthoritiesList;
   }
   public String getUsername() {
      return username;
   }
   public void setUsername(String username) {
      this.username = username;
   }
}

ここで、次のコードを使用して、Spring Boot認証用にorg.springframework.security.core.userdetails.Userクラスを拡張するCustomUserクラスを定義します。

package com.finddevguides.websecurityapp;

import org.springframework.security.core.userdetails.User;

public class CustomUser extends User {
   private static final long serialVersionUID = 1L;
   public CustomUser(UserEntity user) {
      super(user.getUsername(), user.getPassword(), user.getGrantedAuthoritiesList());
   }
}

@Repositoryクラスを作成して、データベースからユーザー情報を読み取り、それをカスタムユーザーサービスに送信し、付与された権限「ROLE_SYSTEMADMIN」を追加することもできます。

package com.finddevguides.websecurityapp;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Repository;

@Repository
public class OAuthDao {
   @Autowired
   private JdbcTemplate jdbcTemplate;

   public UserEntity getUserDetails(String username) {
      Collection<GrantedAuthority> grantedAuthoritiesList = new ArrayList<>();
      String userSQLQuery = "SELECT * FROM USERS WHERE USERNAME=?";
      List<UserEntity> list = jdbcTemplate.query(userSQLQuery, new String[] { username },
         (ResultSet rs, int rowNum) -> {

         UserEntity user = new UserEntity();
         user.setUsername(username);
         user.setPassword(rs.getString("PASSWORD"));
         return user;
      });
      if (list.size() > 0) {
         GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_SYSTEMADMIN");
         grantedAuthoritiesList.add(grantedAuthority);
         list.get(0).setGrantedAuthoritiesList(grantedAuthoritiesList);
         return list.get(0);
      }
      return null;
   }
}

org.springframework.security.core.userdetails.UserDetailsS​​erviceを拡張するカスタムユーザー詳細サービスクラスを作成して、図のようにDAOリポジトリクラスを呼び出すことができます。

package com.finddevguides.websecurityapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomDetailsService implements UserDetailsService {
   @Autowired
   OAuthDao oauthDao;

   @Override
   public CustomUser loadUserByUsername(final String username) throws UsernameNotFoundException {
      UserEntity userEntity = null;
      try {
         userEntity = oauthDao.getUserDetails(username);
         CustomUser customUser = new CustomUser(userEntity);
         return customUser;
      } catch (Exception e) {
         e.printStackTrace();
         throw new UsernameNotFoundException("User " + username + " was not found in the database");
      }
   }
}

次に、@ securityクラスを作成してWebセキュリティを有効にし、パスワードエンコーダー(BCryptPasswordEncoder)を定義し、AuthenticationManager Beanを定義します。 セキュリティ構成クラスは、WebSecurityConfigurerAdapterクラスを拡張する必要があります。

package com.finddevguides.websecurityapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
   @Autowired
   private CustomDetailsService customDetailsService;

   @Bean
   public PasswordEncoder encoder() {
      return new BCryptPasswordEncoder();
   }
   @Override
   @Autowired
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(customDetailsService).passwordEncoder(encoder());
   }
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests().anyRequest().authenticated().and().sessionManagement()
         .sessionCreationPolicy(SessionCreationPolicy.NEVER);
   }
   @Override
   public void configure(WebSecurity web) throws Exception {
      web.ignoring();
   }
   @Override
   @Bean
   public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
   }
}

ここで、OAuth2構成クラスを定義して、クライアントID、クライアントシークレットを追加し、トークン署名者キーと検証者キーのJwtAccessTokenConverter、秘密キーと公開キーを定義し、スコープでトークンの有効性のClientDetailsS​​erviceConfigurerを構成します。

package com.finddevguides.websecurityapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
   private String clientid = "finddevguides";
   private String clientSecret = "my-secret-key";
   private String privateKey = "private key";
   private String publicKey = "public key";

   @Autowired
   @Qualifier("authenticationManagerBean")
   private AuthenticationManager authenticationManager;

   @Bean
   public JwtAccessTokenConverter tokenEnhancer() {
      JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
      converter.setSigningKey(privateKey);
      converter.setVerifierKey(publicKey);
      return converter;
   }
   @Bean
   public JwtTokenStore tokenStore() {
      return new JwtTokenStore(tokenEnhancer());
   }
   @Override
   public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore())
      .accessTokenConverter(tokenEnhancer());
   }
   @Override
   public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
      security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
   }
   @Override
   public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients.inMemory().withClient(clientid).secret(clientSecret).scopes("read", "write")
         .authorizedGrantTypes("password", "refresh_token").accessTokenValiditySeconds(20000)
         .refreshTokenValiditySeconds(20000);

   }
}

次に、opensslを使用して秘密鍵と公開鍵を作成します。

秘密鍵を生成するには、次のコマンドを使用できます。

openssl genrsa -out jwt.pem 2048
openssl rsa -in jwt.pem

使用できます公開鍵の生成には、以下のコマンドを使用します。

openssl rsa -in jwt.pem -pubout

1.5以降のSpring Bootのバージョンでは、application.propertiesファイルに以下のプロパティを追加して、OAuth2リソースフィルターの順序を定義します。

security.oauth2.resource.filter-order=3

YAMLファイルのユーザーは、YAMLファイルに以下のプロパティを追加できます。

security:
   oauth2:
      resource:
         filter-order: 3

次に、クラスパスリソース src/main/resources/directory の下にschema.sqlおよびdata.sqlファイルを作成して、アプリケーションをH2データベースに接続します。

schema.sqlファイルは次のとおりです-

CREATE TABLE USERS (ID INT PRIMARY KEY, USERNAME VARCHAR(45), PASSWORD VARCHAR(60));

data.sqlファイルは次のとおりです-

INSERT INTO USERS (ID, USERNAME,PASSWORD) VALUES (
   1, '[email protected]','$2a$08$fL7u5xcvsZl78su29x1ti.dxI.9rYO8t0q5wk2ROJ.1cdR53bmaVG');

INSERT INTO USERS (ID, USERNAME,PASSWORD) VALUES (
   2, '[email protected]','$2a$08$fL7u5xcvsZl78su29x1ti.dxI.9rYO8t0q5wk2ROJ.1cdR53bmaVG');

注意-パスワードは、データベーステーブルにBcrypt Encoderの形式で保存する必要があります。

次のMavenまたはGradleコマンドを使用して、実行可能JARファイルを作成し、Spring Bootアプリケーションを実行できます。

Mavenの場合、以下に示すコマンドを使用できます-

mvn clean install

「BUILD SUCCESS」の後、ターゲットディレクトリの下にJARファイルがあります。

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

さて、ここに示すコマンドを使用してJARファイルを実行します-

java –jar <JARFILE>

アプリケーションはTomcatポート8080で開始されます。

Tomcatポート8080アプリケーション出力

次に、POSTMANを介してPOSTメソッドのURLを押して、OAUTH2トークンを取得します。

*http://localhost:8080/oauth/token*

今、次のようにリクエストヘッダーを追加します-

  • 許可-クライアントIDとクライアントシークレットを使用した基本認証。
  • コンテンツタイプ-application/x-www-form-urlencoded

リクエストヘッダーの追加

今、次のようにリクエストパラメータを追加します-

  • grant_type =パスワード
  • ユーザー名=ユーザー名
  • パスワード=パスワード

リクエストパラメーターの追加

今、APIをヒットし、示されているようにaccess_tokenを取得します-

アクセストークンを取得

次に、示されているように、要求ヘッダーにベアラーアクセストークンを使用してリソースサーバーAPIをヒットします。

ベアラーアクセストークンを使用したリソースサーバーAPI

次に、以下に示すように出力を見ることができます-

JWT出力付きOAuth2

Spring Boot-Google Cloud Platform

Google Cloud Platformは、クラウド環境でSpring Bootアプリケーションを実行するクラウドコンピューティングサービスを提供します。 この章では、GCPアプリエンジンプラットフォームにSpring Bootアプリケーションを展開する方法を説明します。

まず、Spring Initializerページhttps://start.spring.io/[www.start.spring.io]からGradleビルドSpring Bootアプリケーションをダウンロードします。 次のスクリーンショットを確認してください。

春の初期化ページ

次に、build.gradleファイルで、Google Cloud appengineプラグインとappengineクラスパスの依存関係を追加します。

build.gradleファイルのコードは次のとおりです-

buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
      classpath 'com.google.cloud.tools:appengine-gradle-plugin:1.3.3'
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'com.google.cloud.tools.appengine'

group = 'com.finddevguides'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

今、簡単なHTTPエンドポイントを書くと、それは示されているように文字列の成功を返します-

package com.finddevguides.appenginedemo;

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

@SpringBootApplication
@RestController
public class AppengineDemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(AppengineDemoApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String success() {
      return "APP Engine deployment success";
   }
}

次に、示されているようにsrc/main/appengineディレクトリの下にapp.ymlファイルを追加します-

runtime: java
env: flex

handlers:
- url:/.*
   script: this field is required, but ignored

次に、Google Cloudコンソールに移動し、ページ上部の[Googleクラウドのアクティブ化]シェルをクリックします。

Google Cloud Shellをアクティブ化

次に、Googleクラウドシェルを使用して、ソースファイルとGradleファイルをGoogleクラウドマシンのホームディレクトリに移動します。

Google Cloud Shellを使用してホームディレクトリに移動

ここで、コマンドgradle appengineDeployを実行すると、アプリケーションがGoogle Cloud appengineにデプロイされます。

-GCPは課金を有効にして、アプリケーションをappengineにデプロイする前に、GCPでappengineプラットフォームを作成する必要があります。

アプリケーションをGCP appengineプラットフォームにデプロイするには数分かかります。

ビルドが成功すると、コンソールウィンドウにサービスURLが表示されます。

春の初期化ページ

ここで、サービスURLにアクセスして、出力を確認します。

App Engine開発の成功

Google Cloud SQL

Google Cloud SQLをSpring Bootアプリケーションに接続するには、application.propertiesファイルに次のプロパティを追加する必要があります。

JDBC URL形式

jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance = <GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password = <PASSWORD>

-Spring BootアプリケーションとGoogle Cloud SQLは同じGCPプロジェクトにある必要があります。

application.propertiesファイルを以下に示します。

spring.dbProductService.driverClassName = com.mysql.jdbc.Driver
spring.dbProductService.url = jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance = springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = root&password = rootspring.dbProductService.username = root

spring.dbProductService.password = root
spring.dbProductService.testOnBorrow = true
spring.dbProductService.testWhileIdle = true
spring.dbProductService.timeBetweenEvictionRunsMillis = 60000
spring.dbProductService.minEvictableIdleTimeMillis = 30000
spring.dbProductService.validationQuery = SELECT 1
spring.dbProductService.max-active = 15
spring.dbProductService.max-idle = 10
spring.dbProductService.max-wait = 8000

YAMLファイルユーザーは、application.ymlファイルに以下のプロパティを追加できます。

spring:
   datasource:
      driverClassName: com.mysql.jdbc.Driver
      url: "jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance=springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=root&password=root"
      password: "root"
      username: "root"
      testOnBorrow: true
      testWhileIdle: true
      validationQuery: SELECT 1

      max-active: 15
      max-idle: 10
      max-wait: 8000

Spring Boot-Google OAuth2サインイン

この章では、Spring BootアプリケーションとGradleビルドを使用して、Google OAuth2サインインを追加する方法を説明します。

最初に、Spring Boot OAuth2セキュリティ依存関係をビルド構成ファイルに追加します。ビルド構成ファイルは以下のとおりです。

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides.projects'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   compile('org.springframework.security.oauth:spring-security-oauth2')
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

次に、HTTPエンドポイントを追加して、以下に示すようにメインのSpring BootアプリケーションクラスファイルでSpring Bootを介して認証した後、Googleからユーザープリンシパルを読み取ります

package com.finddevguides.projects.googleservice;

import java.security.Principal;

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

@SpringBootApplication
@RestController
public class GoogleserviceApplication {
   public static void main(String[] args) {
      SpringApplication.run(GoogleserviceApplication.class, args);
   }
   @RequestMapping(value = "/user")
   public Principal user(Principal principal) {
      return principal;
   }
}

次に、構成ファイルを作成して、Webセキュリティ用にOAuth2SSOを有効にし、次のようにindexlファイルの認証を削除します-

package com.finddevguides.projects.googleservice;

import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableOAuth2Sso
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http
         .csrf()
         .disable()
         .antMatcher("/**")
         .authorizeRequests()
         .antMatchers("/", "/indexl")
         .permitAll()
         .anyRequest()
         .authenticated();
   }
}

次に、静的リソースの下にindexlファイルを追加し、ユーザーHTTPエンドポイントにリダイレクトするリンクを追加して、以下に示すようにGoogleユーザープリンシパルを読み取ります-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <a href = "user">Click here to Google Login</a>
   </body>
</html>

-Google Cloudコンソールで-Gmailサービス、分析サービス、およびGoogle+サービスAPIを有効にします。

次に、資格情報セクションに移動して資格情報を作成し、OAuthクライアントIDを選択します。

認証情報セクション

次に、OAuth2同意画面で製品名を入力します。

OAuth2同意画面の製品名

次に、「Webアプリケーション」としてアプリケーションタイプを選択し、承認済みのJavaScriptオリジンと承認済みリダイレクトURIを指定します。

承認済みリダイレクトURI

これで、OAuth2クライアントIDとクライアントシークレットが作成されました。

作成されたOAuth2クライアントID

次に、アプリケーションプロパティファイルにクライアントIDとクライアントシークレットを追加します。

security.oauth2.client.clientId = <CLIENT_ID>
security.oauth2.client.clientSecret = <CLIENT_SECRET>
security.oauth2.client.accessTokenUri  =  https://www.googleapis.com/oauth2/v3/token
security.oauth2.client.userAuthorizationUri  =  https://accounts.google.com/o/oauth2/auth
security.oauth2.client.tokenName = oauth_token
security.oauth2.client.authenticationScheme = query
security.oauth2.client.clientAuthenticationScheme = form
security.oauth2.client.scope = profile email

security.oauth2.resource.userInfoUri  =  https://www.googleapis.com/userinfo/v2/me
security.oauth2.resource.preferTokenInfo = false

これで、実行可能なJARファイルを作成し、次のGradleコマンドを使用してSpring Bootアプリケーションを実行できます。

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

コマンドjava –jar <JARFILE>を使用してJARファイルを実行すると、アプリケーションがTomcatポート8080で開始されます。

次に、URL http://localhost:8080/ にアクセスして、Google Loginリンクをクリックします。

Googleログインリンク

Googleログイン画面にリダイレクトされ、Gmailログインの詳細が提供されます。

Googleログイン画面

ログインに成功すると、Gmailユーザーのプリンシパルオブジェクトを受け取ります。

Gmailユーザーの主要オブジェクト