Spring Boot 简明教程

Spring Boot - Quick Guide

Spring Boot - Introduction

Spring Boot 是一个用于创建微服务的开源 Java 框架。它由 Pivotal Team 开发,用于构建独立且可用于生产的 Spring 应用程序。本章将为您介绍 Spring Boot,并帮助您熟悉它的基本概念。

Spring Boot is an open source Java-based framework used to create a micro Service. It is developed by Pivotal Team and is used to build stand-alone and production ready spring applications. This chapter will give you an introduction to Spring Boot and familiarizes you with its basic concepts.

What is Micro Service?

微服务是一种允许开发人员独立开发和部署服务的架构。每个正在运行的服务都有自己的进程,并且实现了轻量级模型以支持业务应用程序。

Micro Service is an architecture that allows the developers to develop and deploy services independently. Each service running has its own process and this achieves the lightweight model to support business applications.

Advantages

微服务为其开发人员提供了以下优势−

Micro services offers the following advantages to its developers −

  1. Easy deployment

  2. Simple scalability

  3. Compatible with Containers

  4. Minimum configuration

  5. Lesser production time

What is Spring Boot?

Spring Boot 为 Java 开发人员提供了一个非常好的平台,用于开发您可以在 just run 的独立而且可用于生产的 Spring 应用程序。您可以在无需进行整个 Spring 配置设置的情况下开始使用最低配置。

Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run. You can get started with minimum configurations without the need for an entire Spring configuration setup.

Advantages

Spring Boot为其开发人员提供了以下优势−

Spring Boot offers the following advantages to its developers −

  1. Easy to understand and develop spring applications

  2. Increases productivity

  3. Reduces the development time

Goals

Spring Boot 基于以下目标设计−

Spring Boot is designed with the following goals −

  1. To avoid complex XML configuration in Spring

  2. To develop a production ready Spring applications in an easier way

  3. To reduce the development time and run the application independently

  4. Offer an easier way of getting started with the application

Why Spring Boot?

您可以根据这里提供的特性和优势选择 Spring Boot−

You can choose Spring Boot because of the features and benefits it offers as given here −

  1. It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions.

  2. It provides a powerful batch processing and manages REST endpoints.

  3. In Spring Boot, everything is auto configured; no manual configurations are needed.

  4. It offers annotation-based spring application

  5. Eases dependency management

  6. It includes Embedded Servlet Container

How does it work?

Spring Boot 根据您使用 @EnableAutoConfiguration 注释添加到项目的依赖项自动配置您的应用程序。例如,如果 MySQL 数据库在您的类路径中,但是您还未配置任何数据库连接,那么 Spring Boot 会自动配置一个内存数据库。

Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database.

Spring 引导应用程序的入口点是包含 @SpringBootApplication 注解和主方法的类。

The entry point of the spring boot application is the class contains @SpringBootApplication annotation and the main method.

Spring 引导使用 @ComponentScan 注解自动扫描项目中包含的所有组件。

Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation.

Spring Boot Starters

处理依赖管理对于大型项目而言是一项艰巨的任务。Spring Boot 通过为开发者提供一组依赖项来解决这个问题。

Handling dependency management is a difficult task for big projects. Spring Boot resolves this problem by providing a set of dependencies for developers convenience.

例如,如果您想使用 Spring 和 JPA 访问数据库,那么只需要在项目中包含 spring-boot-starter-data-jpa 依赖项就足够了。

For example, if you want to use Spring and JPA for database access, it is sufficient if you include spring-boot-starter-data-jpa dependency in your project.

请注意,所有 Spring 引导启动器都遵循相同的命名模式 spring-boot-starter- *,其中 * 表示它是应用程序的类型。

Note that all Spring Boot starters follow the same naming pattern spring-boot-starter- *, where * indicates that it is a type of the application.

Examples

查看下面解释的以下 Spring 引导启动器以更好地理解 −

Look at the following Spring Boot starters explained below for a better understanding −

Spring Boot Starter Actuator dependency 用于监控和管理您的应用程序。其代码如下所示 −

Spring Boot Starter Actuator dependency is used to monitor and manage your application. Its code is shown below −

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

Spring Boot Starter Security dependency 用于 Spring Security。其代码如下所示 −

Spring Boot Starter Security dependency is used for Spring Security. Its code is shown below −

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

Spring Boot Starter web dependency 用于编写 REST 端点。其代码如下所示 −

Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code is shown below −

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

Spring Boot Starter Thyme Leaf dependency 用于创建 Web 应用程序。其代码如下所示 −

Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its code is shown below −

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

Spring Boot Starter Test dependency 用于编写测试用例。其代码如下所示 −

Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown below −

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

Auto Configuration

Spring Boot 自动配置会根据您在项目中添加的 JAR 依赖项自动配置您的 Spring 应用程序。例如,如果 MySQL 数据库在您的类路径中,但您尚未配置任何数据库连接,那么 Spring Boot 会自动配置内存数据库。

Spring Boot Auto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if MySQL database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database.

为此,您需要向您的主类文件添加 @EnableAutoConfiguration 注解或 @SpringBootApplication 注解。然后,您的 Spring 引导应用程序将被自动配置。

For this purpose, you need to add @EnableAutoConfiguration annotation or @SpringBootApplication annotation to your main class file. Then, your Spring Boot application will be automatically configured.

观察以下代码以更好地理解 −

Observe the following code for a better understanding −

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 Application

Spring 引导应用程序的入口点是包含 @SpringBootApplication 注解的类。此类应具有运行 Spring 引导应用程序的主方法。 @SpringBootApplication 注解包括自动配置、组件扫描和 Spring 引导配置。

The entry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration.

如果您向类中添加 @SpringBootApplication 注解,则无需添加 @EnableAutoConfiguration, @ComponentScan@SpringBootConfiguration 注解。 @SpringBootApplication 注解包含所有其他注解。

If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplication annotation includes all other annotations.

观察以下代码以更好地理解 −

Observe the following code for a better understanding −

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);
   }
}

Component Scan

当应用程序初始化时,Spring 引导应用程序扫描所有 Bean 和包声明。您需要为此类文件添加 @ComponentScan 注解以扫描项目中添加的组件。

Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added in your project.

观察以下代码以更好地理解 −

Observe the following code for a better understanding −

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);
   }
}

Spring Boot - Quick Start

本章将教你如何使用 Maven 和 Gradle 创建 Spring Boot 应用程序。

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

Prerequisites

你的系统需要满足以下最低要求才能创建 Spring Boot 应用程序:

Your system need to have the following minimum requirements to create a Spring Boot application −

  1. Java 7

  2. Maven 3.2

  3. Gradle 2.5

Spring Boot CLI

Spring Boot CLI 是一款命令行工具,它允许我们运行 Groovy 脚本。这是使用 Spring Boot 命令行界面创建 Spring Boot 应用程序最简单的方法。你可以在命令提示符中创建、运行和测试应用程序。

The Spring Boot CLI is a command line tool and it allows us to run the Groovy scripts. This is the easiest way to create a Spring Boot application by using the Spring Boot Command Line Interface. You can create, run and test the application in command prompt itself.

本节向你介绍手动安装 Spring Boot CLI 所涉及的步骤。如需获得进一步的帮助,你可以使用以下链接: https://docs.spring.io/springboot/ docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-springboot

This section explains you the steps involved in manual installation of Spring Boot CLI. For further help, you can use the following link: https://docs.spring.io/springboot/ docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-springboot

You can also download the Spring CLI distribution from the Spring Software repository at: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation

对于手动安装,你需要使用以下两个文件夹:

For manual installation, you need to use the following two folders −

  1. spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip

  2. spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz

下载后,解压存档文件并按照 install.txt 文件中给出的步骤操作。不,它不需要任何环境设置。

After the download, unpack the archive file and follow the steps given in the install.txt file. Not that it does not require any environment setup.

在 Windows 中,在命令提示符中进入 Spring Boot CLI bin 目录,然后运行命令 spring –-version 以确保 spring CLI 正确安装。执行该命令后,您可以看到 spring CLI 版本,如下所示 −

In Windows, go to the Spring Boot CLI bin directory in the command prompt and run the command spring –-version to make sure spring CLI is installed correctly. After executing the command, you can see the spring CLI version as shown below −

spring cli version

Run Hello World with Groovy

创建一个简单的 groovy 文件,其中包含 Rest Endpoint 脚本,并使用 spring boot CLI 运行该 groovy 文件。观察此处为此目的所示的代码 −

Create a simple groovy file which contains the Rest Endpoint script and run the groovy file with spring boot CLI. Observe the code shown here for this purpose −

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

现在,以 hello.groovy 的名称保存该 groovy 文件。请注意在此示例中,我们将其 groovy 文件保存在 Spring Boot CLI bin 目录中。现在,使用命令 spring run hello.groovy 运行应用程序,如下所示屏幕截图 −

Now, save the groovy file with the name hello.groovy. Note that in this example, we saved the groovy file inside the Spring Boot CLI bin directory. Now run the application by using the command spring run hello.groovy as shown in the screenshot given below −

run hello world with groovy

运行该 groovy 文件后,所需依赖项将自动下载,它将在 Tomcat 8080 端口启动应用程序,如下所示屏幕截图 −

Once you run the groovy file, required dependencies will download automatically and it will start the application in Tomcat 8080 port as shown in the screenshot given below −

run groovy file tomcat port

一旦 Tomcat 启动,转到 web 浏览器并点击该 URL http://localhost:8080/ ,您可以看到所示的输出。

Once Tomcat starts, go to the web browser and hit the URL http://localhost:8080/ and you can see the output as shown.

hello spring boot

Spring Boot - Bootstrapping

本章将向您解释如何在 Spring Boot 应用程序上执行启动。

This chapter will explain you how to perform bootstrapping on a Spring Boot application.

Spring Initializer

一种启动 Spring Boot 应用程序的方法是使用 Spring Initializer。为此,您将必须访问 Spring Initializer 网页 www.start.spring.io 并选择您的构建、Spring Boot 版本和平台。此外,您还需要提供一个组、制品和运行应用程序所需的依赖项。

One of the ways to Bootstrapping a Spring Boot application is by using Spring Initializer. To do this, you will have to visit the Spring Initializer web page www.start.spring.io and choose your Build, Spring Boot Version and platform. Also, you need to provide a Group, Artifact and required dependencies to run the application.

观察以下屏幕截图,该屏幕截图显示了我们添加 spring-boot-starter-web 依赖项来编写 REST 端点的示例。

Observe the following screenshot that shows an example where we added the spring-boot-starter-web dependency to write REST Endpoints.

spring initializer

在您提供组、制品、依赖项、构建项目、平台和版本后,单击 Generate Project 按钮。zip 文件将下载,并且文件将被提取。

Once you provided the Group, Artifact, Dependencies, Build Project, Platform and Version, click Generate Project button. The zip file will download and the files will be extracted.

本节向您解释使用 Maven 和 Gradle 的示例。

This section explains you the examples by using both Maven and Gradle.

Maven

下载项目后,解压该文件。现在,你的 pom.xml 文件看起来如下所示 −

After you download the project, unzip the file. Now, your pom.xml file looks as shown below −

<?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.tutorialspoint</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 文件看起来如下所示 −

Once you download the project, unzip the file. Now your build.gradle file looks as shown below −

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.tutorialspoint'
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')
}

Class Path Dependencies

Spring Boot 提供许多 Starters ,用于向我们的类路径中添加 jar。例如,对于编写 Rest 端点,我们需要在我们的类路径中添加 spring-boot-starter-web 依赖项。观察下面显示的代码以获得更好的理解 −

Spring Boot provides a number of Starters to add the jars in our class path. For example, for writing a Rest Endpoint, we need to add the spring-boot-starter-web dependency in our class path. Observe the codes shown below for a better understanding −

Maven dependency

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

Gradle dependency

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

Main Method

spring boot 应用程序类应该编写这个主方法。这个类应该使用 @SpringBootApplication 进行注释。这是 spring boot 应用程序开始的入口点。你可以在使用默认包的 src/java/main 目录中找到主类文件。

The main method should be writing the Spring Boot Application class. This class should be annotated with @SpringBootApplication. This is the entry point of the spring boot application to start. You can find the main class file under src/java/main directories with the default package.

在这个例子中,主类文件位于使用默认包 com.tutorialspoint.demosrc/java/main 目录中。观察这里展示的代码以获得更好的理解 −

In this example, the main class file is located at the src/java/main directories with the default package com.tutorialspoint.demo. Observe the code shown here for a better understanding −

package com.tutorialspoint.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);
   }
}

Write a Rest Endpoint

要在 spring boot 应用程序主类文件中编写一个简单的 Hello Word Rest 端点,请遵循以下步骤 −

To write a simple Hello World Rest Endpoint in the Spring Boot Application main class file itself, follow the steps shown below −

  1. Firstly, add the @RestController annotation at the top of the class.

  2. Now, write a Request URI method with @RequestMapping annotation.

  3. Then, the Request URI method should return the Hello World string.

现在,你的 spring boot 应用程序主类文件将看起来像下面给出的代码中所示 −

Now, your main Spring Boot Application class file will look like as shown in the code given below −

package com.tutorialspoint.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";
   }
}

Create an Executable JAR

让我们使用如下所示在命令提示符中使用 Maven 和 Gradle 命令创建一个可执行 JAR 文件来运行 spring boot 应用程序 −

Let us create an executable JAR file to run the Spring Boot application by using Maven and Gradle commands in the command prompt as shown below −

使用 Maven 命令 mvn clean install 如下所示 −

Use the Maven command mvn clean install as shown below −

command mvn clean install

执行命令后,你可以在命令提示符中看到 BUILD SUCCESS 消息,如下所示 −

After executing the command, you can see the BUILD SUCCESS message at the command prompt as shown below −

build success message

使用 Gradle 命令 gradle clean build 如下所示 −

Use the Gradle command gradle clean build as shown below −

gradle clean build

执行命令后,你可以在命令提示符中看到 BUILD SUCCESSFUL 消息,如下所示 −

After executing the command, you can see the BUILD SUCCESSFUL message in the command prompt as shown below −

build successful message in command prompt

Run Hello World with Java

创建可执行 JAR 文件后,你可以在以下目录中找到它。

Once you have created an executable JAR file, you can find it under the following directories.

对于 Maven,你可以在如下所示的 target 目录中找到 JAR 文件 −

For Maven, you can find the JAR file under the target directory as shown below −

maven jar file target directory

对于 Gradle,你可以在如下所示的 build/libs 目录中找到 JAR 文件 −

For Gradle, you can find the JAR file under the build/libs directory as shown below −

jar file under build libs directory

现在,使用命令 java –jar <JARFILE> 运行 JAR 文件。请注意,在上面的示例中,JAR 文件被命名为 demo-0.0.1-SNAPSHOT.jar

Now, run the JAR file by using the command java –jar <JARFILE>. Observe that in the above example, the JAR file is named demo-0.0.1-SNAPSHOT.jar

jar file named demo snapshot

一旦运行 jar 文件,你可以在控制台窗口中看到输出,如下所示 −

Once you run the jar file, you can see the output in the console window as shown below −

output in console window

现在查看控制台,Tomcat 已在端口 8080 (http) 上启动。现在转到 Web 浏览器并输入 URL http://localhost:8080/ ,你将能看到如下所示的输出 −

Now, look at the console, Tomcat started on port 8080 (http). Now, go to the web browser and hit the URL http://localhost:8080/ and you can see the output as shown below −

tomcat started on port 8080 http

Spring Boot - Tomcat Deployment

通过使用 Spring Boot 应用程序,我们可以在 web 服务器中创建 war 文件进行部署。在此章节中,您将学习如何创建一个 WAR 文件,并在 Tomcat web 服务器中部署 Spring Boot 应用程序。

By using Spring Boot application, we can create a war file to deploy into the web server. In this chapter, you are going to learn how to create a WAR file and deploy the Spring Boot application in Tomcat web server.

Spring Boot Servlet Initializer

传统的部署方式是让 Spring Boot 应用程序 @SpringBootApplication 类继承 SpringBootServletInitializer 类。Spring Boot Servlet Initializer 类文件允许您在启动应用程序时使用 Servlet Container 进行配置。

The traditional way of deployment is making the Spring Boot Application @SpringBootApplication class extend the SpringBootServletInitializer class. Spring Boot Servlet Initializer class file allows you to configure the application when it is launched by using Servlet Container.

JAR 文件部署的 Spring Boot 应用程序类文件的代码如下 -

The code for Spring Boot Application class file for JAR file deployment is given below −

package com.tutorialspoint.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 应用程序类文件的代码如下 -

We need to extend the class SpringBootServletInitializer to support WAR file deployment. The code of Spring Boot Application class file is given below −

package com.tutorialspoint.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);
   }
}

Setting Main Class

在 Spring Boot 中,我们需要在构建文件中提及应启动的主类。为此,您可以使用以下代码片断 -

In Spring Boot, we need to mention the main class that should start in the build file. For this purpose, you can use the following pieces of code −

对于 Maven,在 pom.xml 属性中添加启动类,如下所示 -

For Maven, add the start class in pom.xml properties as shown below −

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

对于 Gradle,在 build.gradle 文件中添加主类名,如下所示:

For Gradle, add the main class name in build.gradle as shown below −

mainClassName="com.tutorialspoint.demo.DemoApplication"

Update packaging JAR into WAR

我们必须使用以下代码片断将打包 JAR 更新为 WAR:

We have to update the packaging JAR into WAR using the following pieces of code −

对于 Maven,在 pom.xml 中将打包添加为 WAR,如下所示:

For Maven, add the packaging as WAR in pom.xml as shown below −

<packaging>war</packaging>

对于 Gradle,在 build.gradle 中添加应用程序插件和 war 插件,如下所示:

For Gradle, add the application plugin and war plugin in the build.gradle as shown below −

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

现在,让我们编写一个简单的 Rest 端点以返回字符串“Hello World from Tomcat”。要编写 Rest 端点,我们需要将 Spring Boot web starter 依赖项添加到构建文件中。

Now, let us write a simple Rest Endpoint to return the string “Hello World from Tomcat”. To write a Rest Endpoint, we need to add the Spring Boot web starter dependency into our build file.

对于 Maven,使用以下代码在 pom.xml 中添加 Spring Boot starter 依赖项:

For Maven, add the Spring Boot starter dependency in pom.xml using the code as shown below −

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

对于 Gradle,使用以下代码在 build.gradle 中添加 Spring Boot starter 依赖项:

For Gradle, add the Spring Boot starter dependency in build.gradle using the code as shown below −

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

现在,使用以下代码,在 Spring Boot 应用程序类文件中编写一个简单的 Rest 端点:

Now, write a simple Rest Endpoint in Spring Boot Application class file using the code as shown below −

package com.tutorialspoint.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";
   }
}

Packaging your Application

现在,使用 Maven 和 Gradle 命令来打包应用程序,并创建一个 WAR 文件以部署到 Tomcat 服务器,如下所示:

Now, create a WAR file to deploy into the Tomcat server by using Maven and Gradle commands for packaging your application as given below −

对于 Maven,使用命令 mvn package 来打包应用程序。然后,将创建 WAR 文件,你可以在目标目录中找到它,如下面的屏幕截图所示:

For Maven, use the command mvn package for packaging your application. Then, the WAR file will be created and you can find it in the target directory as shown in the screenshots given below −

maven mvn package
maven packaging application target directory

对于 Gradle,使用命令 gradle clean build 来打包应用程序。然后,你的 WAR 文件将被创建,你可以在 build/libs 目录中找到它。仔细观察此处给出的屏幕截图,以更好地理解:

For Gradle, use the command gradle clean build for packaging your application. Then, your WAR file will be created and you can find it under build/libs directory. Observe the screenshots given here for a better understanding −

gradle clean build command
maven packaging application target directory

Deploy into Tomcat

现在,运行 Tomcat 服务器,并将 WAR 文件部署在 webapps 目录下。仔细观察此处显示的屏幕截图,以更好地理解:

Now, run the Tomcat Server, and deploy the WAR file under the webapps directory. Observe the screenshots shown here for a better understanding −

tomcat web application maneger
webapps directory

成功部署后,在 Web 浏览器 http://localhost:8080/demo-0.0.1-SNAPSHOT/ 中输入 URL,你会看到输出的外观如下面给出的屏幕截图所示:

After successful deployment, hit the URL in your web browser http://localhost:8080/demo-0.0.1-SNAPSHOT/ and observe that the output will look as shown in the screenshot given below −

successful deployment screenshot

为此目的的完整代码如下所示:

The full code for this purpose is given below.

pom.xml

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.tutorialspoint</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.tutorialspoint.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

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.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
mainClassName = "com.tutorialspoint.demo.DemoApplication"

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

Spring Boot 主应用程序类文件的代码如下 -

The code for main Spring Boot application class file is given below −

package com.tutorialspoint.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 - Build Systems

在 Spring Boot 中,选择构建系统是一项重要任务。我们推荐 Maven 或 Gradle,因为它们为依赖管理提供了良好的支持。Spring 很好地不支持其他构建系统。

In Spring Boot, choosing a build system is an important task. We recommend Maven or Gradle as they provide a good support for dependency management. Spring does not support well other build systems.

Dependency Management

Spring Boot 团队提供了依赖项列表来为其每个版本的 Spring Boot 版本提供支持。你无需在构建配置文件中为依赖项提供版本。Spring Boot 会根据版本自动配置依赖项版本。请记住,当你升级 Spring Boot 版本时,依赖项也会自动升级。

Spring Boot team provides a list of dependencies to support the Spring Boot version for its every release. You do not need to provide a version for dependencies in the build configuration file. Spring Boot automatically configures the dependencies version based on the release. Remember that when you upgrade the Spring Boot version, dependencies also will upgrade automatically.

Note - 如果你想为依赖项指定版本,你可以在配置文件中指定它。但是,Spring Boot 团队强烈建议不需要为依赖项指定版本。

Note − If you want to specify the version for dependency, you can specify it in your configuration file. However, the Spring Boot team highly recommends that it is not needed to specify the version for dependency.

Maven Dependency

对于 Maven 配置,我们应继承 Spring Boot Starter 父项目以管理 Spring Boot Starter 依赖项。为此,我们可以像下面所示一样简单地继承 our pom.xml 文件中的 starter parent。

For Maven configuration, we should inherit the Spring Boot Starter parent project to manage the Spring Boot Starters dependencies. For this, simply we can inherit the starter parent in our pom.xml file as shown below.

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

我们应指定 Spring Boot Parent Starter 依赖项的版本号。然后,对于其他 starter 依赖项,我们不需要指定 Spring Boot 版本号。观察下面给出的代码 −

We should specify the version number for Spring Boot Parent Starter dependency. Then for other starter dependencies, we do not need to specify the Spring Boot version number. Observe the code given below −

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

Gradle Dependency

我们可以直接将 Spring Boot Starter 依赖项导入 build.gradle 文件中。我们不需要像针对 Gradle 的 Maven 那样的 Spring Boot Start 父依赖项。观察下面给出的代码 −

We can import the Spring Boot Starters dependencies directly into build.gradle file. We do not need Spring Boot start Parent dependency like Maven for Gradle. Observe the code given below −

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

类似地,在 Gradle 中,我们不需要为依赖项指定 Spring Boot 版本号。Spring Boot 根据版本自动配置依赖项。

Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies. Spring Boot automatically configures the dependency based on the version.

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

Spring Boot - Code Structure

Spring Boot 没有可供使用的代码布局。但是,有一些最佳做法将有助于我们。本章将详细讨论这些做法。

Spring Boot does not have any code layout to work with. However, there are some best practices that will help us. This chapter talks about them in detail.

Default package

一个不包含任何 package 声明的类被视为一个 default package 。请注意,通常不建议使用默认的 package 声明。当您使用默认 package 时,Spring Boot 将导致问题,例如自动配置或组件扫描出现故障。

A class that does not have any package declaration is considered as a default package. Note that generally a default package declaration is not recommended. Spring Boot will cause issues such as malfunctioning of Auto Configuration or Component Scan, when you use default package.

Note - Java 为 package 声明推荐的命名约定是反转域名。例如 − com.tutorialspoint.myproject

Note − Java’s recommended naming convention for package declaration is reversed domain name. For example − com.tutorialspoint.myproject

Typical Layout

Spring Boot 应用程序的典型布局如下面给出的图片所示 −

The typical layout of Spring Boot application is shown in the image given below −

typical layout of spring boot application

Application.java 文件应使用 @SpringBootApplication 声明 main 方法。观察下面给出的代码以更好地理解 −

The Application.java file should declare the main method along with @SpringBootApplication. Observe the code given below for a better understanding −

package com.tutorialspoint.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);}
}

Beans and Dependency Injection

在 Spring 引导中,我们可以使用 Spring Framework 来定义我们的 Bean 及其依赖项注入。 @ComponentScan 注释用于查找 Bean,而 @Autowired 注释用于注入相应的 Bean。

In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation.

如果您遵循了 Spring 引导典型布局,则无需为 @ComponentScan 注释指定任何参数。所有组件类文件都将自动注册到 Spring Bean 中。

If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation. All component class files are automatically registered with Spring Beans.

以下示例提供了有关自动连接 Rest 模板对象并为其创建 Bean 的思路:

The following example provides an idea about Auto wiring the Rest Template object and creating a Bean for the same −

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

以下代码显示了在 Spring 引导应用程序主类文件中自动连接的 Rest 模板对象和 Bean 创建对象的代码:

The following code shows the code for auto wired Rest Template object and Bean creation object in main Spring Boot Application class file −

package com.tutorialspoint.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();
   }
}

Spring Boot - Runners

Application Runner 和 Command Line Runner 接口允许您在启动 Spring Boot 应用程序后执行代码。您可以在应用程序启动后立即使用这些接口执行任何操作。本章会详细讨论。

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

Application Runner 是一个在启动 Spring Boot 应用程序后用于执行代码的接口。下面给出的示例展示了如何在主类文件上实现 Application Runner 接口。

Application Runner is an interface used to execute the code after the Spring Boot application started. The example given below shows how to implement the Application Runner interface on the main class file.

package com.tutorialspoint.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");
   }
}

现在,如果您观察一下 Hello World from Application Runner 下面的控制台窗口,则会发现 println 语句是在 Tomcat 启动后执行的。以下屏幕截图是否相关?

Now, if you observe the console window below Hello World from Application Runner, the println statement is executed after the Tomcat started. Is the following screenshot relevant?

hello world from application runner

Command Line Runner

Command Line Runner 是一个接口。它用于在启动 Spring Boot 应用程序后执行代码。下面给出的示例展示了如何在主类文件上实现 Command Line Runner 接口。

Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started. The example given below shows how to implement the Command Line Runner interface on the main class file.

package com.tutorialspoint.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");
   }
}

查看下面 控制台窗口中的“来自 Command Line Runner 的 Hello world”,在 Tomcat 启动后执行 println 语句。

Look at the console window below “Hello world from Command Line Runner” println statement is executed after the Tomcat started.

command line runner

Spring Boot - Application Properties

应用程序属性支持我们在不同环境中工作。在本章中,你将学习如何配置和指定 Spring Boot 应用程序的属性。

Application Properties support us to work in different environments. In this chapter, you are going to learn how to configure and specify the properties to a Spring Boot application.

Command Line Properties

Spring Boot 应用程序将命令行属性转换为 Spring Boot 环境属性。命令行属性优先于其他属性源。默认情况下,Spring Boot 使用 8080 端口号启动 Tomcat。让我们了解如何使用命令行属性更改端口号。

Spring Boot application converts the command line properties into Spring Boot Environment properties. Command line properties take precedence over the other property sources. By default, Spring Boot uses the 8080 port number to start the Tomcat. Let us learn how change the port number by using command line properties.

Step 1 − 创建可执行 JAR 文件后,使用命令 java –jar <JARFILE> 运行它。

Step 1 − After creating an executable JAR file, run it by using the command java –jar <JARFILE>.

Step 2 − 使用下面截图中给出的命令,通过使用命令行属性更改 Spring Boot 应用程序的端口号。

Step 2 − Use the command given in the screenshot given below to change the port number for Spring Boot application by using command line properties.

command line properties jarfile

Note − 使用分隔符 − ­可以提供多个应用程序属性。

Note − You can provide more than one application properties by using the delimiter −.

Properties File

属性文件用于将“N”个属性保留在一个文件中,以在不同的环境中运行应用程序。在 Spring Boot 中,属性保存在 classpath 下的 application.properties 文件中。

Properties files are used to keep ‘N’ number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application.properties file under the classpath.

application.properties 文件位于 src/main/resources 目录中。示例 application.properties 文件的代码如下 −

The application.properties file is located in the src/main/resources directory. The code for sample application.properties file is given below −

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

请注意,在上面显示的代码中,Spring Boot 应用程序 demoservice 在端口 9090 上启动。

Note that in the code shown above the Spring Boot application demoservice starts on the port 9090.

YAML File

Spring Boot 支持基于 YAML 的属性配置以运行应用程序。我们可以使用 application.yml 文件代替 application.properties 。此 YAML 文件还应保留在 classpath 中。示例 application.yml 文件如下 −

Spring Boot supports YAML based properties configurations to run the application. Instead of application.properties, we can use application.yml file. This YAML file also should be kept inside the classpath. The sample application.yml file is given below −

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

Externalized Properties

我们可以将属性保留在不同位置或路径,而不用将属性文件保留在 classpath 中。在运行 JAR 文件时,我们可以指定属性文件路径。你可以使用以下命令来指定运行 JAR 时属性文件的位置 −

Instead of keeping the properties file under classpath, we can keep the properties in different location or path. While running the JAR file, we can specify the properties file path. You can use the following command to specify the location of properties file while running the JAR −

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

Use of @Value Annotation

@Value 注释用于在 Java 代码中读取环境或应用程序属性值。读取属性值的语法如下所示 −

The @Value annotation is used to read the environment or application property value in Java code. The syntax to read the property value is shown below −

@Value("${property_key_name}")

请看以下示例,它展示了使用 @Value 注解在 Java 变量中读取 spring.application.name 属性值时的语法。

Look at the following example that shows the syntax to read the spring.application.name property value in Java variable by using @Value annotation.

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

为得到更好的理解,观察下面给出的代码 −

Observe the code given below for a better understanding −

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;
   }
}

Note − 如果在运行应用程序时未找到属性,Spring Boot 会抛出 Illegal Argument 异常,形式为 Could not resolve placeholder 'spring.application.name' in value "${spring.application.name}"

Note − If the property is not found while running the application, Spring Boot throws the Illegal Argument exception as Could not resolve placeholder 'spring.application.name' in value "${spring.application.name}".

要解决占位符问题,我们可以使用下面给出的语法为属性设置默认值 −

To resolve the placeholder issue, we can set the default value for the property using thr syntax given below −

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

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

Spring Boot Active Profile

Spring Boot 支持基于 Spring 活动配置文件的不同属性。例如,我们可以保持两个独立的文件,用于开发和生产,以运行 Spring Boot 应用程序。

Spring Boot supports different properties based on the Spring active profile. For example, we can keep two separate files for development and production to run the Spring Boot application.

Spring active profile in application.properties

让我们了解如何在 application.properties 中使用 Spring 活动配置文件。默认情况下,application.properties 将用于运行 Spring Boot 应用程序。如果您要使用基于配置文件的属性,我们可以为每个配置文件保存独立的属性文件,如下所示 −

Let us understand how to have Spring active profile in application.properties. By default, application. properties will be used to run the Spring Boot application. If you want to use profile based properties, we can keep separate properties file for each profile as shown below −

application.properties

application.properties

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

application-dev.properties

application-dev.properties

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

application-prod.properties

application-prod.properties

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

在运行 JAR 文件时,我们需要基于每个属性文件指定 Spring 活动配置文件。默认情况下,Spring Boot 应用程序使用 application.properties 文件。设置 Spring 活动配置文件的命令如下所示 −

While running the JAR file, we need to specify the spring active profile based on each properties file. By default, Spring Boot application uses the application.properties file. The command to set the spring active profile is shown below −

prod properties active dev

您可以在控制台日志中看到活动配置文件名,如下所示 −

You can see active profile name on the console log as shown below −

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

现在,Tomcat 已在端口 9090(http)上启动,如下所示 −

Now, Tomcat has started on the port 9090 (http) as shown below −

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

您可以将生产活动配置文件设置如下所示 −

You can set the Production active profile as shown below −

production active profile

您可以在控制台日志中看到活动配置文件名,如下所示 −

You can see active profile name on the console log as shown below −

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

现在,Tomcat 已在端口 4431(http)上启动,如下所示 −

Now, Tomcat started on the port 4431 (http) as shown below −

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

Spring active profile for application.yml

让我们了解如何为 application.yml 保持 Spring 活动配置文件。我们可以将 Spring 活动配置文件属性保存在单个 application.yml 文件中。无需像 application.properties 那样使用独立的文件。

Let us understand how to keep Spring active profile for application.yml. We can keep the Spring active profile properties in the single application.yml file. No need to use the separate file like application.properties.

下面是一个示例代码,用于将 Spring 活动配置文件保存在 application.yml 文件中。请注意,分隔符 (---) 用于在 application.yml 文件中分隔每个配置文件。

The following is an example code to keep the Spring active profiles in application.yml file. Note that the delimiter (---) is used to separate each profile in application.yml file.

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

设置开发活动配置文件的命令如下所示 −

To command to set development active profile is given below −

prod properties active dev

您可以在控制台日志中看到活动配置文件名,如下所示 −

You can see active profile name on the console log as shown below −

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

现在,Tomcat 已在端口 9090(http)上启动,如下所示 −

Now, Tomcat started on the port 9090 (http) as shown below −

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

设置生产活动配置文件的命令如下所示 −

The command to set Production active profile is given below −

production active profile

您可以在控制台日志中看到活动配置文件名,如下所示 −

You can see active profile name on the console log as shown below −

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

如下所示,这将启动 4431 端口(http)上的 Tomcat:

This will start Tomcat on the port 4431 (http) as shown below:

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

Spring Boot 使用 Apache Commons 记录所有内部记录。Spring Boot 的默认配置为使用 Java Util 记录、Log4j2 和 Logback 提供支持。使用这些,我们可以配置控制台记录以及文件记录。

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 Starter,则 Logback 将很好地支持记录。此外,Logback 同样为通用记录、Util 记录、Log4J 和 SLF4J 提供良好的支持。

If you are using Spring Boot Starters, Logback will provide a good support for logging. Besides, Logback also provides a use of good support for Common Logging, Util Logging, Log4J, and SLF4J.

Log Format

Spring Boot 的 Log 默认格式如下面给出的屏幕截图中所示。

The default Spring Boot Log format is shown in the screenshot given below.

spring boot log format

它向您提供以下信息 −

which gives you the following information −

  1. Date and Time that gives the date and time of the log

  2. Log level shows INFO, ERROR or WARN

  3. Process ID

  4. The --- which is a separator

  5. Thread name is enclosed within the square brackets []

  6. Logger Name that shows the Source class name

  7. The Log message

Console Log Output

默认日志消息将打印到控制台窗口。默认情况下,“INFO”、“ERROR”和“WARN”日志消息将打印到日志文件中。

The default log messages will print to the console window. By default, “INFO”, “ERROR” and “WARN” log messages will print in the log file.

如果您必须启用调试级别日志,请使用以下所示的命令在启动应用程序时添加调试标志 -

If you have to enable the debug level log, add the debug flag on starting your application using the command shown below −

java –jar demo.jar --debug

您还可以将调试模式添加到 application.properties 文件,如下所示 -

You can also add the debug mode to your application.properties file as shown here −

debug = true

File Log Output

默认情况下,所有日志都将打印在控制台窗口中,而不在文件中。如果您想在文件中打印日志,则需要在 application.properties 文件中设置属性 logging.filelogging.path

By default, all logs will print on the console window and not in the files. If you want to print the logs in a file, you need to set the property logging.file or logging.path in the application.properties file.

您可以使用以下所示的属性指定日志文件路径。请注意,日志文件名是 spring.log。

You can specify the log file path using the property shown below. Note that the log file name is spring.log.

logging.path = /var/tmp/

您可以使用以下所示的属性指定自己的日志文件名 -

You can specify the own log file name using the property shown below −

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

Note - 文件在达到 10 MB 大小时将自动轮换。

Note − files will rotate automatically after reaching the size 10 MB.

Log Levels

Spring Boot 支持所有日志记录级别,例如“TRACE”、“DEBUG”、“INFO”、“WARN”、“ERROR”、“FATAL”、“OFF”。您可以按如下所示在 application.properties 文件中定义 Root 记录器 -

Spring Boot supports all logger levels such as “TRACE”, “DEBUG”, “INFO”, “WARN”, “ERROR”, “FATAL”, “OFF”. You can define Root logger in the application.properties file as shown below −

logging.level.root = WARN

Note - Logback 不支持“FATAL”级别日志。它映射到“ERROR”级别日志。

Note − Logback does not support “FATAL” level log. It is mapped to the “ERROR” level log.

Configure Logback

Logback 支持基于 XML 的配置来处理 Spring Boot Log 配置。日志配置详细信息配置在 logback.xml 文件中。logback.xml 文件应放置在类路径下。

Logback supports XML based configuration to handle Spring Boot Log configurations. Logging configuration details are configured in logback.xml file. The logback.xml file should be placed under the classpath.

您可以使用以下给出的代码在 Logback.xml 文件中配置 ROOT 级别日志 -

You can configure the ROOT level log in Logback.xml file using the code given below −

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

您可以使用下面给出的代码在 Logback.xml 文件中配置控制台追加程序。

You can configure the console appender in Logback.xml file given below.

<?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 文件中配置文件追加程序。请注意,您需要在文件追加程序内部指定日志文件路径。

You can configure the file appender in Logback.xml file using the code given below. Note that you need to specify the Log file path insider the file appender.

<?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 文件中定义日志模式。您还可以使用以下给出的代码在控制台或文件日志追加程序中定义一组受支持的日志模式 -

You can define the Log pattern in logback.xml file using the code given below. You can also define the set of supported log patterns inside the console or file log appender using the code given below −

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

完整的 logback.xml 文件代码如下。您必须将其放在类路径中。

The code for complete logback.xml file is given below. You have to place this in the class path.

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

下面给出的代码展示如何将 slf4j 记录器添加到 Spring Boot 主类文件中。

The code given below shows how to add the slf4j logger in Spring Boot main class file.

package com.tutorialspoint.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);
   }
}

您可以在控制台窗口中看到的输出显示在这里 -

The output that you can see in the console window is shown here −

logger console window

您可以在日志文件中看到的输出显示在这里 -

The output that you can see in the log file is shown here −

log output

Spring Boot - Building RESTful Web Services

Spring Boot 为企业应用程序构建 RESTful Web 服务提供了非常好的支持。本章将详细介绍使用 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.

Note - 对于构建 RESTful Web 服务,我们需要将 Spring Boot Starter Web 依赖添加到构建配置文件中。

Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file.

如果您是 Maven 用户,使用以下代码将下列依赖添加到 pom.xml 文件中 -

If you are a Maven user, use the following code to add the below dependency in your pom.xml file −

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

如果您是 Gradle 用户,使用以下代码将下列依赖添加到 build.gradle 文件中。

If you are a Gradle user, use the following code to add the below dependency in your build.gradle file.

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

完整构建配置文件 Maven build – pom.xml 的代码如下 -

The code for complete build configuration file Maven build – pom.xml is given below −

<?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.tutorialspoint</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 的代码如下 -

The code for complete build configuration file Gradle Build – build.gradle is given below −

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.tutorialspoint'
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 服务之前,建议您了解以下注释 -

Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following annotations −

Rest Controller

@RestController 注解用于定义 RESTful Web 服务。它提供 JSON、XML 和自定义响应。其语法如下所示 -

The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below −

@RestController
public class ProductServiceController {
}

Request Mapping

@RequestMapping 注解用于定义访问 REST 端点的请求 URI。我们可以定义请求方法来使用和生成对象。默认请求方法为 GET。

The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET.

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

Request Body

@RequestBody 注解用于定义请求正文内容类型。

The @RequestBody annotation is used to define the request body content type.

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

Path Variable

@PathVariable 注解用于定义自定义或动态请求 URI。请求 URI 中的路径变量定义为花括号 {},如下所示 -

The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below −

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

Request Parameter

@RequestParam 注解用于从请求 URL 中读取请求参数。默认情况下,它是一个必需参数。我们还可以为请求参数设置默认值,如下所示 -

The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here −

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

GET API

默认 HTTP 请求方法为 GET。此方法不需要任何请求正文。您可以发送请求参数和路径变量来定义自定义或动态 URL。

The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL.

定义 HTTP GET 请求方法的示例代码如下所示。在此示例中,我们使用 HashMap 来存储产品。请注意,我们使用 POJO 类作为要存储的产品。

The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored.

此处,请求 URI 为 /products ,它将从 HashMap 存储库返回产品列表。包含 GET 方法 REST 端点的控制器类文件如下所示。

Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint.

package com.tutorialspoint.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.tutorialspoint.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。

The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL.

以下示例展示了定义 HTTP POST 请求方法的示例代码。在此示例中,我们使用了 HashMap 来存储产品,其中产品是一个 POJO 类。

The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class.

此处,请求 URI 为 /products ,它会在将产品存储到 HashMap 存储库后返回字符串。

Here, the request URI is /products, and it will return the String after storing the product into HashMap repository.

package com.tutorialspoint.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.tutorialspoint.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。

The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL.

以下给出的示例展示了如何定义 HTTP PUT 请求方法。在此示例中,我们使用了 HashMap 来更新现有产品,其中产品是一个 POJO 类。

The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class.

此处请求 URI 为 /products/{id} ,它会在将产品存储到 HashMap 存储库后返回字符串。请注意,我们使用了路径变量 {id} ,它定义了需要更新的产品 ID。

Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated.

package com.tutorialspoint.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.tutorialspoint.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 Delete 请求用于删除现有资源。此方法不包含任何请求主体。我们可以发送请求参数和路径变量来定义自定义或动态 URL。

The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL.

以下给出的示例展示了如何定义 HTTP DELETE 请求方法。在此示例中,我们使用了 HashMap 来移除现有产品,它是一个 POJO 类。

The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class.

请求 URI 为 /products/{id} ,它会在从 HashMap 存储库删除产品后返回字符串。我们使用了路径变量 {id} ,它定义了需要删除的产品 ID。

The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the Path variable {id} which defines the products ID that needs to be deleted.

package com.tutorialspoint.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.tutorialspoint.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);
   }
}

本部分为您提供了完整的源代码集。请观察以下代码及其各自的功能 −

This section gives you the complete set of source code. Observe the following codes for their respective functionalities −

The Spring Boot main application class – DemoApplication.java

The Spring Boot main application class – DemoApplication.java

package com.tutorialspoint.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);
   }
}

The POJO class – Product.java

The POJO class – Product.java

package com.tutorialspoint.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;
   }
}

The Rest Controller class – ProductServiceController.java

The Rest Controller class – ProductServiceController.java

package com.tutorialspoint.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.tutorialspoint.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 命令运行 Spring Boot 应用程序,如下所示 −

You can create an executable JAR file, and run the spring boot application by using the below Maven or Gradle commands as shown −

对于 Maven,使用以下所示的命令 −

For Maven, use the command shown below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用以下所示的命令 −

For Gradle, use the command shown below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

您可以使用以下所示的命令运行 JAR 文件 −

You can run the JAR file by using the command shown below −

java –jar <JARFILE>

这将启动 8080 端口上的应用程序,如下所示 −

This will start the application on the Tomcat port 8080 as shown below −

started application on tomcat port 8080

现在点击 POSTMAN 应用程序中以下所示的 URL,并查看输出。

Now hit the URL shown below in POSTMAN application and see the output.

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

postman application get api url

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

postman application post api url
postman application put api url

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

postman application delete api url

Spring Boot - Exception Handling

在 API 中处理异常和错误,并向客户端发送适当响应,这对于企业应用程序而言十分有益。在本章中,我们将学习如何在 Spring Boot 中处理异常。

Handling exceptions and errors in APIs and sending the proper response to the client is good for enterprise applications. In this chapter, we will learn how to handle exceptions in Spring Boot.

在开始异常处理之前,让我们了解一下以下注解。

Before proceeding with exception handling, let us gain an understanding on the following annotations.

Controller Advice

@ControllerAdvice 是一种注解,用于全局处理异常。

The @ControllerAdvice is an annotation, to handle the exceptions globally.

Exception Handler

@ExceptionHandler 是一种注解,用于处理特定异常并向客户端发送自定义响应。

The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client.

你可以使用以下代码来创建 @ControllerAdvice 类以全局处理异常−

You can use the following code to create @ControllerAdvice class to handle the exceptions globally −

package com.tutorialspoint.demo.exception;

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

@ControllerAdvice
   public class ProductExceptionController {
}

定义一个扩展 RuntimeException 类的类。

Define a class that extends the RuntimeException class.

package com.tutorialspoint.demo.exception;

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

你可以定义 @ExceptionHandler 方法来处理异常,如下所示。这种方法应该用于编写控制器建议类文件。

You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file.

@ExceptionHandler(value = ProductNotfoundException.class)

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

现在,使用下面给出的代码从 API 中抛出异常。

Now, use the code given below to throw the exception from the API.

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

处理异常的完整代码如下所示。在这个示例中,我们使用 PUT API 来更新产品。这里,在更新产品时,如果未找到产品,则返回响应错误消息“未找到产品”。请注意, ProductNotFoundException 异常类应该扩展 RuntimeException

The complete code to handle the exception is given below. In this example, we used the PUT API to update the product. Here, while updating the product, if the product is not found, then return the response error message as “Product not found”. Note that the ProductNotFoundException exception class should extend the RuntimeException.

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

全局处理异常的控制器建议类如下所示。我们可以在这个类文件中定义任何异常处理方法。

The Controller Advice class to handle the exception globally is given below. We can define any Exception Handler methods in this class file.

package com.tutorialspoint.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);
   }
}

产品服务 API 控制器文件如下所示,用于更新产品。如果未找到产品,则会抛出 ProductNotFoundException 类。

The Product Service API controller file is given below to update the Product. If the Product is not found, then it throws the ProductNotFoundException class.

package com.tutorialspoint.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.tutorialspoint.demo.exception.ProductNotfoundException;
import com.tutorialspoint.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 主应用程序类文件的代码如下 -

The code for main Spring Boot application class file is given below −

package com.tutorialspoint.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 class 的代码如下所示 −

The code for POJO class for Product is given below −

package com.tutorialspoint.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 build – pom.xml 的代码如下所示 −

The code for Maven build – pom.xml is shown below −

<?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.tutorialspoint</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 的代码如下所示 −

The code for Gradle Build – build.gradle is given below −

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.tutorialspoint'
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 应用程序 −

You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands −

对于 Maven,可以使用以下命令:

For Maven, you can use the following command −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,可以使用以下命令:

For Gradle, you can use the following command −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

你可以使用以下命令运行 JAR 文件 −

You can run the JAR file by using the following command −

java –jar <JARFILE>

这将启动 8080 端口上的应用程序,如下所示 −

This will start the application on the Tomcat port 8080 as shown below −

exception handling tomcat application startded

现在在 POSTMAN 应用程序中访问下面的 URL,你就可以看到如下所示的输出 −

Now hit the below URL in POSTMAN application and you can see the output as shown below −

更新 URL: [role="bare"] [role="bare"]http://localhost:8080/products/3

Update URL: [role="bare"]http://localhost:8080/products/3

postman application update url

Spring Boot - Interceptor

你可以在 Spring Boot 中使用 Interceptor 在下列情况中执行操作 −

You can use the Interceptor in Spring Boot to perform operations under the following situations −

  1. Before sending the request to the controller

  2. Before sending the response to the client

例如,你可以在向控制器发送请求之前使用拦截器添加请求头,并在向客户端发送响应之前添加响应头。

For example, you can use an interceptor to add the request header before sending the request to the controller and add the response header before sending the response to the client.

要使用拦截器,你需要创建支持它的 @Component 类,并实现 HandlerInterceptor 接口。

To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface.

以下是使用拦截器时你需要了解的三种方法 −

The following are the three methods you should know about while working on Interceptors −

  1. preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.

  2. postHandle() method − This is used to perform operations before sending the response to the client.

  3. afterCompletion() method − This is used to perform operations after completing the request and response.

观察以下代码以更好地理解 −

Observe the following code for a better understanding −

@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 将此 Interceptor 注册到 InterceptorRegistry ,如下所示 −

You will have to register this Interceptor with InterceptorRegistry by using WebMvcConfigurerAdapter as shown below −

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

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

在下面的示例中,我们将触及 GET products API,其输出如下所示 −

In the example given below, we are going to hit the GET products API which gives the output as given under −

Interceptor 类 ProductServiceInterceptor.java 的代码如下 −

The code for the Interceptor class ProductServiceInterceptor.java is given below −

package com.tutorialspoint.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");
   }
}

注册 Interceptor 的应用程序配置类文件的代码,InterceptorRegistry – ProductServiceInterceptorAppConfig.java 如下所示 −

The code for Application Configuration class file to register the Interceptor into Interceptor Registry – ProductServiceInterceptorAppConfig.java is given below −

package com.tutorialspoint.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);
   }
}

控制器类文件 ProductServiceController.java 的代码如下 −

The code for Controller class file ProductServiceController.java is given below −

package com.tutorialspoint.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.tutorialspoint.demo.exception.ProductNotfoundException;
import com.tutorialspoint.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 类文件的代码如下 −

The code for POJO class for Product.java is given below −

package com.tutorialspoint.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 的代码如下 −

The code for main Spring Boot application class file DemoApplication.java is given below −

package com.tutorialspoint.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 如下所示 −

The code for Maven build – pom.xml is shown here −

<?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.tutorialspoint</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.gradle 如下所示 −

The code for Gradle Build build.gradle is shown here −

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.tutorialspoint'
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 应用程序。

You can create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands.

对于 Maven,使用如下所示的命令:

For Maven, use the command as shown below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,像下面这样使用命令 -

For Gradle, use the command as shown below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

你可以使用以下命令运行 JAR 文件 −

You can run the JAR file by using the following command −

java –jar <JARFILE>

现在,应用程序在 Tomcat 端口 8080 上启动,如下所示 -

Now, the application has started on the Tomcat port 8080 as shown below −

started application on tomcat port 8080

现在在 POSTMAN 应用程序中点击下面的 URL,您会看到像下面显示的输出−

Now hit the below URL in POSTMAN application and you can see the output as shown under −

postman application get api url

在控制台窗口中,您会看到在拦截器中添加的 System.out.println 语句,如下面给出的屏幕截图所示−

In the console window, you can see the System.out.println statements added in the Interceptor as shown in the screenshot given below −

interceptor output console window

Spring Boot - Servlet Filter

过滤器是用于拦截应用程序的 HTTP 请求和响应的对象。通过使用过滤器,我们可以在两个实例执行两个操作−

A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances −

  1. Before sending the request to the controller

  2. Before sending a response to the client.

以下代码展示了一个 Servlet 过滤器实现类的样例代码,带 @Component 注解。

The following code shows the sample code for a Servlet Filter implementation class with @Component annotation.

@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 对象读取远程主机和远程地址的代码。

The following example shows the code for reading the remote host and remote address from the ServletRequest object before sending the request to the controller.

在 doFilter() 方法中,我们添加了 System.out.println 语句来打印远程主机和远程地址。

In doFilter() method, we have added the System.out.println statements to print the remote host and remote address.

package com.tutorialspoint.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 端点。

In the Spring Boot main application class file, we have added the simple REST endpoint that returns the “Hello World” string.

package com.tutorialspoint.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 如下−

The code for Maven build – pom.xml is given below −

<?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.tutorialspoint</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.gradle 如下 −

The code for Gradle Build – build.gradle is given below −

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.tutorialspoint'
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 应用程序−

You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below −

对于 Maven,使用如下所示的命令:

For Maven, use the command as shown below −

mvn clean install

在 BUILD SUCCESS 之后,您可以在 target 目录下找到 JAR 文件。

After BUILD SUCCESS, you can find the JAR file under the target directory.

对于 Gradle,像下面这样使用命令 -

For Gradle, use the command as shown below −

gradle clean build

在 BUILD SUCCESSFUL 之后,您可以在 build/libs 目录下找到 JAR 文件。

After BUILD SUCCESSFUL, you can find the JAR file under the build/libs directory.

现在,使用以下命令运行 JAR 文件

Now, run the JAR file by using the following command

java –jar <JARFILE>

您可以看到应用程序已在 Tomcat 端口 8080 上启动。

You can see the application has started on the Tomcat port 8080.

现在点击 URL http://localhost:8080/ 并查看输出 Hello World。它应该像下面显示的那样−

Now hit the URL http://localhost:8080/ and see the output Hello World. It should look as shown below −

tomcat started on port 8080 http

然后,您可以在控制台日志中看到远程主机和远程地址,如下所示−

Then, you can see the Remote host and Remote address on the console log as shown below −

remote host remote address on console log

Spring Boot - Tomcat Port Number

Spring Boot 允许您在不同的端口号上多次运行同一应用程序。本章将对此进行详细说明。请注意,默认端口号为 8080。

Spring Boot lets you to run the same application more than once on a different port number. In this chapter, you will learn about this in detail. Note that the default port number 8080.

Custom Port

application.properties 文件中,我们可以为 server.port 属性设置自定义端口号

In the application.properties file, we can set custom port number for the property server.port

server.port = 9090

application.yml 文件中,您可以找到以下内容:−

In the application.yml file, you can find as follows −

server:
   port: 9090

Random Port

application.properties 文件中,我们可以为 server.port 属性设置随机端口号

In the application.properties file, we can set random port number for the property server.port

server.port = 0

application.yml 文件中,您可以找到以下内容:−

In the application.yml file, you can find as follows −

server:
   port: 0

Note − 如果在启动 Spring Boot 应用程序时 server.port 号码为 0,则 Tomcat 将使用随机端口号。

Note − If the server.port number is 0 while starting the Spring Boot application, Tomcat uses the random port number.

Spring Boot - Rest Template

Rest Template 用于创建使用 RESTful Web 服务的应用程序。您可以使用 exchange() 方法对所有 HTTP 方法使用 Web 服务。下面给出的代码展示了如何为 Rest Template 创建 Bean,自动连接 Rest Template 对象。

Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object.

package com.tutorialspoint.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

Consuming the GET API by using RestTemplate - exchange() method

Consuming the GET API by using RestTemplate - exchange() method

假设此 URL http://localhost:8080/products 返回以下 JSON,我们将使用以下代码通过 Rest Template 使用此 API 响应 -

Assume this URL http://localhost:8080/products returns the following JSON and we are going to consume this API response by using Rest Template using the following code −

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

您将必须遵循给定的要点来使用 API -

You will have to follow the given points to consume the API −

  1. Autowired the Rest Template Object.

  2. Use HttpHeaders to set the Request Headers.

  3. Use HttpEntity to wrap the request object.

  4. Provide the URL, HttpMethod, and Return type for Exchange() method.

@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

Consuming POST API by using RestTemplate - exchange() method

Consuming POST API by using RestTemplate - exchange() method

假设此 URL http://localhost:8080/products 返回如下所示的响应,我们将使用 Rest Template 使用此 API 响应。

Assume this URL http://localhost:8080/products returns the response shown below, we are going to consume this API response by using the Rest Template.

以下给出的代码为请求正文 -

The code given below is the Request body −

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

以下给出的代码为响应正文 -

The code given below is the Response body −

Product is created successfully

您将必须遵循下面给出的要点来使用 API -

You will have to follow the points given below to consume the API −

  1. Autowired the Rest Template Object.

  2. Use the HttpHeaders to set the Request Headers.

  3. Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body.

  4. Provide the URL, HttpMethod, and Return type for exchange() method.

@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

Consuming PUT API by using RestTemplate - exchange() method

Consuming PUT API by using RestTemplate - exchange() method

假设此 URL http://localhost:8080/products/3 返回如下响应,我们将使用 Rest Template 使用此 API 响应。

Assume this URL http://localhost:8080/products/3 returns the below response and we are going to consume this API response by using Rest Template.

以下代码为请求正文 -

The code given below is Request body −

{
   "name":"Indian Ginger"
}

以下给出的代码为响应正文 -

The code given below is the Response body −

Product is updated successfully

您将必须遵循下面给出的要点来使用 API -

You will have to follow the points given below to consume the API −

  1. Autowired the Rest Template Object.

  2. Use HttpHeaders to set the Request Headers.

  3. Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body.

  4. Provide the URL, HttpMethod, and Return type for exchange() method.

@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

Consuming DELETE API by using RestTemplate - exchange() method

Consuming DELETE API by using RestTemplate - exchange() method

假设此 URL http://localhost:8080/products/3 返回给定的响应,并且我们准备使用 Rest 模板来处理此 API 响应。

Assume this URL http://localhost:8080/products/3 returns the response given below and we are going to consume this API response by using Rest Template.

下面显示的此代码行是响应主体 -

This line of code shown below is the Response body −

Product is deleted successfully

您必须遵循下方所示步骤,以处理 API -

You will have to follow the points shown below to consume the API −

  1. Autowired the Rest Template Object.

  2. Use HttpHeaders to set the Request Headers.

  3. Use HttpEntity to wrap the request object.

  4. Provide the URL, HttpMethod, and Return type for exchange() method.

@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 模板控制器类文件如下 -

The complete Rest Template Controller class file is given below −

package com.tutorialspoint.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.tutorialspoint.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 应用程序类 - DemoApplication.java 的代码如下 -

The code for Spring Boot Application Class – DemoApplication.java is given below −

package com.tutorialspoint.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 如下 −

The code for Maven build – pom.xml is given below −

<?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.tutorialspoint</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.gradle 如下 −

The code for Gradle Build – build.gradle is given below −

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.tutorialspoint'
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 应用程序 -

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −

对于 Maven,你可以使用下面给出的命令 −

For Maven, you can use the command given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用下面显示的命令 −

For Gradle, you can use the command shown below −

gradle clean build

在 “BUILD SUCCESSFUL” 后,你可以在 build/libs 目录下找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory.

现在,通过使用以下命令运行 JAR 文件 −

Now, run the JAR file by using the following command −

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 8080 上启动。

Now, the application has started on the Tomcat port 8080.

started application on tomcat port 8080

现在在 POSTMAN 应用程序中输入以下 URL,您将看到输出。

Now hit the below URL’s in POSTMAN application and you can see the output.

使用 Rest 模板获取产品 - http://localhost:8080/template/products

GET Products by Rest Template − http://localhost:8080/template/products

get products by rest template

Create Products POST − http://localhost:8080/template/products

create products post
update products post
delete products post

Spring Boot - File Handling

在本章中,您将学习如何使用 Web 服务上传和下载文件。

In this chapter, you will learn how to upload and download the file by using web service.

File Upload

对于上传文件,您可以使用 MultipartFile 作为请求参数,并且此 API 应使用多部分表单数据值。观察下面给出的代码 −

For uploading a file, you can use MultipartFile as a Request Parameter and this API should consume Multi-Part form data value. Observe the code given below −

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

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

完整的代码如下 −

The complete code for the same is given below −

package com.tutorialspoint.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";
   }
}

File Download

对于文件下载,您应该使用 InputStreamResource 下载文件。我们需要在响应中设置 Content-Disposition 的 HttpHeader,并且需要指定应用程序的响应媒体类型。

For file download, you should use InputStreamResource for downloading a File. We need to set the HttpHeader Content-Disposition in Response and need to specify the response Media Type of the application.

Note − 在以下示例中,文件应可在应用程序正在运行的指定路径上获得。

Note − In the following example, file should be available on the specified path where the application is running.

@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;
}

完整的代码如下 −

The complete code for the same is given below −

package com.tutorialspoint.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 的主应用程序如下 −

The main Spring Boot application is given below −

package com.tutorialspoint.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 如下 −

The code for Maven build – pom.xml is given below −

<?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.tutorialspoint</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.gradle 如下 −

The code for Gradle Build – build.gradle is given below −

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.tutorialspoint'
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 应用程序 −

Now you can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −

对于 Maven,使用以下给出的命令 −

For Maven, use the command given below −

mvn clean install

在“构建成功”后,您可以在 target 目录下找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under target directory.

对于 Gradle,您可以使用以下所示命令 −

For Gradle, you ca use the command shown below −

sgradle clean build

在 “BUILD SUCCESSFUL” 后,你可以在 build/libs 目录下找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory.

现在,通过使用以下命令运行 JAR 文件 −

Now, run the JAR file by using the following command −

java –jar <JARFILE>

这将启动 8080 端口上的应用程序,如下所示 −

This will start the application on the Tomcat port 8080 as shown below −

started application on tomcat port 8080

现在在 POSTMAN 应用程序中点击下方 URL,你就可以看到如下图所示的输出:

Now hit the below URL’s in POSTMAN application and you can see the output as shown below −

文件上传 − http://localhost:8080/upload

postman application file upload

文件下载 − http://localhost:8080/upload

File download − http://localhost:8080/upload

Spring Boot - Service Components

服务组件是包含 @Service 注解的类文件。这些类文件用于在不同层编写业务逻辑,与 @RestController 类文件分隔。此处显示创建服务组件类文件的逻辑:

Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here −

public interface ProductService {
}

实现 @Service 批注的接口的类如下所示:

The class that implements the Interface with @Service annotation is as shown −

@Service
public class ProductServiceImpl implements ProductService {
}

请注意,在本教程中,我们使用 Product Service API(s) 来存储、检索、更新和删除产品。我们在 @RestController 类文件中编写了业务逻辑。现在,我们要将业务逻辑代码从控制器移到服务组件。

Observe that in this tutorial, we are using Product Service API(s) to store, retrieve, update and delete the products. We wrote the business logic in @RestController class file itself. Now, we are going to move the business logic code from controller to service component.

你可以使用如下所示的代码创建一个包含添加、编辑、获取和删除方法的接口:

You can create an Interface which contains add, edit, get and delete methods using the code as shown below −

package com.tutorialspoint.demo.service;

import java.util.Collection;
import com.tutorialspoint.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();
}

以下代码可让你创建一个实现 ProdutoService 接口的类,用 @Service 批注,并编写业务逻辑来存储、检索、删除和更新产品。

The following code will let you to create a class which implements the ProductService interface with @Service annotation and write the business logic to store, retrieve, delete and updates the product.

package com.tutorialspoint.demo.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.tutorialspoint.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 控制器的类文件,在这里我们 @Autowired 了 ProdutoService 接口并调用了方法。

The code here show the Rest Controller class file, here we @Autowired the ProductService interface and called the methods.

package com.tutorialspoint.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.tutorialspoint.demo.model.Product;
import com.tutorialspoint.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 的代码:

The code for POJO class – Product.java is shown here −

package com.tutorialspoint.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 应用程序:

A main Spring Boot application is given below −

package com.tutorialspoint.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 的代码:

The code for Maven build – pom.xml is shown below −

<?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.tutorialspoint</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.gradle 的代码:

The code for Gradle Build – build.gradle is shown below −

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.tutorialspoint'
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 应用程序:

You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −

对于 Maven,使用如下所示的命令:

For Maven, use the command as shown below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,你可以使用如下所示的命令:

For Gradle, you can use the command as shown below −

gradle clean build

在 “BUILD SUCCESSFUL” 后,你可以在 build/libs 目录下找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory.

使用给出的命令运行 JAR 文件:

Run the JAR file by using the command given below −

java –jar <JARFILE>

现在,应用程序已经在 Tomcat 端口 8080 上启动,如下图所示:

Now, the application has started on the Tomcat port 8080 as shown in the image given below −

build successful

现在在 POSTMAN 应用程序中点击下方 URL,你就可以看到如下图所示的输出:

Now hit the below URL’s in POSTMAN application and you can see the output as shown below −

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

postman application get api url

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

postman application post api url
postman application put api url

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

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

postman application delete api url

Spring Boot - Thymeleaf

Thymeleaf 是一个基于 Java 的库,用于创建 Web 应用程序。它为在 Web 应用程序中使用 XHTML/HTML5 提供了良好的支持。在本章中,你将详细了解 Thymeleaf。

Thymeleaf is a Java-based library used to create a web application. It provides a good support for serving a XHTML/HTML5 in web applications. In this chapter, you will learn in detail about Thymeleaf.

Thymeleaf Templates

Thymeleaf 将你的文件转换为格式良好的 XML 文件。它包含 6 种类型的模板,如下所示 −

Thymeleaf converts your files into well-formed XML files. It contains 6 types of templates as given below −

  1. XML

  2. Valid XML

  3. XHTML

  4. Valid XHTML

  5. HTML5

  6. Legacy HTML5

除了传统 HTML5 之外,所有模板都指的是格式良好的有效的 XML 文件。传统 HTML5 允许我们在网页中呈现 HTML5 标签,包括未闭合的标签。

All templates, except Legacy HTML5, are referring to well-formed valid XML files. Legacy HTML5 allows us to render the HTML5 tags in web page including not closed tags.

Web Application

你可以使用 Thymeleaf 模板在 Spring Boot 中创建一个 Web 应用程序。你需要按照以下步骤使用 Thymeleaf 在 Spring Boot 中创建一个 Web 应用程序。

You can use Thymeleaf templates to create a web application in Spring Boot. You will have to follow the below steps to create a web application in Spring Boot by using Thymeleaf.

使用以下代码创建一个 @Controller 类文件,以便将请求 URI 重定向到 HTML 文件 −

Use the following code to create a @Controller class file to redirect the Request URI to HTML file −

package com.tutorialspoint.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 ,控制重定向到 index.html 文件。请注意,index.html 文件应放置在 templates 目录下,所有 JS 和 CSS 文件应放置在类路径中的 static 目录下。在所示示例中,我们使用 CSS 文件来更改文本颜色。

In the above example, the request URI is /index, and the control is redirected into the index.html file. Note that the index.html file should be placed under the templates directory and all JS and CSS files should be placed under the static directory in classpath. In the example shown, we used CSS file to change the color of the text.

你可以使用以下代码并在单独的文件夹 css 中创建一个 CSS 文件,并将文件命名为 styles.css −

You can use the following code and created a CSS file in separate folder css and name the file as styles.css −

h4 {
   color: red;
}

index.html 文件的代码如下 -

The code for index.html file is given below −

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

项目资源管理器显示在下方的截图中 −

The project explorer is shown in the screenshot given below −

project explorer screenshot

现在,我们需要在我们的构建配置文件中添加 Spring Boot Starter Thymeleaf 依赖。

Now, we need to add the Spring Boot Starter Thymeleaf dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加下列依赖 -

Maven users can add the following dependency into the pom.xml file −

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

Gradle 用户可以在 build.gradle 文件中添加下列依赖 -

Gradle users can add the following dependency in the build.gradle file −

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

Spring Boot 主应用程序类文件的代码如下 -

The code for main Spring Boot application class file is given below −

package com.tutorialspoint.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 的代码如下 -

The code for Maven – pom.xml is given below −

<?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.tutorialspoint</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 的代码如下 -

The code for Gradle – build.gradle is given below −

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.tutorialspoint'
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')
}

您可以创建一个可执行 JAR 文件,并通过使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 -

You can create an executable JAR file, and run the spring boot application by using the following Maven or Gradle commands −

对于 Maven,使用如下所示的命令:

For Maven, use the command as shown below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,像下面这样使用命令 -

For Gradle, use the command as shown below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用此处提供的命令运行 JAR 文件 −

Run the JAR file by using the command given here −

java –jar <JARFILE>

现在,应用程序在 Tomcat 端口 8080 上启动,如下所示 -

Now, the application has started on the Tomcat port 8080 as shown below −

started application on tomcat port 8080

现在在您的浏览器中输入 URL,您可以看到输出如下所示 −

Now hit the URL in your web browser and you can see the output as shown −

spring boot thymleaf web application

Consuming RESTful Web Services

本章将详细讨论如何使用 jQuery AJAX 处理 RESTful Web 服务。

This chapter will discuss in detail about consuming a RESTful Web Services by using jQuery AJAX.

创建一个简单的 Spring Boot Web 应用程序,并编写一个用于重定向到 HTML 文件的控制器类,用于处理 RESTful Web 服务。

Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services.

我们需要在构建配置文件中添加 Spring Boot 入门 Thymeleaf 和 Web 依赖项。

We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file.

对于 Maven 用户,请在您的 pom.xml 文件中添加以下依赖项。

For Maven users, add the below dependencies in your pom.xml file.

<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 文件中添加以下依赖项 -

For Gradle users, add the below dependencies into your build.gradle file −

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

@Controller 类文件的代码如下 -

The code for @Controller class file is given below −

@Controller
public class ViewController {
}

您可以定义请求 URI 方法以重定向到 HTML 文件,如下所示 -

You can define the Request URI methods to redirects into the HTML file as shown below −

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

此 API http://localhost:9090/products 应返回以下 JSON 作为响应,如下所示:

This API http://localhost:9090/products should return the below JSON in response as shown below −

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

现在,在类路径中 templates 目录下创建一个 view-products.html 文件。

Now, create a view-products.html file under the templates directory in the classpath.

在 HTML 文件中,我们添加了 jQuery 库并在页面加载时编写了代码来利用 RESTful Web 服务。

In the HTML file, we added the jQuery library and written the code to consume the RESTful web service on page load.

<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 应包含以下请求体和响应体。

The POST method and this URL http://localhost:9090/products should contains the below Request Body and Response body.

请求体的代码如下:

The code for Request body is given below −

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

响应体的代码如下:

The code for Response body is given below −

Product is created successfully

现在,在类路径中 templates 目录下创建 add-products.html 文件。

Now, create the add-products.html file under the templates directory in the classpath.

在 HTML 文件中,我们添加了 jQuery 库并编写了代码,以便在单击按钮时将表单提交到 RESTful Web 服务。

In the HTML file, we added the jQuery library and written the code that submits the form to RESTful web service on clicking the button.

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

完整的代码如下:

The complete code is given below.

Maven — pom.xml 文件

Maven – pom.xml file

<?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.tutorialspoint</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 的代码如下 -

The code for Gradle – build.gradle is given below −

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.tutorialspoint’
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 如下所示——

The controller class file given below – ViewController.java is given below −

package com.tutorialspoint.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-products.html 文件如下所示:

The view-products.html file is given below −

<!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-products.html 文件如下所示:

The add-products.html file is given below −

<!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 应用程序类文件如下所示:

The main Spring Boot Application class file is given below −

package com.tutorialspoint.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);
   }
}

现在,您可以创建一个可执行 JAR 文件,并使用以下 Maven 或 Gradle 命令运行 Spring 引导应用程序。

Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,使用如下所示的命令:

For Maven, use the command as given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用如下所示的命令:

For Gradle, use the command as given below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用以下命令运行 JAR 文件 −

Run the JAR file by using the following command −

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 8080 上启动。

Now, the application has started on the Tomcat port 8080.

started application on tomcat port 8080

现在在您的浏览器中输入 URL,您可以看到输出如下所示 −

Now hit the URL in your web browser and you can see the output as shown −

[role="bare"] [role="bare"]http://localhost:8080/view-products

1honey 2almond

[role="bare"] [role="bare"]http://localhost:8080/add-products

submit form spring boot

现在,单击按钮 Click here to submit the form ,您便可以看到结果,如下所示

Now, click the button Click here to submit the form and you can see the result as shown −

submit form spring boot output window

现在,点击查看产品网址,查看已创建的产品。

Now, hit the view products URL and see the created product.

1honey 2almond 3ginger

Angular JS

如需使用 Angular JS 消费 API,可以使用以下提供的示例 −

To consume the APIs by using Angular JS, you can use the examples given below −

使用以下代码创建 Angular JS 控制器以消费 GET API - http://localhost:9090/products

Use the following code to create the Angular JS Controller to consume the 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 控制器以消费 POST API - http://localhost:9090/products

Use the following code to create the Angular JS Controller to consume the 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");
   });
});

Note − Post 方法数据表示以 JSON 格式创建产品的请求正文。

Note − The Post method data represents the Request body in JSON format to create a product.

Spring Boot - CORS Support

跨源资源共享 (CORS) 是一种安全概念,允许限制在 Web 浏览器中实现的资源。它可以防止 JavaScript 代码针对不同的源创建或使用请求。

Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It prevents the JavaScript code producing or consuming the requests against different origin.

例如,如果你的 Web 应用程序正在 8080 端口运行,并且通过使用 JavaScript 尝试从 9090 端口使用 RESTful Web 服务。在这种情况下,你将在 Web 浏览器上遇到跨源资源共享安全问题。

For example, your web application is running on 8080 port and by using JavaScript you are trying to consuming RESTful web services from 9090 port. Under such situations, you will face the Cross-Origin Resource Sharing security issue on your web browsers.

需要两个条件来处理此问题 −

Two requirements are needed to handle this issue −

  1. RESTful web services should support the Cross-Origin Resource Sharing.

  2. RESTful web service application should allow accessing the API(s) from the 8080 port.

在本章中,我们将详细了解如何为 RESTful Web 服务应用程序启用跨源请求。

In this chapter, we are going to learn in detail about How to Enable Cross-Origin Requests for a RESTful Web Service application.

Enable CORS in Controller Method

我们需要通过 @CrossOrigin 为控制器方法添加注解来设置 RESTful Web 服务的来源。此 @CrossOrigin 注解支持特定的 REST API,而并非整个应用程序。

We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {
   return null;
}

Global CORS Configuration

我们需要定义所示的 @Bean 配置,以将 CORS 配置支持全局应用于你的 Spring Boot 应用程序。

We need to define the shown @Bean configuration to set the CORS configuration support globally to your Spring Boot application.

@Bean
public WebMvcConfigurer corsConfigurer() {
   return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/products").allowedOrigins("http://localhost:9000");
      }
   };
}

在 Spring Boot 主应用程序中全局设置 CORS 配置的代码如下所示。

To code to set the CORS configuration globally in main Spring Boot application is given below.

package com.tutorialspoint.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 服务应用程序。有关 RESTful Web 服务实现的更多详细信息,你可以参阅本教程中题为 Consuming RESTful Web Services 的章节。

Now, you can create a Spring Boot web application that runs on 8080 port and your RESTful web service application that can run on the 9090 port. For further details about implementation about RESTful Web Service, you can refer to the chapter titled Consuming RESTful Web Services of this tutorial.

Spring Boot - Internationalization

国际化是一个过程,它让你的应用程序能够适应不同的语言和地区,而无需对源代码进行工程更改。换句话说,国际化是本地化的准备就绪。

Internationalization is a process that makes your application adaptable to different languages and regions without engineering changes on the source code. In ither words, Internationalization is a readiness of Localization.

在本章中,我们将详细了解如何在 Spring Boot 中实现国际化。

In this chapter, we are going to learn in detail about How to implement the Internationalization in Spring Boot.

Dependencies

我们需要 Spring Boot Starter Web 和 Spring Boot Starter Thymeleaf 依赖项才能在 Spring Boot 中开发 Web 应用程序。

We need the Spring Boot Starter Web and Spring Boot Starter Thymeleaf dependency to develop a web application in Spring Boot.

Maven

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

We need to determine default Locale of your application. We need to add the LocaleResolver bean in our Spring Boot application.

@Bean
public LocaleResolver localeResolver() {
   SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
   sessionLocaleResolver.setDefaultLocale(Locale.US);
   return sessionLocaleResolver;
}

LocaleChangeInterceptor

LocaleChangeInterceptor 用于根据添加到请求的语言参数的值来更改新语言环境。

LocaleChangeInterceptor is a used to change the new Locale based on the value of the language parameter added to a request.

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
   LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
   localeChangeInterceptor.setParamName("language");
   return localeChangeInterceptor;
}

为了达到此效果,我们需要将 LocaleChangeInterceptor 添加到应用程序的注册拦截器中。配置类应该扩展 WebMvcConfigurerAdapter 类并覆盖 addInterceptors() 方法。

To take this effect, we need to add the LocaleChangeInterceptor into the application’s registry interceptor. The configuration class should extend the WebMvcConfigurerAdapter class and override the addInterceptors() method.

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

Messages Sources

Spring Boot 应用程序默认情况下从 classpath 下的 src/main/resources 文件夹获取消息源。默认区域消息文件名应该是 message.properties ,每个区域的文件都应该命名为 messages_XX.properties 。“XX” 表示区域代码。

Spring Boot application by default takes the message sources from src/main/resources folder under the classpath. The default locale message file name should be message.properties and files for each locale should name as messages_XX.properties. The “XX” represents the locale code.

所有消息属性都应该用作键值对。如果区域中找不到任何属性,应用程序将使用 messages.properties 文件中的默认属性。

All the message properties should be used as key pair values. If any properties are not found on the locale, the application uses the default property from messages.properties file.

默认的 messages.properties 将如下所示 −

The default messages.properties will be as shown −

welcome.text=Hi Welcome to Everyone

法语 messages_fr.properties 将如下所示 −

The French language messages_fr.properties will be as shown −

welcome.text=Salut Bienvenue à tous

Note − 消息源文件应该保存为 “UTF-8” 文件格式。

Note − Messages source file should be saved as “UTF-8” file format.

HTML file

在 HTML 文件中,使用语法 #{key} 从属性文件显示消息。

In the HTML file, use the syntax #{key} to display the messages from the properties file.

<h1 th:text = "#{welcome.text}"></h1>

完整的代码如下所示

The complete code is given below

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.tutorialspoint</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.tutorialspoint'
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 应用程序主类文件如下所示 −

The main Spring Boot application class file is given below −

package com.tutorialspoint.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);
   }
}

控制器类文件如下 −

The controller class file is given below −

package com.tutorialspoint.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";
   }
}

国际化配置类

Configuration class to support the Internationalization

package com.tutorialspoint.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 如下所示 −

The Message sources – messages.properties is as shown −

welcome.text = Hi Welcome to Everyone

消息来源—— message_fr.properties 如下所示 −

The Message sources – message_fr.properties is as shown −

welcome.text = Salut Bienvenue à tous

HTML 文件 locale.html 应放置在类路径模板目录下,如下所示 −

The HTML file locale.html should be placed under the templates directory on the classpath as shown −

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1"/>
      <title>Internationalization</title>
   </head>
   <body>
      <h1 th:text = "#{welcome.text}"></h1>
   </body>
</html>

你可以创建可执行 JAR 文件,并使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 −

You can create an executable JAR file, and run the Spring boot application by using the following Maven or Gradle commands −

对于 Maven,使用以下命令 −

For Maven, use the following command −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用以下命令 −

For Gradle, use the following command −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,使用命令运行 JAR 文件,如下所示 −

Now, run the JAR file by using the command as shown −

java –jar <JARFILE>

你将发现应用程序已在 Tomcat 端口 8080 上启动。

You will find that the application has started on the Tomcat port 8080.

started application on tomcat port 8080

现在在你的 Web 浏览器中点击 URL http://localhost:8080/locale ,你将看到以下输出 −

Now hit the URL http://localhost:8080/locale in your web browser and you can see the following output −

output web browser

URL http://localhost:8080/locale?language=fr 将为你提供以下输出 −

The URL http://localhost:8080/locale?language=fr will give you the output as shown −

output web browser salut bienvenue

Spring Boot - Scheduling

调度是一个针对特定时间段执行任务的过程。Spring 引导为在 Spring 应用程序上编写调度器提供了良好的支持。

Scheduling is a process of executing the tasks for the specific time period. Spring Boot provides a good support to write a scheduler on the Spring applications.

Java Cron Expression

Java Cron 表达式用于配置 CronTrigger 的实例,CronTrigger 是 org.quartz.Trigger 的子类。有关 Java cron 表达式的更多信息,您可以参考此链接 −

Java Cron expressions are used to configure the instances of CronTrigger, a subclass of org.quartz.Trigger. For more information about Java cron expression you can refer to this link −

@EnableScheduling 注解用于为应用程序启用调度程序。此注解应添加到主 Spring Boot 应用程序类文件中。

The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file.

@SpringBootApplication
@EnableScheduling

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

@Scheduled 注解用于在特定时间段内触发调度程序。

The @Scheduled annotation is used to trigger the scheduler for a specific time period.

@Scheduled(cron = "0 * 9 * * ?")
public void cronJobSch() throws Exception {
}

以下是一个示例代码,展示了如何从早上 9:00 开始到早上 9:59 结束的每天每分钟执行一次任务

The following is a sample code that shows how to execute the task every minute starting at 9:00 AM and ending at 9:59 AM, every day

package com.tutorialspoint.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 作业调度器任务都已执行。

The following screenshot shows how the application has started at 09:03:23 and for every one minute from that time the cron job scheduler task has executed.

cron job scheduler

Fixed Rate

固定频率调度程序用于在特定时间执行任务。它不会等待上一个任务完成。值应以毫秒为单位。示例代码如下所示:

Fixed Rate scheduler is used to execute the tasks at the specific time. It does not wait for the completion of previous task. The values should be in milliseconds. The sample code is shown here −

@Scheduled(fixedRate = 1000)
public void fixedRateSch() {
}

这里有一个在应用程序启动后每秒执行一次任务的示例代码:

A sample code for executing a task on every second from the application startup is shown here −

package com.tutorialspoint.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 启动的应用程序,之后每秒执行一次固定频率调度器任务。

Observe the following screenshot that shows the application that has started at 09:12:00 and after that every second fixed rate scheduler task has executed.

fixed rate scheduler task executed

Fixed Delay

固定延迟调度程序用于在特定时间执行任务。它应该等到上一个任务完成。值应以毫秒为单位。示例代码如下所示:

Fixed Delay scheduler is used to execute the tasks at a specific time. It should wait for the previous task completion. The values should be in milliseconds. A sample code is shown here −

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void fixedDelaySch() {
}

在此处,initialDelay 是任务在初始延迟值后第一次执行后的时间。

Here, the initialDelay is the time after which the task will be executed the first time after the initial delay value.

下面展示了一个从应用程序启动后 3 秒内每秒执行一次任务的示例:

An example to execute the task for every second after 3 seconds from the application startup has been completed is shown below −

package com.tutorialspoint.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 秒的每秒都执行固定延迟调度器任务。

Observe the following screenshot which shows the application that has started at 09:18:39 and after every 3 seconds, the fixed delay scheduler task has executed on every second.

fixed delay scheduler task executed

Spring Boot - Enabling HTTPS

默认情况下,Spring Boot 应用程序在应用程序启动时使用 HTTP 8080 端口。

By default, Spring Boot application uses HTTP 8080 port when the application starts up.

started application on tomcat port 8080

你需要执行以下步骤配置 Spring Boot 应用程序中的 HTTPS 和端口 443 −

You need to follow the steps given below to configure the HTTPS and the port 443 in Spring Boot application −

  1. Obtain the SSL certificate – Create a self-signed certificate or get one from a Certificate Authority

  2. Enable HTTPS and 443 port

Self-Signed Certificate

要创建自签名证书,Java 运行时环境自带证书管理实用程序 key tool。该实用程序用于创建自签名证书。在给定的代码中展示了这一点 −

To create a self-signed certificate, Java Run Time environment comes bundled with certificate management utility key tool. This utility tool is used to create a Self-Signed certificate. It is shown in the code given here −

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。

This code will generate a PKCS12 keystore file named as keystore.p12 and the certificate alias name is tomcat.

Configure HTTPS

我们需要在 application.properties 文件中提供服务器端口 443、密钥库文件路径、密钥库密码、密钥库类型和密钥别名。观察给定的代码 −

We need to provide the server port as 443, key-store file path, key-store-password, key-store-type and key alias name into the application.properties file. Observe the code given here −

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 −

You can use the following code if you are using YAML properties use below application.yml −

server:
   port: 443
   ssl:
      key-store: keystore.p12
      key-store-password: springboot
      keyStoreType: PKCS12
      keyAlias: tomcat

你可以创建一个可执行 JAR 文件,然后使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序。

You can create an executable JAR file, and run the spring boot application by using the following Maven or Gradle commands.

对于 Maven,可以使用以下命令:

For Maven, you can use the following command −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,你可以使用以下命令

For Gradle, you can use the command

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,通过使用以下命令运行 JAR 文件 −

Now, run the JAR file by using the following command −

java –jar <JARFILE>

现在,该应用程序已经使用 https(如下图所示)在 Tomcat 端口 443 上启动 −

Now, the application has started on the Tomcat port 443 with https as shown −

started application on tomcat port 443

Spring Boot - Eureka Server

Eureka 服务器是一个保存所有客户端服务应用程序的信息的应用程序。每个微服务将在 Eureka 服务器中进行注册,Eureka 服务器知道运行在每个端口和 IP 地址上的所有客户端应用程序。Eureka 服务器还可以被称为发现服务器。

Eureka Server is an application that holds the information about all client-service applications. Every Micro service will register into the Eureka server and Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server.

在本章中,我们将详细了解如何构建 Eureka 服务器。

In this chapter, we will learn in detail about How to build a Eureka server.

Building a Eureka Server

Eureka 服务器随 Spring Cloud 软件包提供。为此,我们需要开发 Eureka 服务器并在默认端口 8761 上运行它。

Eureka Server comes with the bundle of Spring Cloud. For this, we need to develop the Eureka server and run it on the default port 8761.

访问 Spring Initializer 主页 https://start.spring.io/ ,并使用 Eureka 服务器依赖项下载 Spring Boot 项目。它在下面屏幕截图中展示 −

Visit the Spring Initializer homepage https://start.spring.io/ and download the Spring Boot project with Eureka server dependency. It is shown in the screenshot below −

build eureka server

在 main Spring Boot 应用程序类文件中下载项目后,我们需要添加 @EnableEurekaServer 注释。@EnableEurekaServer 注释用于让您的 Spring Boot 应用程序充当 Eureka 服务器。

After downloading the project in main Spring Boot Application class file, we need to add @EnableEurekaServer annotation. The @EnableEurekaServer annotation is used to make your Spring Boot application acts as a Eureka Server.

main Spring Boot 应用程序类文件代码如下所示 −

The code for main Spring Boot application class file is as shown below −

package com.tutorialspoint.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 服务器依赖项。

Make sure Spring cloud Eureka server dependency is added in your build configuration file.

Maven 用户依赖项代码如下所示 −

The code for Maven user dependency is shown below −

<dependency>
<groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

Gradle 用户依赖项代码如下 −

The code for Gradle user dependency is given below −

compile('org.springframework.cloud:spring-cloud-starter-eureka-server')

完整的构建配置文件如下所示 −

The complete build configuration file is given below −

Maven pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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 服务器会将它自身注册到发现中。您应该将下面提供的配置添加到您的 application.properties 文件或 application.yml 文件中。

By default, the Eureka Server registers itself into the discovery. You should add the below given configuration into your application.properties file or application.yml file.

application.properties 文件如下 −

application.properties file is given below −

eureka.client.registerWithEureka = false
eureka.client.fetchRegistry = false
server.port = 8761

application.yml 文件如下 −

The application.yml file is given below −

eureka:
   client:
      registerWithEureka: false
      fetchRegistry: false
server:
   port: 8761

现在,您可以创建一个可执行 JAR 文件,并使用下面所示的 Maven 或 Gradle 命令运行 Spring Boot 应用程序 −

Now, you can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below −

对于 Maven,使用如下所示的命令:

For Maven, use the command as shown below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用下面显示的命令 −

For Gradle, you can use the command shown below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,通过使用以下命令运行 JAR 文件 −

Now, run the JAR file by using the following command −

 java –jar <JARFILE>

您可以发现应用程序已在 Tomcat 端口 8761 上启动,如下所示 −

You can find that the application has started on the Tomcat port 8761 as shown below −

application started on tomcat port 8761

现在,在您的网络浏览器中点击 URL http://localhost:8761/ ,您会发现 Eureka Server 在端口 8761 上运行,如下所示 −

Now, hit the URL http://localhost:8761/ in your web browser and you can find the Eureka Server running on the port 8761 as shown below −

eureka server running on port 8761

Service Registration with Eureka

在本教程中,你将详细了解如何将 Spring Boot 微服务应用程序注册到 Eureka Server 中。在注册该应用程序之前,请确保 Eureka Server 正在端口 8761 上运行,或者先构建 Eureka Server 然后运行它。有关构建 Eureka Server 的更多信息,你可以参考前一章。

In this chapter, you are going to learn in detail about How to register the Spring Boot Micro service application into the Eureka Server. Before registering the application, please make sure Eureka Server is running on the port 8761 or first build the Eureka Server and run it. For further information on building the Eureka server, you can refer to the previous chapter.

首先,你需要在我们的构建配置文件中添加以下依赖项来将微服务注册到 Eureka Server 中。

First, you need to add the following dependencies in our build configuration file to register the microservice with the Eureka server.

Maven 用户可以在 pom.xml 文件中添加以下依赖项 −

Maven users can add the following dependencies into the pom.xml file −

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

Gradle 用户可以在 build.gradle 文件中添加以下依赖项 −

Gradle users can add the following dependencies into the build.gradle file −

compile('org.springframework.cloud:spring-cloud-starter-eureka')

现在,我们需要在 Spring Boot 应用程序主类文件中添加 @EnableEurekaClient 注解。@EnableEurekaClient 注解让你的 Spring Boot 应用程序充当 Eureka 客户端。

Now, we need to add the @EnableEurekaClient annotation in the main Spring Boot application class file. The @EnableEurekaClient annotation makes your Spring Boot application act as a Eureka client.

Spring Boot 应用程序主类如下所示 −

The main Spring Boot application is as given below −

package com.tutorialspoint.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 micro service应用程序注册到 Eureka Server 中,我们需要在其 application.properties 文件或 application.yml 文件中添加以下配置并在其配置中指定 Eureka Server URL。

To register the Spring Boot application into Eureka Server we need to add the following configuration in our application.properties file or application.yml file and specify the Eureka Server URL in our configuration.

application.yml 文件的代码如下所示 −

The code for application.yml file is given below −

eureka:
   client:
      serviceUrl:
         defaultZone: http://localhost:8761/eureka
      instance:
      preferIpAddress: true
spring:
   application:
      name: eurekaclient

application.properties 文件的代码如下所示 −

The code for application.properties file is given below −

eureka.client.serviceUrl.defaultZone  = http://localhost:8761/eureka
eureka.client.instance.preferIpAddress = true
spring.application.name = eurekaclient

现在,添加 Rest Endpoint 在 Spring Boot 应用程序中返回字符串,以及 Spring Boot Starter web 依赖项在构建配置文件中。观察以下给出的代码 −

Now, add the Rest Endpoint to return String in the main Spring Boot application and the Spring Boot Starter web dependency in build configuration file. Observe the code given below −

package com.tutorialspoint.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";
   }
}

整个配置文件如下所示。

The entire configuration file is given below.

For Maven user - pom.xml

For Maven user - 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.tutorialspoint</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>

For Gradle user – build.gradle

For Gradle user – 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.tutorialspoint'
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}"
   }
}

您可以创建一个可执行 JAR 文件并使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 -

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −

对于 Maven,可以使用以下命令:

For Maven, you can use the following command −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,可以使用以下命令:

For Gradle, you can use the following command −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,使用命令运行 JAR 文件,如下所示 −

Now, run the JAR file by using the command as shown −

java –jar <JARFILE>

现在,该应用程序已经使用 https(如下图所示)在 Tomcat 端口 8080 上启动,并且 Eureka Client 应用程序已经注册到 Eureka Server 中 −

Now, the application has started on the Tomcat port 8080 and Eureka Client application is registered with the Eureka Server as shown below −

started application on tomcat port

访问 URL [role="bare"] [role="bare"]http://localhost:8761/ 中的 Web 浏览器,你就可以看到 Eureka Client 应用程序已注册到 Eureka Server 中。

Hit the URL [role="bare"]http://localhost:8761/ in your web browser and you can see the Eureka Client application is registered with Eureka Server.

eureka client application

现在在你的网页浏览器中点击 URL http://localhost:8080/ 并查看 rest 端点的输出。

Now hit the URL http://localhost:8080/ in your web browser and see the Rest Endpoint output.

eureka client application output

Spring Boot - Zuul Proxy Server and Routing

Zuul 服务器是一个网关应用程序,处理所有请求并对微服务应用程序进行动态路由。Zuul 服务器也被称为边缘服务器。

Zuul Server is a gateway application that handles all the requests and does the dynamic routing of microservice applications. The Zuul Server is also known as Edge Server.

例如, /api/user 映射到用户服务,/api/products 映射到产品服务,Zuul 服务器将动态地将请求路由到各自的后端应用程序。

For Example, /api/user is mapped to the user service and /api/products is mapped to the product service and Zuul Server dynamically routes the requests to the respective backend application.

在本章中,我们将详细地了解如何在 Spring Boot 中创建 Zuul 服务器应用程序。

In this chapter, we are going to see in detail how to create Zuul Server application in Spring Boot.

Creating Zuul Server Application

Zuul 服务器与 Spring Cloud 依赖项捆绑在一起。你可以从 Spring Initializer 页面 https://start.spring.io/ 下载 Spring Boot 项目,并选择 Zuul 服务器依赖项。

The Zuul Server is bundled with Spring Cloud dependency. You can download the Spring Boot project from Spring Initializer page https://start.spring.io/ and choose the Zuul Server dependency.

creating zuul server application

在你的 Spring Boot 主应用程序中添加 @EnableZuulProxy 注释。@EnableZuulProxy 注释用于让你的 Spring Boot 应用程序充当 Zuul 代理服务器。

Add the @EnableZuulProxy annotation on your main Spring Boot application. The @EnableZuulProxy annotation is used to make your Spring Boot application act as a Zuul Proxy server.

package com.tutorialspoint.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 依赖项。

You will have to add the Spring Cloud Starter Zuul dependency in our build configuration file.

Maven 用户必须在你的 pom.xml 文件中添加以下依赖项:

Maven users will have to add the following dependency in your pom.xml file −

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>

对于 Gradle 用户,在你的 build.gradle 文件中添加以下依赖项:

For Gradle users, add the below dependency in your build.gradle file

compile('org.springframework.cloud:spring-cloud-starter-zuul')

对于 Zuul 路由,在你的 application.properties 文件或 application.yml 文件中添加以下属性。

For Zuul routing, add the below properties in your application.properties file or application.yml file.

spring.application.name = zuulserver
zuul.routes.products.path = /api/demo/**
zuul.routes.products.url = http://localhost:8080/
server.port = 8111

这意味着对 /api/demo/ 的 http 调用被转发到产品服务。例如, /api/demo/products 被转发到 /products

This means that http calls to /api/demo/ get forwarded to the products service. For example, /api/demo/products is forwarded to /products.

yaml 文件用户可以使用下面所示的 application.yml 文件:

yaml file users can use the application.yml file shown below −

server:
   port: 8111
spring:
   application:
      name: zuulserver
zuul:

routes:
   products:
      path: /api/demo/**
      url: http://localhost:8080/

Note - 在通过 Zuul 代理路由之前, http://localhost:8080/ 应用程序应该已经运行。

Note − The http://localhost:8080/ application should already be running before routing via Zuul Proxy.

完整的构建配置文件如下所示。

The complete build configuration file is given below.

Maven 用户可以使用下面给出的 pom.xml 文件:

Maven users can use the pom.xml file given below −

<?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.tutorialspoint</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 文件,如下所示 −

Gradle users can use the build.gradle file given below −

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.tutorialspoint'
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 应用程序:

You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −

对于 Maven,你可以使用下面给出的命令 −

For Maven, you can use the command given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,你可以使用下面给出的命令:

For Gradle, you can use the command given below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,使用如下所示的命令运行 JAR 文件:

Now, run the JAR file by using the command shown below −

java –jar <JARFILE>

你可以在此处看到应用程序已经启动,端口为 Tomcat 端口 8111。

You can find the application has started on the Tomcat port 8111 as shown here.

started application on tomcat port 8111

现在,在你的网页浏览器中点击 URL http://localhost:8111/api/demo/products ,你可以看到 /products REST 端点的输出,如下所示:

Now, hit the URL http://localhost:8111/api/demo/products in your web browser and you can see the output of /products REST Endpoint as shown below −

products rest endpoint

Spring Boot - Cloud Configuration Server

Spring Cloud 配置服务器是一个管理所有应用程序相关配置属性的集中式应用程序。在本章,您将详细了解如何创建 Spring Cloud 配置服务器。

Spring Cloud Configuration Server is a centralized application that manages all the application related configuration properties. In this chapter, you will learn in detail about how to create Spring Cloud Configuration server.

Creating Spring Cloud Configuration Server

首先,从 Spring Initializer 页面下载 Spring Boot 项目,并选择 Spring Cloud Config Server 依赖。观察以下给出的屏幕截图 −

First, download the Spring Boot project from the Spring Initializer page and choose the Spring Cloud Config Server dependency. Observe the screenshot given below −

creating spring cloud configuration server

现在,在构建配置文件中添加 Spring Cloud 配置服务器依赖,具体解释如下 −

Now, add the Spring Cloud Config server dependency in your build configuration file as explained below −

Maven 用户可以在 pom.xml 文件中添加以下依赖。

Maven users can add the below dependency into the pom.xml file.

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-config-server</artifactId>
</dependency>

Gradle 用户可以在 build.gradle 文件中添加下面的依赖关系。

Gradle users can add the below dependency in your build.gradle file.

compile('org.springframework.cloud:spring-cloud-config-server')

现在,在你的 Spring Boot 应用程序主类文件中添加 @EnableConfigServer 注释。@EnableConfigServer 注释使你的 Spring Boot 应用程序充当配置服务器。

Now, add the @EnableConfigServer annotation in your main Spring Boot application class file. The @EnableConfigServer annotation makes your Spring Boot application act as a Configuration Server.

Spring Boot 应用程序主类文件如下所示 −

The main Spring Boot application class file is given below −

package com.tutorialspoint.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 文件。观察下面给出的代码 −

Now, add the below configuration to your properties file and replace the application.properties file into bootstrap.properties file. Observe the code given below −

server.port = 8888
spring.cloud.config.server.native.searchLocations=file:///C:/configprop/
SPRING_PROFILES_ACTIVE=native

配置服务器在 Tomcat 8888 端口上运行,并且应用程序配置属性从本地搜索位置加载。

Configuration Server runs on the Tomcat port 8888 and application configuration properties are loaded from native search locations.

现在,在 file:///C:/configprop/ 中放置您的客户端应用程序应用程序。properties 文件。例如,您的客户端应用程序名称为 config-client ,然后将您的 application.properties 文件重命名为 config-client.properties 并将属性文件放置在路径 file:///C:/configprop/ 上。

Now, in file:///C:/configprop/, place your client application - application.properties file. For example, your client application name is config-client, then rename your application.properties file as config-client.properties and place the properties file on the path file:///C:/configprop/.

config-client 属性文件的代码如下所示 −

The code for config-client properties file is given below −

welcome.message = Welcome to Spring cloud config server

完整的构建配置文件如下所示 −

The complete build configuration file is given below −

Maven 用户可以在下面使用 pom.xml

Maven users can use pom.xml given below −

<?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.tutorialspoint</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 文件,如下所示 −

Gradle users can use the build.gradle file given below −

<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.tutorialspoint'
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 应用程序 −

Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −

对于 Maven,使用以下给出的命令 −

For Maven, use the command given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用以下给出的命令 −

For Gradle, use the command given below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用以下命令运行 JAR 文件 −

Run the JAR file by using the following command −

 java –jar <JARFILE>

现在,该应用程序已在 Tomcat 8888 端口上启动,如下所示 −

Now, the application has started on the Tomcat port 8888 as shown here −

tomcat port 8888 output

现在,在您的 Web 浏览器中点击 URL http://localhost:8888/config-client/default/master ,您将可以看到您的 config-client 应用程序配置属性,如下所示。

Now hit the URL http://localhost:8888/config-client/default/master on your web browser and you can see your config-client application configuration properties as shown here.

config client application

Spring Boot - Cloud Configuration Client

一些应用程序可能需要需要更改的配置属性,开发人员可能需要将它们关闭或重启应用程序来执行此操作。然而,这可能会导致生产中的停机时间和重启应用程序的需要。Spring Cloud Configuration Server 允许开发人员在不重启应用程序和不产生任何停机时间的情况下加载新的配置属性。

Some applications may need configuration properties that may need a change and developers may need to take them down or restart the application to perform this. However, this might be lead to downtime in production and the need of restarting the application. Spring Cloud Configuration Server lets developers to load the new configuration properties without restarting the application and without any downtime.

Working with Spring Cloud Configuration Server

首先,从 https://start.spring.io/ 下载 Spring Boot 项目,并选择 Spring Cloud Config Client 依赖项。现在,在你的构建配置文件中添加 Spring Cloud Starter Config 依赖项。

First, download the Spring Boot project from https://start.spring.io/ and choose the Spring Cloud Config Client dependency. Now, add the Spring Cloud Starter Config dependency in your build configuration file.

Maven 用户可以将下面的依赖项添加到 pom.xml 文件中。

Maven users can add the following dependency into the pom.xml file.

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

Gradle 用户可以将下面的依赖项添加到 build.gradle 文件中。

Gradle users can add the following dependency into the build.gradle file.

compile('org.springframework.cloud:spring-cloud-starter-config')

现在,您需要将 @RefreshScope 注解添加到您的 Spring Boot 主应用程序中。@RefreshScope 注解用于从配置服务器中加载配置属性值。

Now, you need to add the @RefreshScope annotation to your main Spring Boot application. The @RefreshScope annotation is used to load the configuration properties value from the Config server.

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,并提供您的应用程序名称。

Now, add the config server URL in your application.properties file and provide your application name.

Note − [role="bare"] [role="bare"]http://localhost:8888 配置服务器应在启动配置客户端应用程序之前运行。

Note − [role="bare"]http://localhost:8888 config server should be run before starting the config client application.

spring.application.name = config-client
spring.cloud.config.uri = http://localhost:8888

下面给出了用于编写一个简单的 REST 端点以从配置服务器读取欢迎消息的代码 −

The code for writing a simple REST Endpoint to read the welcome message from the configuration server is given below −

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;
   }
}

您可以创建一个可执行 JAR 文件并使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 -

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −

对于 Maven,您可以使用下面所示的命令 −

For Maven, you can use the command shown below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用下面显示的命令 −

For Gradle, you can use the command shown below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,使用此处所示的命令运行 JAR 文件:

Now, run the JAR file by using the command shown here:

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 8080 上启动,如下所示 −

Now, the application has started on the Tomcat port 8080 as shown here −

started application on tomcat port 8080

您可以在控制台窗口中看到日志;配置客户端应用程序正在从 https://localhost:8888 中获取配置

You can see the log in console window; config-client application is fetching the configuration from the https://localhost:8888

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/ 欢迎消息从配置服务器加载。

Now hit the URL, http://localhost:8080/ welcome message is loaded from the Configuration server.

spring cloud config server

现在,进入配置服务器更改属性值,然后点击执行器端点 POST URL http://localhost:8080/refresh ,并在 URL http://localhost:8080/ 中查看新配置属性值

Now, go and change the property value on the Configuration server and hit the actuator Endpoint POST URL http://localhost:8080/refresh and see the new configuration property value in the URL http://localhost:8080/

Spring Boot - Actuator

Spring Boot Actuator 为监视和管理您的 Spring Boot 应用程序提供了安全端点。默认情况下,所有 actuator 端点都是安全的。本章将详细介绍如何为您的应用程序启用 Spring Boot actuator。

Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. By default, all actuator endpoints are secured. In this chapter, you will learn in detail about how to enable Spring Boot actuator to your application.

Enabling Spring Boot Actuator

要为 Spring Boot 应用程序启用 Spring Boot actuator 端点,我们需要在我们的构建配置文件中添加 Spring Boot Starter actuator 依赖项。

To enable Spring Boot actuator endpoints to your Spring Boot application, we need to add the Spring Boot Starter actuator dependency in our build configuration file.

Maven 用户可以在您的 pom.xml 文件中添加以下依赖项。

Maven users can add the below dependency in your pom.xml file.

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

Gradle 用户可以在 build.gradle 文件中添加下面的依赖关系。

Gradle users can add the below dependency in your build.gradle file.

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

在 application.properties 文件中,我们需要禁用执行器端点的安全性。

In the application.properties file, we need to disable the security for actuator endpoints.

management.security.enabled = false

YAML 文件用户可以在 application.yml 文件中添加以下属性。

YAML file users can add the following property in your application.yml file.

management:
   security:
      enabled: false

如果您想使用单独的端口号来访问 Spring 引导执行器端点,请在 application.properties 文件中添加管理端口号。

If you want to use the separate port number for accessing the Spring boot actutator endpoints add the management port number in application.properties file.

management.port = 9000

YAML 文件用户可以在 application.yml 文件中添加以下属性。

YAML file users can add the following property in your application.yml file.

management:
   port: 9000

现在,您可以创建一个可执行 JAR 文件,并使用以下 Maven 或 Gradle 命令运行 Spring 引导应用程序。

Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,可以使用以下命令:

For Maven, you can use the following command −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,可以使用以下命令:

For Gradle, you can use the following command −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,您可以使用以下命令运行 JAR 文件:

Now, you can run the JAR file by using the following command −

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 8080 上启动。请注意,如果您指定了管理端口号,则同一个应用程序将运行在两个不同的端口号上。

Now, the application has started on the Tomcat port 8080. Note that if you specified the management port number, then same application is running on two different port numbers.

started application on tomcat port

下面给出了几个重要的 Spring 引导执行器端点。您可以在 Web 浏览器中输入它们并监控您的应用程序行为。

Some important Spring Boot Actuator endpoints are given below. You can enter them in your web browser and monitor your application behavior.

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 - Admin Server

使用 Spring Boot Actuator 端点监控您的应用程序有点困难。这是因为,如果您有“n”个应用程序,则每个应用程序都有单独的执行器端点,从而使监控变得困难。Spring Boot Admin Server 是一款用于管理和监控您的微服务应用程序的应用程序。

Monitoring your application by using Spring Boot Actuator Endpoint is slightly difficult. Because, if you have ‘n’ number of applications, every application has separate actuator endpoints, thus making monitoring difficult. Spring Boot Admin Server is an application used to manage and monitor your Microservice application.

为了处理这种情况,CodeCentric Team 提供了一个 Spring Boot Admin UI 来管理和监控所有 Spring Boot 应用程序执行器端点,并集中在一个地方。

To handle such situations, CodeCentric Team provides a Spring Boot Admin UI to manage and monitor all your Spring Boot application Actuator endpoints at one place.

对于构建 Spring Boot Admin Server,我们需要在构建配置文件中添加以下依赖项。

For building a Spring Boot Admin Server we need to add the below dependencies in your build configuration file.

Maven 用户可以在其 pom.xml 文件中添加以下依赖项 −

Maven users can add the below dependencies in your pom.xml file −

<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 文件中添加以下依赖项 −

Gradle users can add the below dependencies in your build.gradle file −

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 注解用于将您作为 Admin Server 来监控所有其他微服务。

Add the @EnableAdminServer annotation in your main Spring Boot application class file. The @EnableAdminServer annotation is used to make your as Admin Server to monitor all other microservices.

package com.tutorialspoint.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 和应用程序名称,如下所示 −

Now, define the server.port and application name in application.properties file a shown −

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

对于 YAML 用户,使用下列属性来在 application.yml 文件中定义端口号和应用程序名。

For YAML users, use the following properties to define the port number and application name in application.yml file.

server:
   port: 9090
spring:
   application:
      name: adminserver

构建配置文件如下。

The build configuration file is given below.

For Maven users – pom.xml

For Maven users – 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.tutorialspoint</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>

For Gradle users – build.gradle file

For Gradle users – build.gradle file

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.tutorialspoint'
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')
}

您可以创建一个可执行 JAR 文件并使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 -

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −

对于 Maven,使用此处所示命令 −

For Maven, use the command shown here −

mvn clean install

在“构建成功”后,您可以在 target 目录下找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under target directory.

对于 Gradle,使用此处所示命令 −

For Gradle, use the command shown here −

gradle clean build

在 “BUILD SUCCESSFUL” 后,你可以在 build/libs 目录下找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory.

现在,运行 JAR 文件,使用如下所示命令 −

Now, run the JAR file by using the command given below −

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 9090 上启动,如下所示 −

Now, the application has started on the Tomcat port 9090 as shown here −

tomcat port 9090 output

现在从 Web 浏览器访问以下 URL,查看 Admin Server UI。

Now hit the below URL from your web browser and see the Admin Server UI.

web browser admin server ui

Spring Boot - Admin Client

要通过 Spring Boot Admin Server 监控和管理微服务应用程序,您应该添加 Spring Boot Admin Starter 客户端依赖项并在应用程序属性文件中指出 Admin Server URI。

For monitoring and managing your microservice application via Spring Boot Admin Server, you should add the Spring Boot Admin starter client dependency and point out the Admin Server URI into the application properties file.

Note - 为了监控应用程序,您应该为您的微服务应用程序启用 Spring Boot Actuator 端点。

Note − For monitoring an application, you should enable the Spring Boot Actuator Endpoints for your Microservice application.

首先,在您的构建配置中添加以下 Spring Boot Admin starter 客户端依赖项和 Spring Boot starter actuator 依赖项。

First, add the following Spring Boot Admin starter client dependency and Spring Boot starter actuator dependency in your build configuration file.

Maven 用户可以在您的 pom.xml 文件中添加以下依赖项 -

Maven users can add the following dependencies in your pom.xml file −

<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 文件中添加以下依赖项。

Gradle users can add the following dependencies in your build.gradle file.

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 添加到您的应用程序属性文件中。

Now, add the Spring Boot Admin Server URL into your application properties file.

对于属性文件用户,在 application.properties 文件中添加以下属性。

For properties file users, add the following properties in the application.properties file.

spring.boot.admin.url = http://localhost:9090/

对于 YAML 用户,在 application.yml 文件中添加以下属性。

For YAML users, add the following property in application.yml file.

spring:
   boot:
      admin:
         url: http://localhost:9000/

现在,创建一个可执行 JAR 文件,并使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序。

Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,您可以使用如下命令:−

For Maven, you can use the command as shown −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用如下命令:−

For Gradle, you can use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,运行 JAR 文件,使用所示命令 −

Now, run the JAR file by using the command shown −

java –jar <JARFILE>

现在,应用程序已经启动在 Tomcat 端口 9090 中,具体如下所示:

Now, the application has started on the Tomcat port 9090 as shown −

tomcat port 9090 output

现在,从网络浏览器访问以下网址,查看您的 Spring Boot 应用程序已经注册于 Spring Boot Admin Server。

Now hit the following URL from your web browser and see your spring Boot application is registered with Spring Boot Admin Server.

spring boot admin server

现在,点击 Details 按钮,然后在 Admin Server UI 中查看执行器端点。

Now, click the Details button and the see the actuator endpoints in Admin Server UI.

actuator endpoints in admin server ui

Spring Boot - Enabling Swagger2

Swagger2 是一个用于为 RESTful Web 服务生成 REST API 文档的开源项目。它提供了一个用户界面,能够通过网络浏览器访问我们的 RESTful Web 服务。

Swagger2 is an open source project used to generate the REST API documents for RESTful web services. It provides a user interface to access our RESTful web services via the web browser.

要启用 Spring Boot 应用程序中的 Swagger2,您需要在我们的构建配置中添加以下依赖项。

To enable the Swagger2 in Spring Boot application, you need to add the following dependencies in our build configurations file.

<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 文件中添加以下依赖项。

For Gradle users, add the following dependencies in your build.gradle file.

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。

Now, add the @EnableSwagger2 annotation in your main Spring Boot application. The @EnableSwagger2 annotation is used to enable the Swagger2 for your Spring Boot application.

主要 Spring Boot 应用程序的代码如下所示:

The code for main Spring Boot application is shown below −

package com.tutorialspoint.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。我们需要定义基本包以配置 REST API 以供 Swagger2 使用。

Next, create Docket Bean to configure Swagger2 for your Spring Boot application. We need to define the base package to configure REST API(s) for Swagger2.

@Bean
   public Docket productApi() {
      return new Docket(DocumentationType.SWAGGER_2).select()
         .apis(RequestHandlerSelectors.basePackage("com.tutorialspoint.swaggerdemo")).build();
   }

现在,将此 Bean 添加到 Spring Boot 主应用程序类文件中,您的 Spring Boot 主应用程序类将如下所示:

Now, add this bean in main Spring Boot application class file itself and your main Spring Boot application class will look as shown below −

package com.tutorialspoint.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.tutorialspoint.swaggerdemo")).build();
   }
}

现在,在您的构建配置文件中添加以下 Spring Boot Starter Web 依赖项以编写 REST 端点,具体如下所示:

Now, add the below Spring Boot Starter Web dependency in your build configuration file to write a REST Endpoints as shown below −

Maven 用户可以在他们的 pom.xml 文件中添加以下依赖 −

Maven users can add the following dependency in your pom.xml file −

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

Gradle 用户可以在 build.gradle 文件中添加以下依赖项:

Gradle users can add the following dependency in build.gradle file −

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

现在,通过如下所示,此处展示了在 Rest Controller 文件中构建两个简单的 RESTful Web 服务 GET 和 POST 的代码:

Now, the code to build two simple RESTful web services GET and POST in Rest Controller file is shown here −

package com.tutorialspoint.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";
   }
}

完整的构建配置文件如下所示 −

The complete build configuration file is given below −

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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'
}

您可以创建一个可执行 JAR 文件,并通过使用以下 Maven 或 Gradle 命令来运行 Spring Boot 应用程序。

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,您可以使用此处所示的命令:

For Maven, you can use the command shown here −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用此处所示的命令:

For Gradle, you can use the command as shown here −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,通过使用此处所示命令运行 JAR 文件:

Now, run the JAR file by using the command shown here −

java –jar <JARFILE>

现在,应用程序将启动在 Tomcat 端口 8080 中,具体如下所示:

Now, the application will start on the Tomcat port 8080 as shown −

started application on tomcat port 8080

现在,在您的网络浏览器中访问该 URL,然后查看 Swagger API 功能。

Now, hit the URL in your web browser and see the Swagger API functionalities.

swagger api functionalities

Spring Boot - Creating Docker Image

Docker 是一种容器管理服务,可简化构建和部署。如果您是 Docker 新手,可以从以下链接详细了解它: [role="bare" [role="bare"]https://www.tutorialspoint.com/docker/index.htm ]

Docker is a container management service that eases building and deployment. If you are a beginner to Docker, you can learn about is in detail at this link − [role="bare"https://www.tutorialspoint.com/docker/index.htm]

在本章中,我们将了解如何使用 Spring Boot 应用程序的 Maven 和 Gradle 依赖关系创建 Docker 镜像。

In this chapter, we are going to see How to create a Docker image by using Maven and Gradle dependencies for your Spring Boot application.

Create Dockerfile

首先,在目录 src/main/docker 下创建名称为 Dockerfile 的文件,内容如下所示。请注意,此文件对于创建 Docker 镜像非常重要。

First, create a file with the name Dockerfile under the directories src/main/docker with the contents shown below. Note that this file is important to create a Docker image.

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

对于 Maven,将 Docker Maven 插件添加到构建配置文件 pom.xml

For Maven, add the Docker Maven plugin into your build configuration file pom.xml

<properties>
   <docker.image.prefix>spring-boot-tutorialspoint</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 文件如下所示:

The complete pom.xml file is given below −

<?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.tutorialspoint</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-tutorialspoint</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

Now, you can run your application by using the Maven command mvn package docker:build

mvn package docker build

Note - 在 tcp://localhost:2375 上启用公开守护进程,不使用 TLS。

Note − Enable the Expose daemon on tcp://localhost:2375 without TLS.

构建成功后,您可以在控制台看到输出,如下所示:

After build success, you can see the output on the console as shown below −

mvn package docker output

现在,通过使用 docker images 命令查看 Docker 镜像并在控制台上查看镜像信息。

Now, see the Docker images by the command using docker images and see the image info on the console.

docker images command

Gradle

要使用 Gradle 构建配置构建 Docker 镜像,我们需要添加 docker 插件并编写任务 buildDocker 以创建 Docker 镜像。

To build a Docker image by using Gradle build configuration, we need to add the docker plugin and need to write a task buildDocker to create a Docker image.

Gradle Docker 配置的代码如下所示。

The code for Gradle Docker configuration is given below.

buildscript {
   .....
   dependencies {
      .....
      classpath('se.transmode.gradle:gradle-docker:1.2')
   }
}

group = 'spring-boot-tutorialspoint'

.....
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 文件如下所示。

The complete build.gradle file is given below.

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-tutorialspoint'

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

group = 'com.tutorialspoint'
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 镜像:

Now, create a Docker image by using the command shown below −

gradle build buildDocker
gradle build docker

执行命令后,您可以在控制台窗口上看到 BUILD SUCCESSFUL 日志。

After executing the command, you can see the BUILD SUCCESSFUL log on the console window.

docker build successful

现在,通过使用 docker images 命令查看 Docker 镜像并在控制台上查看镜像的信息。

Now, see the Docker images by the command using docker images and see the image’s info on the console.

get image info using dockerimages

Spring Boot - Tracing Micro Service Logs

如果出现任何问题,大多数开发人员都面临着跟踪日志的困难。这个问题可以通过弹簧云 Sleuth 和 ZipKin 服务器解决,以用于弹簧启动应用程序。

Most developers face difficulty of tracing logs if any issue occurred. This can be solved by Spring Cloud Sleuth and ZipKin server for Spring Boot application.

Spring Cloud Sleuth

弹簧云 Sleuth 日志以以下格式打印 −

Spring cloud Sleuth logs are printed in the following format −

[application-name,traceid,spanid,zipkin-export]

其中,

Where,

  1. Application-name = Name of the application

  2. Traceid = each request and response traceid is same when calling same service or one service to another service.

  3. Spanid = Span Id is printed along with Trace Id. Span Id is different every request and response calling one service to another service.

  4. Zipkin-export = By default it is false. If it is true, logs will be exported to the Zipkin server.

现在,按照如下所示在您的构建配置文件中添加 Spring Cloud Starter Sleuth 依赖项 −

Now, add the Spring Cloud Starter Sleuth dependency in your build configuration file as follows −

Maven 用户可以在他们的 pom.xml 文件中添加以下依赖 −

Maven users can add the following dependency in your pom.xml file −

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>

Gradle 用户可以在他们的 build.gradle 文件中添加以下依赖 −

Gradle users can add the following dependency in your build.gradle file −

compile('org.springframework.cloud:spring-cloud-starter-sleuth')

现在,按照此处所示,将日志添加到您的 Spring Boot 应用程序 Rest 控制器类文件中 −

Now, add the Logs into your Spring Boot application Rest Controller class file as shown here −

package com.tutorialspoint.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 文件中添加应用程序名称 −

Now, add the application name in application.properties file as shown −

spring.application.name = tracinglogs

完整构建配置文件的代码如下所示 −

The complete code for build configuration file is given below −

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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}"
   }
}

您可以创建一个可执行 JAR 文件,并通过使用以下 Maven 或 Gradle 命令来运行 Spring Boot 应用程序。

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,可以使用以下命令:

For Maven, you can use the following command −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,可以使用以下命令:

For Gradle, you can use the following command −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,通过使用此处所示命令运行 JAR 文件:

Now, run the JAR file by using the command shown here −

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 8080 上启动。

Now, the application has started on the Tomcat port 8080.

started application on tomcat port 8080

现在,在 Web 浏览器中按 URL 并查看控制台日志中的输出。

Now, hit the URL in your web browser and see the output in console log.

output welcome sleuth

您可以在控制台窗口中看到以下日志。注意,日志采用以下格式打印 [应用程序名称、traceid、spanid、zipkin-export]

You can see the following logs in the console window. Observe that log is printed in the following format [application-name, traceid, spanid, zipkin-export]

log is printed

Zipkin Server

Zipkin 是一个监视和管理 Spring Boot 应用程序的 Spring Cloud Sleuth 日志的应用程序。要构建一个 Zipkin 服务器,我们需要在构建配置文件中添加 Zipkin UI 和 Zipkin Server 依赖。

Zipkin is an application that monitors and manages the Spring Cloud Sleuth logs of your Spring Boot application. To build a Zipkin server, we need to add the Zipkin UI and Zipkin Server dependencies in our build configuration file.

Maven 用户可以在他们的 pom.xml 文件中添加以下依赖 −

Maven users can add the following dependency in your pom.xml file −

<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 文件中添加如下依赖:

Gradle users can add the below dependency in your build.gradle file −

compile('io.zipkin.java:zipkin-autoconfigure-ui')
compile('io.zipkin.java:zipkin-server')

现在,在应用程序属性文件中配置 server.port = 9411。

Now, configure the server.port = 9411 in application properties file.

对于属性文件用户,在 application.properties 文件中添加以下属性。

For properties file users, add the below property in application.properties file.

server.port = 9411

对于 YAML 用户,在 application.yml 文件中添加以下属性。

For YAML users, add the below property in application.yml file.

server:
   port: 9411

在您的主 Spring Boot 应用程序类文件中添加 @EnableZipkinServer 注解。@EnableZipkinServer 注解用于启用您的应用程序充当 Zipkin 服务器。

Add the @EnableZipkinServer annotation in your main Spring Boot application class fie. The @EnableZipkinServer annotation is used to enable your application act as a Zipkin server.

package com.tutorialspoint.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);
   }
}

完整构建配置文件的代码如下所示。

The code for complete build configuration file is given below.

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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 应用程序:

You can create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands −

对于 Maven,使用以下给出的命令 −

For Maven, use the command given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用以下给出的命令 −

For Gradle, use the command given below −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用显示的命令运行 JAR 文件 −

Run the JAR file by using the command shown −

java –jar <JARFILE>

现在,应用程序已在 Tomcat 端口 9411 上启动,如下所示 −

Now, the application has started on the Tomcat port 9411 as shown below −

output tomcat port 9411

现在,点击下面的 URL 并查看 Zipkin 服务器 UI。

Now, hit the below URL and see the Zipkin server UI.

zipkin server ui

然后,在客户端服务应用程序中添加以下依赖,并指出 Zipkin 服务器 URL 以通过 Zipkin UI 追踪微服务日志。

Then, add the following dependency in your client service application and point out the Zipkin Server URL to trace the microservice logs via Zipkin UI.

现在,在构建配置文件中添加 Spring Cloud Starter Zipkin 依赖,如下所示 −

Now, add the Spring Cloud Starter Zipkin dependency in your build configuration file as shown −

Maven 用户可以在 pom.xml 文件中添加以下依赖 −

Maven users can add the following dependency in pom.xml file −

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>

Gradle 用户可以在 build.gradle 文件中添加以下依赖 −

Gradle users can add the below dependency in build.gradle file −

compile('org.springframework.cloud:spring-cloud-sleuth-zipkin')

现在,在 Spring Boot 应用程序中添加 Always Sampler Bean 以将日志导出至 Zipkin 服务器。

Now, add the Always Sampler Bean in your Spring Boot application to export the logs into Zipkin server.

@Bean
public AlwaysSampler defaultSampler() {
   return new AlwaysSampler();
}

如果你添加了 AlwaysSampler Bean,Spring Sleuth Zipkin Export 选项会自动从 false 变为 true。

If you add the AlwaysSampler Bean, then automatically Spring Sleuth Zipkin Export option will change from false to true.

接下来,在客户端服务 application.properties 文件中配置你的 Zipkin 服务器基本 URL。

Next, configure your Zipkin Server base URL in client service application.properties file.

spring.zipkin.baseUrl = http://localhost:9411/zipkin/

然后,提供跟踪 ID 并找出 Zipkin UI 中的跟踪。

Then, provide the trace id and find the traces in Zipkin UI.

Spring Boot - Flyway Database

Flyway 是一款版本控制应用程序,可以轻松可靠地在所有实例上改造您的数据库架构。要了解有关 Flyway 的更多信息,您可以使用以下链接: www.flywaydb.org

Flyway is a version control application to evolve your Database schema easily and reliably across all your instances. To learn more about Flyway, you can use the link − www.flywaydb.org

许多软件项目使用关系数据库。这需要对数据库迁移(也称为架构迁移)进行处理。

Many software projects use relational databases. This requires the handling of database migrations, also often called schema migrations.

在本章中,您将详细了解如何在 Spring Boot 应用程序中配置 Flyway 数据库。

In this chapter, you are going to learn in detail about how to configure Flyway database in your Spring Boot application.

Configuring Flyway Database

首先,从 Spring Initializer 页面 www.start.spring.io 下载 Spring Boot 项目并选择以下依赖项:

First, download the Spring Boot project from Spring Initializer page www.start.spring.io and choose the following dependencies −

  1. Spring Boot Starter Web

  2. Flyway

  3. MySQL

  4. JDBC

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependencies in pom.xml file.

<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 文件中添加以下依赖项。

Gradle users can add the following dependencies in build.gradle file.

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,还需要配置我们在应用程序属性中要配置的 flyway 属性。

In application properties, we need to configure the database properties for creating a DataSource and also flyway properties we need to configure in application properties.

对于属性文件用户,请在 application.properties 文件中添加以下属性。

For properties file users, add the below properties in the application.properties file.

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 文件中添加以下属性。

YAML users can add the following properties in application.yml file.

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”

Now, create a SQL file under the src/main/resources/db/migration directory. Name the SQL file as “V1__Initial.sql”

CREATE TABLE USERS (ID INT AUTO_INCREMENT PRIMARY KEY, USERID VARCHAR(45));
INSERT INTO USERS (ID, USERID) VALUES (1, 'tutorialspoint.com');

主要 Spring Boot 应用程序类文件代码如下所示:

The main Spring Boot application class file code is given below −

package com.tutorialspoint.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);
   }
}

完整的构建配置文件如下所示。

The complete build configuration file is given below.

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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 应用程序:

You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −

对于 Maven,您可以使用此处所示的命令:

For Maven, you can use the command shown here −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,可以使用此处显示的命令:

For Gradle, you can use the command shown here −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,通过使用以下命令运行 JAR 文件 −

Now, run the JAR file by using the following command −

 java –jar <JARFILE>

现在,Tomcat 在端口 8080 上启动,并且可以在控制台窗口中看到 flyway 数据库日志,如下所示。

Now, Tomcat started on the port 8080 and in the console window you can see the flyway database logs as shown here.

flyway database logs

你现在可以转到数据库并执行选择查询。

You can now go to the database and do the select queries.

database and select the queries

Spring Boot - Sending Email

通过使用 Spring Boot RESTful Web 服务,您可以通过 Gmail 传输层安全性发送电子邮件。在本章中,让我们详细了解如何使用此特性。

By using Spring Boot RESTful web service, you can send an email with Gmail Transport Layer Security. In this chapter, let us understand in detail how to use this feature.

首先,我们需要在 build 配置文件中添加 Spring Boot Starter Mail 依赖项。

First, we need to add the Spring Boot Starter Mail dependency in your build configuration file.

Maven 用户可以将下面的依赖项添加到 pom.xml 文件中。

Maven users can add the following dependency into the pom.xml file.

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

Gradle 用户可以在 build.gradle 文件中添加以下依赖项。

Gradle users can add the following dependency in your build.gradle file.

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

主要 Spring Boot 应用程序类文件代码如下所示:

The code of main Spring Boot application class file is given below −

package com.tutorialspoint.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 API,如下所示在 Rest 控制器类文件中发送电子邮件。

You can write a simple Rest API to send to email in Rest Controller class file as shown.

package com.tutorialspoint.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";
   }
}

您可以编写一个方法以便使用附件发送电子邮件。定义 mail.smtp 属性并使用 PasswordAuthentication。

You can write a method to send the email with Attachment. Define the mail.smtp properties and used 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("tutorialspoint@gmail.com", "<your password>");
      }
   });
   Message msg = new MimeMessage(session);
   msg.setFrom(new InternetAddress("tutorialspoint@gmail.com", false));

   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("tutorialspoint@gmail.com"));
   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() 方法,如下所示:

Now, call the above sendmail() method from the Rest API as shown −

@RequestMapping(value = "/sendemail")
public String sendEmail() throws AddressException, MessagingException, IOException {
   sendmail();
   return "Email sent successfully";
}

Note - 在发送电子邮件之前,请打开 Gmail 帐户设置中允许不安全的应用程序。

Note − Please switch ON allow less secure apps in your Gmail account settings before sending an email.

完整的构建配置文件如下所示。

The complete build configuration file is given below.

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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 应用程序 −

Now, you can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands shown below −

对于 Maven,您可以使用如下命令:−

For Maven, you can use the command as shown −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用如下命令:−

For Gradle, you can use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,运行 JAR 文件,使用如下所示命令 −

Now, run the JAR file by using the command given below −

java –jar <JARFILE>

你可以看到应用程序已在 Tomcat 端口 8080 上启动。

You can see that the application has started on the Tomcat port 8080.

tomcat port 8080 application output

现在,从您的 Web 浏览器访问以下 URL,您将收到一封电子邮件。

Now hit the following URL from your web browser and you will receive an email.

email sent successfully browser window
email sent successfully

Spring Boot - Hystrix

Hystrix 是 Netflix 的一个库。Hystrix 可隔离服务之间的接入点,阻止级联故障,并提供后备选项。

Hystrix is a library from Netflix. Hystrix isolates the points of access between the services, stops cascading failures across them and provides the fallback options.

例如,当您调用第三方应用程序时,它需要更多时间来发送响应。因此,那时,控件就会进入后备方法,并向您的应用程序返回自定义响应。

For example, when you are calling a 3rd party application, it takes more time to send the response. So at that time, the control goes to the fallback method and returns the custom response to your application.

在本章中,您将看到如何在 Spring Boot 应用程序中实现 Hystrix。

In this chapter you are going to see How to implement the Hystrix in a Spring Boot application.

首先,我们需要在我们的构建配置文件中添加 Spring Cloud Starter Hystrix 依赖关系。

First, we need to add the Spring Cloud Starter Hystrix dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖关系 −

Maven users can add the following dependency in the pom.xml file −

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

Gradle 用户可以在 build.gradle 文件中添加下列依赖 -

Gradle users can add the following dependency in the build.gradle file −

compile('org.springframework.cloud:spring-cloud-starter-hystrix')

现在,在您的主 Spring Boot 应用程序类文件中添加 @EnableHystrix 注解。@EnableHystrix 注解用于在 Spring Boot 应用程序中启用 Hystrix 功能。

Now, add the @EnableHystrix annotation into your main Spring Boot application class file. The @EnableHystrix annotation is used to enable the Hystrix functionalities into your Spring Boot application.

主要 Spring Boot 应用程序类文件代码如下所示:

The main Spring Boot application class file code is given below −

package com.tutorialspoint.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);
   }
}

现在,编写一个简单的 Rest Controller,以便在从请求时间开始的 3 秒后返回字符串。

Now write a simple Rest Controller such that it returns the String after 3 seconds from the requested time.

@RequestMapping(value = "/")
public String hello() throws InterruptedException {
   Thread.sleep(3000);
   return "Welcome Hystrix";
}

现在,为 Rest API 添加 @HystrixCommand 和 @HystrixProperty,并以毫秒值为单位定义超时时间。

Now, add the @Hystrix command and @HystrixProperty for the Rest API and define the timeout in milliseconds value.

@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
   @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})

接下来,如果请求响应时间较长,则定义后备方法 fallback_hello()。

Next, define the fallback method fallback_hello() if the request takes a long time to respond.

private String fallback_hello() {
   return "Request fails. It takes long time to response";
}

下面显示了包含 REST API 和 Hystrix 属性的完整 Rest Controller 类文件 −

The complete Rest Controller class file that contains REST API and Hystrix properties is shown here −

@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";
}

在此示例中,REST API 本身以主 Spring Boot 应用程序类文件编写。

In this example, REST API written in main Spring Boot application class file itself.

package com.tutorialspoint.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";
   }
}

完整的构建配置文件如下所示。

The complete build configuration file is given below.

Maven – pom.xml file

Maven – pom.xml file

<?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.tutorialspoint</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

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.tutorialspoint'
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}"
   }
}

您可以创建一个可执行 JAR 文件并使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 -

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −

对于 Maven,使用命令,如所示 −

For Maven, use the command as shown −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用命令,如所示 −

For Gradle, use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,运行 JAR 文件,使用如下所示命令 −

Now, run the JAR file by using the command given below −

java –jar <JARFILE>

这将启动 8080 端口上的应用程序,如下所示 −

This will start the application on the Tomcat port 8080 as shown below −

tomcat application command prompt

现在,从 Web 浏览器点击网址 http://localhost:8080/ ,然后查看 Hystrix 响应。API 响应时间为 3 秒,但 Hystrix 超时时间为 1 秒。

Now, hit the URL http://localhost:8080/ from your web browser, and see the Hystrix response. The API takes 3 seconds to respond, but Hystrix timeout is 1 second.

request fail hystrix timeout

Spring Boot - Web Socket

在本章中,让我们了解如何通过使用 Spring Boot 和 Web 套接字构建交互式 Web 应用程序。

In this chapter, let us understand how to build an interactive web application by using Spring Boot with Web sockets.

若要在 Spring Boot 中使用 Web 套接字构建交互式 Web 应用程序,您需要添加以下依赖关系。

To build an interactive web application in Spring Boot with Web socket, you need to add the following dependencies.

Maven 用户应在 pom.xml 文件中添加以下依赖关系。

Maven users should add the following dependencies in the pom.xml file.

<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 文件中添加以下依赖关系 −

Gradle users can add the following dependencies in your build.gradle file −

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”的消息。

Let us create a Message handling controller to work with STOMP messaging. STOMP messages can be routed to @Controller class file. For example, GreetingController is mapped to handle the messages to destination “/hello”.

package com.tutorialspoint.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。编写一个 WebSocketConfig 类文件,扩展 AbstractWebSocketMessageBrokerConfigurer 类,如下所示。

Now, configure Spring for STOMP messaging. Write a WebSocketConfig class file that extends the AbstractWebSocketMessageBrokerConfigurer class as shown below.

package com.tutorialspoint.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("/tutorialspoint-websocket").withSockJS();
   }
}

使用 @EnableWebSocketMessageBroker 注解来配置 Websocket 消息代理来创建 STOMP 端点。

The @EnableWebSocketMessageBroker annotation is used to configure the Web socket message broker to create STOMP endpoints.

您可以在 src/main/resources/static/index.html 下创建浏览器客户端文件,如下所示 −

You can create a browser client file under the src/main/resources/static/index.html as shown −

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

让我们创建一个 app.js 文件,使用 STOMP 来消费和生产消息。

Let us create an app.js file to consume and produce the messages by using STOMP.

var stompClient = null;

function setConnected(connected) {
   $("#connect").prop("disabled", connected);
   $("#disconnect").prop("disabled", !connected);

   if (connected) {
      $("#conversation").show();
   } else {
      $("#conversation").hide();
   }
   $("#greetings").html("");
}

function connect() {
   var socket = new SockJS('/tutorialspoint-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 应用程序的代码。

The code for main Spring Boot application is shown below.

package com.tutorialspoint.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);
   }
}

完整的构建配置文件如下所示。

The complete build configuration file is given below.

Maven – pom.xml

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.tutorialspoint</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

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")
}

Spring Boot - Batch Service

您可以创建一个可执行 JAR 文件,并使用 Maven 或 Gradle 命令运行 Spring Boot 应用程序,如下所示 −

You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands as shown below −

对于 Maven,你可以使用下面给出的命令 −

For Maven, you can use the command given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用如下命令:−

For Gradle, you can use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用此处提供的命令运行 JAR 文件 −

Run the JAR file by using the command given here −

java –jar <JARFILE>

现在,该应用程序已经启动在所示的 Tomcat 端口 8080 上。

Now, the application has started on the Tomcat port 8080 as shown.

batch service application started on tomcat port

现在,在您的 Web 浏览器中访问 URL http://localhost:8080/ 并连接 Websocket,发送问候语并接收消息。

Now, hit the URL http://localhost:8080/ in your web browser and connect the web socket and send the greeting and receive the message.

web socket send receive message

批处理服务是一个在单个任务中执行多条命令的过程。在本章中,您将学习如何在 Spring Boot 应用程序中创建批处理服务。

Batch Service is a process to execute more than one command in a single task. In this chapter, you are going to learn how to create batch service in a Spring Boot application.

让我们考虑一个示例,其中我们要将 CSV 文件内容保存到 HSQLDB 中。

Let us consider an example where we are going to save the CSV file content into HSQLDB.

要创建批处理服务程序,我们需要在构建配置文件中添加 Spring Boot Starter Batch 依赖项和 HSQLDB 依赖项。

To create a Batch Service program, we need to add the Spring Boot Starter Batch dependency and HSQLDB dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependencies in pom.xml file.

<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 文件中添加以下依赖项。

Gradle users can add the following dependencies in build.gradle file.

compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.hsqldb:hsqldb")

现在,在类路径资源下添加简单的 CSV 数据文件 – src/main/resources,并将文件命名为 file.csv,如下所示 −

Now, add the simple CSV data file under classpath resources – src/main/resources and name the file as file.csv as shown −

William,John
Mike, Sebastian
Lawarance, Lime

接下来,写入 HSQLDB 的 SQL 脚本 – 在类路径资源目录下 – request_fail_hystrix_timeout

Next, write a SQL script for HSQLDB – under the classpath resource directory – 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 类,如下所示 −

Create a POJO class for USERS model as shown −

package com.tutorialspoint.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 之前执行操作。

Now, create an intermediate processor to do the operations after the reading the data from the CSV file and before writing the data into SQL.

package com.tutorialspoint.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 应用程序启用批处理操作。

Let us create a Batch configuration file, to read the data from CSV and write into the SQL file as shown below. We need to add the @EnableBatchProcessing annotation in the configuration class file. The @EnableBatchProcessing annotation is used to enable the batch operations for your Spring Boot application.

package com.tutorialspoint.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 中。

The reader() method is used to read the data from the CSV file and writer() method is used to write a data into the SQL.

接下来,我们将不得不编写一个作业完成通知侦听器类 – 用于在作业完成后通知。

Next, we will have to write a Job Completion Notification Listener class – used to notify after the Job completion.

package com.tutorialspoint.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 应用程序。

Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,使用命令,如所示 −

For Maven, use the command as shown −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用如下命令:−

For Gradle, you can use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用此处提供的命令运行 JAR 文件 −

Run the JAR file by using the command given here −

java –jar <JARFILE>

您可以看到控制台窗口中的输出,如下所示 −

You can see the output in console window as shown −

batch service output in console window

Spring Boot - Apache Kafka

Apache Kafka 是一个开源项目,用于基于容错性消息传递系统发布和订阅消息。它设计上快速、可扩展、且分布式。如果您是 Kafka 初学者,或希望对其进行更深入的了解,请参阅此链接 − www.tutorialspoint.com/apache_kafka/

Apache Kafka is an open source project used to publish and subscribe the messages based on the fault-tolerant messaging system. It is fast, scalable and distributed by design. If you are a beginner to Kafka, or want to gain a better understanding on it, please refer to this link − www.tutorialspoint.com/apache_kafka/

在本章节中,我们将看看如何在 Spring Boot 应用程序中实现 Apache Kafka。

In this chapter, we are going to see how to implement the Apache Kafka in Spring Boot application.

首先,我们需要在我们的构建配置文件中添加 Spring Kafka 依赖项。

First, we need to add the Spring Kafka dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependency in the pom.xml file.

<dependency>
   <groupId>org.springframework.kafka</groupId>
   <artifactId>spring-kafka</artifactId>
   <version>2.1.0.RELEASE</version>
</dependency>

Gradle 用户可以在 build.gradle 文件中添加以下依赖项。

Gradle users can add the following dependency in the build.gradle file.

compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.1.0.RELEASE'

Producing Messages

要向 Apache Kafka 中发送消息,我们需要为生产者配置定义 Configuration 类,如所示 −

To produce messages into Apache Kafka, we need to define the Configuration class for Producer configuration as shown −

package com.tutorialspoint.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 Template 对象并产生消息,如所示。

To publish a message, auto wire the Kafka Template object and produce the message as shown.

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;

public void sendMessage(String msg) {
   kafkaTemplate.send(topicName, msg);
}

Consuming a Message

要使用消息,我们需要编写 Consumer 配置类文件,如所示 −

To consume messages, we need to write a Consumer configuration class file as shown below.

package com.tutorialspoint.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;
   }
}

接下来,编写监听器以侦听消息。

Next, write a Listener to listen to the messages.

@KafkaListener(topics = "tutorialspoint", groupId = "group-id")
public void listen(String message) {
   System.out.println("Received Messasge in group - group-id: " + message);
}

让我们从主 Spring Boot 应用程序类文件的 ApplicationRunner 类 run 方法中调用 sendMessage() 方法,并从同一类文件中使用消息。

Let us call the sendMessage() method from ApplicationRunner class run method from the main Spring Boot application class file and consume the message from the same class file.

您的主 Spring Boot 应用程序类文件代码如下 −

Your main Spring Boot application class file code is given below −

package com.tutorialspoint.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("tutorialspoint", msg);
   }
   public static void main(String[] args) {
      SpringApplication.run(KafkaDemoApplication.class, args);
   }
   @KafkaListener(topics = "tutorialspoint", 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");
   }
}

完整构建配置文件的代码如下所示。

The code for complete build configuration file is given below.

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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 应用程序,如所示 −

Now, create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands as shown −

对于 Maven,使用命令,如所示 −

For Maven, use the command as shown −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用命令,如所示 −

For Gradle, use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用此处提供的命令运行 JAR 文件 −

Run the JAR file by using the command given here −

java –jar <JARFILE>

您可以看到控制台窗口中的输出。

You can see the output in console window.

Spring Boot - Twilio

Twilio 是一个第三方应用程序,用于发送短信并通过我们的应用程序拨打语音电话。它允许我们以编程方式发送短信并拨打语音电话。

Twilio is a 3rd party application used to send SMS and make voice calls from our application. It allows us to send the SMS and make voice calls programmatically.

在本章中,你将学习如何使用带 Twilio 的 Spring Boot 实现发送 SMS 及拨打语音电话。

In this chapter, you are going to learn how to implement the SMS sending and making voice calls by using Spring Boot with Twilio.

Note − 我们使用 Twilio 中的 Trail 帐户来发送短信并拨打语音电话。你可以在 www.twilio.com 了解更多关于 Twilio 的信息。

Note − We used the Trail account in Twilio to send the SMS and making voice calls. You can learn more about Twilio at www.twilio.com.

首先,我们需要在我们的构建配置文件中添加 Twilio 依赖项。

First, we need to add the Twilio dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependency in the pom.xml file.

<dependency>
   <groupId>com.twilio.sdk</groupId>
   <artifactId>twilio</artifactId>
   <version>7.16.1</version>
</dependency>

Gradle 用户可以在 build.gradle 文件中添加以下依赖项。

Gradle users can add the following dependency in the build.gradle file.

compile group: "com.twilio.sdk", name:"twilio", version: "7.16.1"

现在,在静态块中初始化 Twilio 帐户,其中包含 ACCOUNT_SID 和 AUTH_ID,如下所示:

Now, initialize the Twilio account with ACCOUNT_SID and AUTH_ID in static block as shown −

static {
   Twilio.init(ACCOUNT_SID, AUTH_ID);
}

Sending SMS

要发送短信,我们需要向 Message.create() 方法提供 from-number 和 to-number。消息正文内容,我们还需要为方法 Message.creator() 提供,如下所示:

To send the SMS, we need to provide a from-number and to-number to the Message.create() method. Message body content also we need to provide for the method Message.creator()as shown −

Message.creator(new PhoneNumber("to-number"), new PhoneNumber("from-number"),
   "Message from Spring Boot Application").create();

主要的 Spring Boot 应用程序类文件如下所示。

The main Spring Boot application class file looks below.

package com.tutorialspoint.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();
   }
}

构建配置文件的完整代码如下所示:

The complete code to build configuration file is given below −

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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.+"
}

您可以创建一个可执行 JAR 文件,并通过使用以下 Maven 或 Gradle 命令运行 Spring Boot 应用程序 -

You can create an executable JAR file, and run the spring boot application by using the following Maven or Gradle commands −

对于 Maven,使用命令,如所示 −

For Maven, use the command as shown −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用命令,如所示 −

For Gradle, use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用如下命令运行 JAR 文件:

Run the JAR file by using the command as given below −

java –jar <JARFILE>

现在,你将收到发送到你的 “to-number” 的短信。

Now, you will receive the SMS to your “to-number”.

消息已收到 “to-number”。

Message received to “to-number”.

Sent from your Twilio trail account
- Message from Spring Boot Application

Note − 在此示例中,我们使用了 Trail 帐户。因此,你应当在发送短信前验证号码。

Note − In this example, we used the Trail account. So, you should verify the numbers before sending the SMS.

Voice Calls

要使用 Twilio 拨打语音电话,我们需要调用 Call.creator() 方法。对于此方法,我们需要提供 to-number、from-number 和语音注释,如下所示:

To make voice calls by using Twilio, we need to call the Call.creator() method. For this method, we need to provide a to-number, from-number, and voice-note as shown here.

Call.creator(new PhoneNumber("<to-number>"), new PhoneNumber("<from-number>"),
   new URI("http://demo.twilio.com/docs/voice.xml")).create();

主 Spring Boot 应用程序类文件的代码如下所示。

The code for main Spring Boot application class file is given below.

package com.tutorialspoint.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();
   }
}

完整构建配置文件的代码如下所示:

The code for complete build configuration file is given below −

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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.+"
}

您可以创建一个可执行 JAR 文件,并通过使用以下 Maven 或 Gradle 命令来运行 Spring Boot 应用程序。

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,使用命令,如所示 −

For Maven, use the command as shown −

 mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,使用命令,如所示 −

For Gradle, use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,使用此处提供的命令运行 JAR 文件:

Now, run the JAR file by using the command given here −

java –jar <JARFILE>

现在,你将从 Twilio 收到呼叫到你的 “to-number”。

Now, you will receive call to your “to-number” from Twilio.

在接听电话后按任意键,你将听到来自 https://demo.twilio.com/docs/voice.xml 的语音注释。

Press any key after attending the call, you will hear the voice note from https://demo.twilio.com/docs/voice.xml

Note − 在此示例中,我们使用了 Trail 帐户。因此,你应当在拨打电话前验证号码。

Note − In this example, we used the Trail account. So, you should verify the numbers before making calls.

Spring Boot - Unit Test Cases

单元测试是由开发人员进行的测试,用于确保各个单元或组件功能正常工作。

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 控制器编写单元测试用例。

In this tutorial, we are going to see how to write a unit test case by using Mockito and Web Controller.

Mockito

要将 Mockito Mocks 注入到 Spring Beans,我们需要在我们的构建配置文件中添加 Mockito-core 依赖项。

For injecting Mockito Mocks into Spring Beans, we need to add the Mockito-core dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependency in your pom.xml file.

<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 文件中添加以下依赖项。

Gradle users can add the following dependency in the build.gradle file.

compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
testCompile('org.springframework.boot:spring-boot-starter-test')

编写服务类的代码,其中包含返回字符串值的方法,如下所示。

The code to write a Service class which contains a method that returns the String value is given here.

package com.tutorialspoint.mockitodemo;

import org.springframework.stereotype.Service;

@Service
public class ProductService {
   public String getProductName() {
      return "Honey";
   }
}

现在,将 ProductService 类注入到另一个服务类文件中,如下所示。

Now, inject the ProductService class into another Service class file as shown.

package com.tutorialspoint.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 应用程序主类文件如下所示 −

The main Spring Boot application class file is given below −

package com.tutorialspoint.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);
   }
}

然后,为测试配置应用程序上下文。 src/test/resources 注释用于在测试用例运行时配置类。

Then, configure the Application context for the tests. The @Profile(“test”) annotation is used to configure the class when the Test cases are running.

package com.tutorialspoint.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 包下为订单服务编写单元测试用例。

Now, you can write a Unit Test case for Order Service under the src/test/resources package.

package com.tutorialspoint.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);
   }
}

完整的构建配置文件代码如下。

The complete code for build configuration file is given below.

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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')
}

您可以创建可执行 JAR 文件,并使用以下 Maven 或 Gradle1 命令运行 Spring Boot 应用程序。

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle1 commands.

对于 Maven,您可以使用如下命令:−

For Maven, you can use the command as shown −

mvn clean install

您可以在控制台窗口中看到测试结果。

You can see the test results in console window.

test results in console window

对于 Gradle,您可以使用如下命令:−

For Gradle, you can use the command as shown −

gradle clean build

您可以在控制台窗口中看到其余结果。

You can see the rest results in console window.

rest results in console window

Spring Boot - Rest Controller Unit Test

Spring Boot 提供了一种便捷的方式来针对 Rest Controller 文件编写单元测试。借助于 SpringJUnit4ClassRunner 和 MockMvc,我们可以创建一个 Web 应用程序上下文来针对 Rest Controller 文件编写单元测试。

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 目录下。

Unit Tests should be written under the src/test/java directory and classpath resources for writing a test should be placed under the src/test/resources directory.

要编写一个单元测试,我们需要在构建配置文件中添加 Spring Boot Starter 测试依赖,如下所示。

For Writing a Unit Test, we need to add the Spring Boot Starter Test dependency in your build configuration file as shown below.

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

Gradle 用户可以在 build.gradle 文件中添加以下依赖项。

Gradle users can add the following dependency in your build.gradle file.

testCompile('org.springframework.boot:spring-boot-starter-test')

在编写测试用例之前,我们应该首先构建 RESTful Web 服务。有关构建 RESTful Web 服务的更多信息,请参阅本教程中给出的相同章节。

Before writing a Test case, we should first build RESTful web services. For further information on building RESTful web services, please refer to the chapter on the same given in this tutorial.

Writing a Unit Test for REST Controller

在本节中,让我们看看如何编写 REST 控制器的单元测试。

In this section, let us see how to write a Unit Test for the REST Controller.

首先,我们需要创建一个用于通过 MockMvc 创建 Web 应用程序上下文的抽象类文件,并定义 mapToJson() 和 mapFromJson() 方法,以将 Java 对象转换成 JSON 字符串,并将 JSON 字符串转换成 Java 对象。

First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object.

package com.tutorialspoint.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 方法编写一个单元测试。

Next, write a class file that extends the AbstractTest class and write a Unit Test for each method such GET, POST, PUT and DELETE.

下面给出了 GET API 测试用例的代码。此 API 用于查看产品列表。

The code for GET API Test case is given below. This API is to view the list of products.

@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 用于创建产品。

The code for POST API test case is given below. This API is to create a product.

@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 用于更新现有产品。

The code for PUT API Test case is given below. This API is to update the existing product.

@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 将删除现有产品。

The code for Delete API Test case is given below. This API will delete the existing product.

@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");
}

下面给出了完整的控制器测试类文件 −

The full Controller Test class file is given below −

package com.tutorialspoint.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.tutorialspoint.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 应用程序:

You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −

对于 Maven,你可以使用下面给出的命令 −

For Maven, you can use the command given below −

mvn clean install

现在,你可以在控制台窗口中查看测试结果。

Now, you can see the test results in console window.

test results in console window

对于 Gradle,你可以使用如下所示的命令:

For Gradle, you can use the command as shown below −

gradle clean build

你可以在控制台窗口中查看 rest 结果,如下所示。

You can see the rest results in console window as shown below.

rest results in console window

Spring Boot - Database Handling

Spring Boot 提供了非常好的支持来创建用于数据库的数据源。我们不需要编写任何额外的代码在 Spring Boot 中创建一个数据源。只需添加依赖并进行配置详细信息就足以创建一个数据源并连接数据库。

Spring Boot provides a very good support to create a DataSource for Database. We need not write any extra code to create a DataSource in Spring Boot. Just adding the dependencies and doing the configuration details is enough to create a DataSource and connect the Database.

在本章中,我们将使用 Spring Boot JDBC 驱动程序连接连接数据库。

In this chapter, we are going to use Spring Boot JDBC driver connection to connect the database.

首先,我们需要在构建配置文件中添加 Spring Boot Starter JDBC 依赖。

First, we need to add the Spring Boot Starter JDBC dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependencies in the pom.xml file.

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

Gradle 用户可以在 build.gradle 文件中添加以下依赖项。

Gradle users can add the following dependencies in the build.gradle file.

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

Connect to H2 database

要连接 H2 数据库,我们需要在构建配置文件中添加 H2 数据库依赖项。

To connect the H2 database, we need to add the H2 database dependency in our build configuration file.

对于 Maven 用户,在 pom.xml 文件中添加以下依赖:

For Maven users, add the below dependency in your pom.xml file.

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
</dependency>

对于 Gradle 用户,在 build.gradle 文件中添加以下依赖:

For Gradle users, add the below dependency in your build.gradle file.

compile('com.h2database:h2')

我们需要在 classpath src/main/resources 目录下创建 schema.sql 文件和 data.sql 文件,以连接 H2 数据库。

We need to create the schema.sql file and data.sql file under the classpath src/main/resources directory to connect the H2 database.

下面给出了 schema.sql 文件。

The schema.sql file is given below.

CREATE TABLE PRODUCT (ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(25));

下面给出了 data.sql 文件。

The data.sql file is given below.

INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (1,'Honey');
INSERT INTO PRODUCT (ID,PRODUCT_NAME) VALUES (2,'Almond');

Connect MySQL

为了连接 MySQL 数据库,我们需要在构建配置文件中添加 MySQL 依赖。

To connect the MySQL database, we need to add the MySQL dependency into our build configuration file.

对于 Maven 用户,在 pom.xml 文件中添加以下依赖:

For Maven users, add the following dependency in your pom.xml file.

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
</dependency>

对于 Gradle 用户,在 build.gradle 文件中添加以下依赖:

For Gradle users, add the following dependency in your build.gradle file.

compile('mysql:mysql-connector-java')

现在,在 MySQL 中创建数据库和表,如下所示:

Now, create database and tables in MySQL as shown −

database and tables in mysql

对于属性文件用户,在 application.properties 文件中添加以下属性。

For properties file users, add the following properties in the application.properties file.

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 文件中添加以下属性:

For YAML users, add the following properties in the application.yml file.

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

Connect Redis

Redis 是一个用于存储内存内数据结构的开源数据库。为了在 Spring Boot 应用程序中连接 Redis 数据库,我们需要在构建配置文件中添加 Redis 依赖。

Redis is an open source database used to store the in-memory data structure. To connect the Redis database in Spring Boot application, we need to add the Redis dependency in our build configuration file.

Maven 用户应在 pom.xml 文件中添加以下依赖:

Maven users should add the following dependency in your pom.xml file.

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

Gradle 用户应在 build.gradle 文件中添加以下依赖:

Gradle users should add the following dependency in your build.gradle file.

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

对于 Redis 连接,我们需要使用 RedisTemplate。对于 RedisTemplate,我们需要提供 JedisConnectionFactory 详细信息。

For Redis connection, we need to use RedisTemplate. For RedisTemplate we need to provide the JedisConnectionFactory details.

@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 数据库访问数据。

Now auto wire the RedisTemplate class and access the data from Redis database.

@Autowired

RedisTemplate<String, Object> redis;
Map<Object,Object> datalist = redis.opsForHash().entries(“Redis_code_index_key”);

JDBCTemplate

为了使用 JdbcTemplate 在 Spring Boot 应用程序中访问关系数据库,我们需要在构建配置文件中添加 Spring Boot Starter JDBC 依赖。

To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file.

然后,如果你 @Autowired 了 JdbcTemplate 类,Spring Boot 会自动连接数据库,并为 JdbcTemplate 对象设置数据源。

Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.

@Autowired
JdbcTemplate jdbcTemplate;
Collection<Map<String, Object>> rows = jdbc.queryForList("SELECT QUERY");

应该向 class 文件添加 @Repository 注解。@Repository 注解用于为 Spring Boot 应用程序创建数据库存储库。

The @Repository annotation should be added into the class file. The @Repository annotation is used to create database repository for your Spring Boot application.

@Repository
public class ProductServiceDAO {
}

Multiple DataSource

我们可以在单个 Spring Boot 应用程序中保留“n”个数据源。这里给出的示例显示了如何在 Spring Boot 应用程序中创建多个数据源。现在,在应用程序属性文件中添加两个数据源配置详细信息。

We can keep ‘n’ number Datasources in a single Spring Boot application. The example given here shows how to create more than 1 data source in Spring Boot application. Now, add the two data source configuration details in the application properties file.

对于属性文件用户,添加以下属性到您的 application.properties 文件中。

For properties file users, add the following properties into your application.properties file.

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 文件中。

Yaml users should add the following properties in your application.yml file.

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。

Now, create a Configuration class to create a DataSource and JdbcTemplate for multiple data sources.

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 对象。

Then, auto wire the JDBCTemplate object by using @Qualifier annotation.

@Qualifier("jdbcProductService")
@Autowired
JdbcTemplate jdbcTemplate;

@Qualifier("jdbcUserService")
@Autowired
JdbcTemplate jdbcTemplate;

Spring Boot - Securing Web Applications

如果在类路径上添加了 Spring Boot Security 依赖项,Spring Boot 应用程序会自动为所有 HTTP 端点要求基本身份验证。端点 “/” 和 “/home” 不需要任何身份验证。所有其他端点都需要身份验证。

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 依赖项。

For adding a Spring Boot Security to your Spring Boot application, we need to add the Spring Boot Starter Security dependency in our build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependency in the pom.xml file.

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

Gradle 用户可以在 build.gradle 文件中添加以下依赖项。

Gradle users can add the following dependency in the build.gradle file.

compile("org.springframework.boot:spring-boot-starter-security")

Securing a Web application

首先,使用 Thymeleaf 模板创建一个不安全的 Web 应用程序。

First, create an unsecure web application by using Thymeleaf templates.

然后,在 src/main/resources/templates 目录下创建一个 home.html 文件。

Then, create a home.html file under src/main/resources/templates directory.

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

HTML 文件中定义的简单视图 /hello 使用了 Thymeleaf 模板。

The simple view /hello defined in the HTML file by using Thymeleaf templates.

现在,在 src/main/resources/templates 下创建一个 hello.html。

Now, create a hello.html under src/main/resources/templates directory.

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

现在,我们需要为 home 和 hello 视图设置 Spring MVC - 视图控制器。

Now, we need to setup the Spring MVC – View controller for home and hello views.

对此,创建一个扩展了 WebMvcConfigurerAdapter 的 MVC 配置文件。

For this, create a MVC configuration file that extends WebMvcConfigurerAdapter.

package com.tutorialspoint.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 启动器安全依赖项添加到您的构建配置文件。

Now, add the Spring Boot Starter security dependency to your build configuration file.

Maven 用户可以在 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependency in your pom.xml file.

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

Gradle 用户可以在 build.gradle 文件中添加以下依赖项。

Gradle users can add the following dependency in the build.gradle file.

compile("org.springframework.boot:spring-boot-starter-security")

现在,创建一个 Web 安全配置文件,用于通过基本认证来保护您的应用程序访问 HTTP 端点。

Now, create a Web Security Configuration file, that is used to secure your application to access the HTTP Endpoints by using basic authentication.

package com.tutorialspoint.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 目录下创建一个 login.html 文件,以允许用户通过登录屏幕访问 HTTP 端点。

Now, create a login.html file under the src/main/resources directory to allow the user to access the HTTP Endpoint via login screen.

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

最后,更新 hello.html 文件 - 允许用户退出应用程序并显示当前用户名,如下所示:

Finally, update the hello.html file – to allow the user to Sign-out from the application and display the current username as shown below −

<!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 应用程序的代码如下:

The code for main Spring Boot application is given below −

package com.tutorialspoint.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);
   }
}

完整的构建配置文件代码如下。

The complete code for build configuration file is given below.

Maven – pom.xml

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.tutorialspoint</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

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.tutorialspoint'
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 应用程序。

Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

Maven 用户可以使用如下所示的命令:

Maven users can use the command as given below −

mvn clean install

在“构建成功”后,您可以在 target 目录下找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under target directory.

Gradle 用户可以使用如下所示的命令:

Gradle users can use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,使用如下所示的命令运行 JAR 文件:

Now, run the JAR file by using the command shown below −

java –jar <JARFILE>

在您的 Web 浏览器中输入 URL http://localhost:8080/ 。您可以看到如图所示的输出。

Hit the URL http://localhost:8080/ in your web browser. You can see the output as shown.

output on web browser click link
output login page
output signout page
output logged out
invalid username password

Spring Boot - OAuth2 with JWT

在本章中,您将详细了解 Spring 引导安全机制和带有 JWT 的 OAuth2。

In this chapter, you will learn in detail about Spring Boot Security mechanisms and OAuth2 with JWT.

Authorization Server

授权服务器是 Web API 安全的一个最高架构组件。授权服务器充当集中授权点,允许您的应用程序和 HTTP 端点识别您的应用程序的功能。

Authorization Server is a supreme architectural component for Web API Security. The Authorization Server acts a centralization authorization point that allows your apps and HTTP endpoints to identify the features of your application.

Resource Server

资源服务器是向客户端提供访问令牌用来访问资源服务器 HTTP 端点的一个应用程序。它是包含 HTTP 端点、静态资源和动态网页的库集合。

Resource Server is an application that provides the access token to the clients to access the Resource Server HTTP Endpoints. It is collection of libraries which contains the HTTP Endpoints, static resources, and Dynamic web pages.

OAuth2

OAuth2 是授权框架,它让应用程序 Web Security 能够从客户端访问资源。为构建 OAuth2 应用程序,我们需要关注授权类型(授权代码)、客户端 ID 和客户端机密。

OAuth2 is an authorization framework that enables the application Web Security to access the resources from the client. To build an OAuth2 application, we need to focus on the Grant Type (Authorization code), Client ID and Client secret.

JWT Token

JWT 令牌是用于表示在两方之间保护的声明的 JSON Web 令牌。你可以在 www.jwt.io/ 上了解有关 JWT 令牌的更多信息。

JWT Token is a JSON Web Token, used to represent the claims secured between two parties. You can learn more about the JWT token at www.jwt.io/.

现在,我们要构建 OAuth2 应用程序,通过 JWT 令牌利用授权服务器和资源服务器。

Now, we are going to build an OAuth2 application that enables the use of Authorization Server, Resource Server with the help of a JWT Token.

你可以使用以下步骤通过访问数据库来实施具有 JWT 令牌的 Spring Boot Security。

You can use the following steps to implement the Spring Boot Security with JWT token by accessing the database.

首先,我们需要在我们的构建配置文件中添加以下依赖项。

First, we need to add the following dependencies in our build configuration file.

Maven 用户可以在他们的 pom.xml 文件中添加以下依赖项。

Maven users can add the following dependencies in your pom.xml file.

<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 文件中添加以下依赖项。

Gradle users can add the following dependencies in the build.gradle file.

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")

其中,

where,

  1. Spring Boot Starter Security − Implements the Spring Security

  2. Spring Security OAuth2 − Implements the OAUTH2 structure to enable the Authorization Server and Resource Server.

  3. Spring Security JWT − Generates the JWT Token for Web security

  4. Spring Boot Starter JDBC − Accesses the database to ensure the user is available or not.

  5. Spring Boot Starter Web − Writes HTTP endpoints.

  6. H2 Database − Stores the user information for authentication and authorization.

完整的构建配置文件如下所示。

The complete build configuration file is given below.

<?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.tutorialspoint</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

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.tutorialspoint'
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 注解,以在同一应用程序中充当身份验证服务器和资源服务器。

Now, in the main Spring Boot application, add the @EnableAuthorizationServer and @EnableResourceServer annotation to act as an Auth server and Resource Server in the same application.

此外,你可以使用以下代码编写一个简单的 HTTP 端点,以便通过使用 JWT 令牌,用 Spring Security 访问 API。

Also, you can use the following code to write a simple HTTP endpoint to access the API with Spring Security by using JWT Token.

package com.tutorialspoint.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 类,以存储用于身份验证的用户信息。

Use the following code to define the POJO class to store the User information for authentication.

package com.tutorialspoint.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;
   }
}

现在,使用以下代码并定义 CustomUser 类,该类拓展了用于 Spring Boot 认证的 org.springframework.security.core.userdetails.User 类。

Now, use the following code and define the CustomUser class that extends the org.springframework.security.core.userdetails.User class for Spring Boot authentication.

package com.tutorialspoint.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 类以从数据库中读取用户信息并将其发送到 Custom 用户服务,并添加已授予的权限 “ROLE_SYSTEMADMIN”。

You can create the @Repository class to read the User information from the database and send it to the Custom user service and also add the granted authority “ROLE_SYSTEMADMIN”.

package com.tutorialspoint.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;
   }
}

你可以创建一个 Custom User 详细信息服务类,该类拓展了 org.springframework.security.core.userdetails.UserDetailsService 以按如下所示调用 DAO 存储库类。

You can create a Custom User detail service class that extends the org.springframework.security.core.userdetails.UserDetailsService to call the DAO repository class as shown.

package com.tutorialspoint.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");
      }
   }
}

接下来,创建一个 @configuration 类以启用 Web Security,定义密码编码器 (BCryptPasswordEncoder),并定义 AuthenticationManager bean。Security 配置类应该拓展 WebSecurityConfigurerAdapter 类。

Next, create a @configuration class to enable the Web Security, defining the Password encoder (BCryptPasswordEncoder), and defining the AuthenticationManager bean. The Security configuration class should extend WebSecurityConfigurerAdapter class.

package com.tutorialspoint.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 Configuration 类以添加 Client ID、Client Secret,定义用于 Token 签名密钥和验证密钥的 JwtAccessTokenConverter、私钥和公钥,并使用作用域配置 Token 有效性的 ClientDetailsServiceConfigurer。

Now, define the OAuth2 Configuration class to add the Client ID, Client Secret, Define the JwtAccessTokenConverter, Private key and Public key for token signer key and verifier key, and configure the ClientDetailsServiceConfigurer for the Token validity with scopes.

package com.tutorialspoint.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 = "tutorialspoint";
   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 创建私钥和公钥。

Now, create a Private key and public key by using openssl.

对于生成私钥可以使用以下命令。

You can use the following commands for generating private key.

openssl genrsa -out jwt.pem 2048
openssl rsa -in jwt.pem

对于生成公钥使用以下命令。

You can use For public key generation use the below commands.

openssl rsa -in jwt.pem -pubout

对于 Spring Boot 1.5 发行版之后的版本,在你的 application.properties 文件中添加以下属性以定义 OAuth2 Resource 过滤器顺序。

For the version of Spring Boot latter than 1.5 release, add the below property in your application.properties file to define OAuth2 Resource filter order.

security.oauth2.resource.filter-order=3

YAML 文件用户可以在 YAML 文件中添加以下属性。

YAML file users can add the below property in YAML file.

security:
   oauth2:
      resource:
         filter-order: 3

现在,在类路径资源 src/main/resources/directory 中创建 schema.sql 和 data.sql 文件以将应用程序连接到 H2 数据库。

Now, create schema.sql and data.sql file under the classpath resources src/main/resources/directory to connect the application to H2 database.

schema.sql 文件如下所示 −

The schema.sql file is as shown −

CREATE TABLE USERS (ID INT PRIMARY KEY, USERNAME VARCHAR(45), PASSWORD VARCHAR(60));

data.sql 文件如下所示 −

The data.sql file is as shown −

INSERT INTO USERS (ID, USERNAME,PASSWORD) VALUES (
   1, 'tutorialspoint@gmail.com','$2a$08$fL7u5xcvsZl78su29x1ti.dxI.9rYO8t0q5wk2ROJ.1cdR53bmaVG');

INSERT INTO USERS (ID, USERNAME,PASSWORD) VALUES (
   2, 'myemail@gmail.com','$2a$08$fL7u5xcvsZl78su29x1ti.dxI.9rYO8t0q5wk2ROJ.1cdR53bmaVG');

Note − 密码应该按照 Bcrypt Encoder 格式存储在数据库表中。

Note − Password should be stored in the format of Bcrypt Encoder in the database table.

您可以创建一个可执行 JAR 文件,并通过使用以下 Maven 或 Gradle 命令来运行 Spring Boot 应用程序。

You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.

对于 Maven,你可以使用下面给出的命令 −

For Maven, you can use the command given below −

mvn clean install

“BUILD SUCCESS”之后,您可以在目标目录中找到 JAR 文件。

After “BUILD SUCCESS”, you can find the JAR file under the target directory.

对于 Gradle,您可以使用如下命令:−

For Gradle, you can use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

现在,通过使用此处所示命令运行 JAR 文件:

Now, run the JAR file by using the command shown here −

java –jar <JARFILE>

应用程序在 Tomcat 端口 8080 上启动。

The application is started on the Tomcat port 8080.

tomcat port 8080 application output

现在,通过 POSTMAN 访问 POST 方法的 URL 以获取 OAUTH2 令牌。

Now hit the POST method URL via POSTMAN to get the OAUTH2 token.

现在,添加请求头如下 −

Now, add the Request Headers as follows −

  1. Authorization − Basic Auth with your Client Id and Client secret.

  2. Content Type − application/x-www-form-urlencoded

add request headers

现在,按以下方式添加请求参数 −

Now, add the Request Parameters as follows −

  1. grant_type = password

  2. username = your username

  3. password = your password

add request parameters

现在,点击 API 并获取 access_token,如下所示 −

Now, hit the API and get the access_token as shown −

get the access token

现在,在请求头中使用 Bearer 访问令牌,点击资源服务器 API,如下所示。

Now, Hit the Resource Server API with Bearer access token in Request Header as shown.

resource server api with bearer access token

然后,你可以看到如下输出 −

Then you can see the output as shown below −

oauth2 with jwt output

Spring Boot - Google Cloud Platform

Google Cloud Platform 提供云计算服务,可在云环境中运行 Spring Boot 应用程序。在本章中,我们将了解如何将 Spring Boot 应用程序部署到 GCP app engine 平台中。

Google Cloud Platform provides a cloud computing services that run the Spring Boot application in the cloud environment. In this chapter, we are going to see how to deploy the Spring Boot application in GCP app engine platform.

首先,从 Spring Initializer 页面 www.start.spring.io 下载 Gradle 构建的 Spring Boot 应用程序。观察以下屏幕截图。

First, download the Gradle build Spring Boot application from Spring Initializer page www.start.spring.io. Observe the following screenshot.

spring initializer page

现在,在 build.gradle 文件中,添加 Google Cloud Appengine 插件和 Appengine 类路径依赖项。

Now, in build.gradle file, add the Google Cloud appengine plugin and appengine classpath dependency.

build.gradle 文件的代码如下所示 −

The code for build.gradle file is given below −

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.tutorialspoint'
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 端点,使其返回字符串成功,如下所示 −

Now, write a simple HTTP Endpoint and it returns the String success as shown −

package com.tutorialspoint.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 文件,如下所示 −

Next, add the app.yml file under src/main/appengine directory as shown −

runtime: java
env: flex

handlers:
- url: /.*
   script: this field is required, but ignored

现在,请转到 Google Cloud 控制台,然后单击页面顶部的激活 Google Cloud Shell。

Now, go to the Google Cloud console and click the Activate Google cloud shell at the top of the page.

activate google cloud shell

现在,使用 Google Cloud Shell 将您的源文件和 Gradle 文件移入 Google Cloud 机器的主目录中。

Now, move your source files and Gradle file into home directory of your google cloud machine by using google cloud shell.

moving to home directory using google cloud shell

现在,执行命令 gradle appengineDeploy,它会将您的应用程序部署到 Google Cloud Appengine 中。

Now, execute the command gradle appengineDeploy and it will deploy your application into the Google Cloud appengine.

Note − GCP 应启用计费并且在将您的应用程序部署到 appengine 之前,您应在 GCP 中创建 appengine 平台。

Note − GCP should be billing enabled and before deploying your application into appengine, you should create appengine platform in GCP.

将您的应用程序部署到 GCP appengine 平台需要几分钟时间。

It will take few minutes to deploy your application into GCP appengine platform.

构建成功后,您可以在控制台窗口中看到服务 URL。

After build successful you can see the Service URL in console window.

spring initializer page

现在,点击服务 URL 并查看输出。

Now, hit the service URL and see the output.

app engine development success

Google Cloud SQL

要将 Google Cloud SQL 连接到您的 Spring Boot 应用程序,您应将以下属性添加到您的 application.properties 文件中。

To connect the Google Cloud SQL into your Spring Boot application, you should add the following properties into your application.properties file.

JDBC URL Format

jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance = <GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password = <PASSWORD>

Note − Spring Boot 应用程序和 Google Cloud SQL 应位于同一 GCP 项目中。

Note − The Spring Boot application and Google Cloud SQL should be in same GCP project.

应用程序属性文件如下。

The application.properties file is given below.

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 文件中。

YAML file users can add the below properties to your application.yml file.

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 Sign-In

在本章中,我们将了解如何使用 Spring Boot 应用程序及 Gradle 构建添加 Google OAuth2 帐号登录。

In this chapter, we are going to see how to add the Google OAuth2 Sign-In by using Spring Boot application with Gradle build.

首先,在您的构建配置文件中添加 Spring Boot OAuth2 安全依赖,您的构建配置文件如下。

First, add the Spring Boot OAuth2 security dependency in your build configuration file and your build configuration file is given below.

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.tutorialspoint.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')
}

现在,在主 Spring Boot 应用程序类文件中的 Spring Boot 进行身份验证后,添加 HTTP 端点来读取用户的 Google 主体,如下所示 −

Now, add the HTTP Endpoint to read the User Principal from the Google after authenticating via Spring Boot in main Spring Boot application class file as given below −

package com.tutorialspoint.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,并移除 index.html 文件的身份验证,如下所示 −

Now, write a Configuration file to enable the OAuth2SSO for web security and remove the authentication for index.html file as shown −

package com.tutorialspoint.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("/", "/index.html")
         .permitAll()
         .anyRequest()
         .authenticated();
   }
}

接下来,在静态资源中添加 index.html 文件,并添加链接以重定向到用户 HTTP 端点来读取 Google 用户主体,如下所示 −

Next, add the index.html file under static resources and add the link to redirect into user HTTP Endpoint to read the Google user Principal as shown below −

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

Note − 在 Google Cloud 控制台中 - 启用 Gmail 服务、Analytics 服务和 Google+ 服务 API。

Note − In Google Cloud console - Enable the Gmail Services, Analytics Services and Google+ service API(s).

然后,转到凭据部分并创建凭据,然后选择 OAuth 客户端 ID。

Then, go the Credentials section and create a credentials and choose OAuth Client ID.

credentials section

接下来,在 OAuth2 同意屏幕中提供产品名称。

Next, provide a Product Name in OAuth2 consent screen.

product name in oauth2 consent screen

接下来,选择应用程序类型为“Web 应用程序”,提供授权的 JavaScript 源和授权的重定向 URI。

Next, choose the Application Type as “Web application”, provide the Authorized JavaScript origins and Authorized redirect URIs.

authorized redirect uris

现在,您的 OAuth2 客户端 ID 和客户端密钥已创建。

Now, your OAuth2 Client Id and Client Secret is created.

oauth2 client id created

接下来,在您的应用程序属性文件中添加客户端 ID 和客户端密钥。

Next, add the Client Id and Client Secret in your application properties file.

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 应用程序。

Now, you can create an executable JAR file, and run the Spring Boot application by using the following Gradle command.

对于 Gradle,您可以使用如下命令:−

For Gradle, you can use the command as shown −

gradle clean build

“BUILD SUCCESSFUL”之后,您可以在 build/libs 目录中找到 JAR 文件。

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

使用以下命令 Java -jar <JARFILE> 运行 JAR 文件,应用程序在 Tomcat 端口 8080 上启动。

Run the JAR file by using the command java –jar <JARFILE> and application is started on the Tomcat port 8080.

现在访问 URL http://localhost:8080/ 并点击 Google 登录链接。

Now hit the URL http://localhost:8080/ and click the Google Login link.

google login link

它将重定向到 Google 登录屏幕并提供 Gmail 登录详细信息。

It will redirect to the Google login screen and provide a Gmail login details.

google login screen

如果登录成功,我们将收到 Gmail 用户的主体对象。

If login success, we will receive the Principal object of the Gmail user.

principal object of the gmail user