本文来自于springboot官方文档
地址:https://docs.spring.io/spring-boot/docs/current/reference/html/
Spring Boot参考指南
作者
菲利普· 韦伯,戴夫 Syer,约什 长,斯特凡 尼科尔,罗布 绞车,安迪· 威尔金森,马塞尔 Overdijk,基督教 杜普伊斯,塞巴斯蒂安· 德勒兹,迈克尔· 西蒙斯,韦德兰Pavić
2.0.0.M3
版权所有©2012-2017
本文件的副本可供您自己使用和分发给他人,前提是您不对此类副本收取任何费用,并且每份副本均包含本版权声明,无论是以印刷版还是电子版分发。
目录
- I. Spring Boot文档
- II。入门
- III。使用Spring Boot
- IV。Spring Boot功能
-
- 23. SpringApplication
- 24.外部化配置
- 25.简介
- 26.记录
- 27.开发Web应用程序
-
- 27.1。'Spring Web MVC框架'
- 27.2。'Spring WebFlux框架'
- 27.3。JAX-RS和泽西岛
- 27.4。嵌入式servlet容器支持
- 28.安全
- 29.使用SQL数据库
- 30.使用NoSQL技术
- 31.缓存
- 32.消息传递
- 33.使用'RestTemplate'调用REST服务
- 34.使用'WebClient'调用REST服务
- 35.验证
- 36.发送电子邮件
- 37.使用JTA的分布式事务
- 38. Hazelcast
- 39. Quartz Scheduler
- 40.春季整合
- 41.春季会议
- 42.对JMX的监督和管理
- 43.测试
-
- 43.1。测试范围依赖性
- 43.2。测试Spring应用程序
- 43.3。测试Spring Boot应用程序
-
- 43.3.1。检测测试配置
- 43.3.2。排除测试配置
- 43.3.3。使用随机端口
- 43.3.4。嘲弄和间谍豆
- 43.3.5。自动配置的测试
- 43.3.6。自动配置的JSON测试
- 43.3.7。自动配置的Spring MVC测试
- 43.3.8。自动配置Spring WebFlux测试
- 43.3.9。自动配置的数据JPA测试
- 43.3.10。自动配置的JDBC测试
- 43.3.11。自动配置的jOOQ测试
- 43.3.12。自动配置的数据MongoDB测试
- 43.3.13。自动配置数据Neo4j测试
- 43.3.14。自动配置的Data Redis测试
- 43.3.15。自动配置的数据LDAP测试
- 43.3.16。自动配置的REST客户端
- 43.3.17。自动配置的Spring REST Docs测试
- 43.3.18。使用Spock测试Spring Boot应用程序
- 43.4。测试工具
- 44. WebSockets
- 45.网络服务
- 46.创建自己的自动配置
- 47.接下来要读什么
- V.弹簧启动执行器:生产就绪功能
- VI。部署Spring Boot应用程序
- 七。Spring Boot CLI
- 八。构建工具插件
- IX。'如何'指南
-
- 72. Spring Boot应用程序
- 73.属性和配置
- 74.嵌入式Web服务器
-
- 74.1。使用其他Web服务器
- 74.2。配置Jetty
- 74.3。向应用程序添加Servlet,过滤器或监听器
- 74.4。更改HTTP端口
- 74.5。使用随机未分配的HTTP端口
- 74.6。在运行时发现HTTP端口
- 74.7。配置SSL
- 74.8。配置访问日志记录
- 74.9。在前端代理服务器后面使用
- 74.10。配置Tomcat
- 74.11。使用Tomcat启用多个连接器
- 74.12。使用Tomcat的LegacyCookieProcessor
- 74.13。配置Undertow
- 74.14。使用Undertow启用多个侦听器
- 74.15。使用@ServerEndpoint创建WebSocket端点
- 74.16。启用HTTP响应压缩
- 75. Spring MVC
- 76. HTTP客户端
- 77.记录
- 78.数据访问
- 79.数据库初始化
- 80.消息传递
- 81.批量申请
- 82.执行器
- 83.安全
- 84.热插拔
- 85.建立
- 86.传统部署
- X.附录
第一部分Spring Boot文档
本节简要概述了Spring Boot参考文档。将其视为文档其余部分的映射。您可以以线性方式阅读本参考指南,或者如果您不感兴趣,可以跳过章节。
1.关于文档
Spring Boot参考指南以html, pdf 和epub文档的形式提供。最新的副本可在docs.spring.io/spring-boot/docs/current/reference上找到。
本文件的副本可供您自己使用和分发给他人,前提是您不对此类副本收取任何费用,并且每份副本均包含本版权声明,无论是以印刷版还是电子版分发。
2.获得帮助
遇到Spring Boot问题,我们想帮忙!
- 试试怎么对的 -他们最常见的问题提供解决方案。
- 学习Spring基础知识 - Spring Boot基于许多其他Spring项目构建,请访问spring.io网站以获取大量参考文档。如果您刚刚开始使用Spring,请尝试其中一个指南。
- 提出问题 - 我们监控*.com以获取标记的问题
spring-boot
。 - 在github.com/spring-projects/spring-boot/issues上使用Spring Boot报告错误。
所有Spring Boot都是开源的,包括文档!如果您发现文档有问题; 或者如果你只是想改进它们,请参与其中。 |
3.第一步
4.使用Spring Boot
准备好开始使用Spring Boot了吗?我们已经为您提供保障。
5.了解Spring Boot功能
需要有关Spring Boot核心功能的更多细节? 这是给你的!
6.转向生产
当您准备好将Spring Boot应用程序推向生产时,我们有 一些您可能喜欢的技巧!
第二部分。入门
如果您刚开始使用Spring Boot,或者一般来说是“Spring”,那么这就是您的选择!在这里,我们回答基本的“什么?”,“如何?”和“为什么?”的问题。您将找到Spring Boot的简要介绍以及安装说明。然后我们将构建我们的第一个Spring Boot应用程序,讨论一些核心原则。
8.介绍Spring Boot
Spring Boot可以轻松创建独立的,生产级的基于Spring的应用程序,您可以“运行”。我们对Spring平台和第三方库采取了自以为是的观点,因此您可以尽量少开始。大多数Spring Boot应用程序只需要很少的Spring配置。
您可以使用Spring Boot创建可以使用java -jar
或更多传统战争部署启动的Java应用程序。我们还提供了一个运行“spring脚本”的命令行工具。
我们的主要目标是:
- 为所有Spring开发提供从根本上更快且可广泛访问的入门体验。
- 开箱即用,但随着需求开始偏离默认值而迅速摆脱困境。
- 提供大类项目常见的一系列非功能性功能(例如嵌入式服务器,安全性,指标,运行状况检查,外部化配置)。
- 绝对没有代码生成,也不需要XML配置。
9.系统要求
Spring Boot 2.0.0.M3需要Java 8和Spring Framework 5.0.0.RC3或更高版本。为Maven(3.2+)和Gradle 3(3.4或更高版本)提供显式构建支持。
9.1 Servlet容器
开箱即用支持以下嵌入式servlet容器:
名称 | Servlet版本 |
---|---|
Tomcat 8.5 |
3.1 |
码头9.4 |
3.1 |
承诺1.3 |
3.1 |
您还可以将Spring Boot应用程序部署到任何Servlet 3.0+兼容容器。
10.安装Spring Boot
Spring Boot可以与“经典”Java开发工具一起使用,也可以作为命令行工具安装。无论如何,您将需要Java SDK v1.8或更高版本。您应该在开始之前检查当前的Java安装:
$ java -version
If you are new to Java development, or if you just want to experiment with Spring Boot you might want to try the Spring Boot CLI first, otherwise, read on for “classic” installation instructions.
10.1 Installation instructions for the Java developer
You can use Spring Boot in the same way as any standard Java library. Simply include the appropriate spring-boot-*.jar
files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor; and there is nothing special about a Spring Boot application, so you can run and debug as you would any other Java program.
Although you could just copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).
10.1.1 Maven installation
Spring Boot is compatible with Apache Maven 3.2 or above. If you don’t already have Maven installed you can follow the instructions at maven.apache.org.
On many operating systems Maven can be installed via a package manager. If you’re an OSX Homebrew user try |
Spring Boot dependencies use the org.springframework.boot
groupId
. Typically your Maven POM file will inherit from the spring-boot-starter-parent
project and declare dependencies to one or more “Starters”. Spring Boot also provides an optional Maven plugin to create executable jars.
Here is a typical 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.example </ groupId>
<artifactId> myproject </ artifactId>
<version> 0.0.1-SNAPSHOT </ version> <! - 继承默认值为Spring Boot - >
<parent>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-parent </ artifactId>
<version> 2.0.0.M3 < / version>
</ parent> <! - 添加Web应用程序的典型依赖项 - >
<dependencies>
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-web </ artifactId>
</ dependency>
</依赖> <! - 打包为可执行jar - >
<build>
<plugins>
<plugin>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-maven-plugin </ artifactId>
</ plugin >
</ plugins>
</ build> <! - 添加Spring存储库 - >
<! - (如果使用的是.RELEASE版本,则不需要这样) - >
<存储库>
<存储库>
<id> spring-snapshots </ id>
< url> http://repo.spring.io/snapshot </ url>
<snapshots> <enabled> true </ enabled> </ snapshots>
</ repository>
<repository>
<id> spring-milestones </ id>
< url> http://repo.spring.io/milestone </ url>
</ repository>
</ repositories>
<pluginRepositories>
<pluginRepository>
<id> spring-snapshots </ id>
<url>http://repo.spring.io/snapshot </ url>
</ pluginRepository>
<pluginRepository>
<id> spring-milestones </ id>
<url> http://repo.spring.io/milestone </ url>
</ pluginRepository>
</ pluginRepositories>
</ project>
这 |
10.1.2 Gradle安装
Spring Boot与Gradle 3(3.4或更高版本)兼容。如果您尚未安装Gradle,则可以按照www.gradle.org/上的说明进行操作。
Spring Boot依赖项可以使用org.springframework.boot
group
。通常,您的项目将声明依赖于一个或多个 “Starters”。Spring Boot提供了一个有用的Gradle插件 ,可用于简化依赖声明和创建可执行jar。
Gradle Wrapper
当您需要构建项目时,Gradle Wrapper提供了一种“获取”Gradle的好方法。这是一个小脚本和库,您可以与代码一起提交以引导构建过程。有关详细信息,请参见docs.gradle.org/3.4.1/userguide/gradle_wrapper.html。
这是一个典型的build.gradle
文件:
buildscript {
存储库{
jcenter()
maven {url'http ://repo.spring.io/snapshot' }
maven {url'http ://repo.spring.io/milestone' }
}
依赖{
classpath'org.springframework.boot :spring-boot-gradle-plugin:2.0.0.M3'
}
} apply plugin:' java'apply
plugin:'org.springframework.boot'apply
plugin:'io.spring.dependency-management' jar {
baseName = 'myproject'version
= '0.0.1-SNAPSHOT'
} 存储库{
jcenter()
maven {url “http://repo.spring.io/snapshot” }
maven {url “http://repo.spring.io/milestone” }
} 依赖{
编译(“org.springframework.boot:spring-boot-starter-web”)
testCompile(“org.springframework.boot:spring-boot-starter-test”)
}
10.2安装Spring Boot CLI
Spring Boot CLI是一个命令行工具,如果您想快速使用Spring进行原型设计,可以使用它。它允许您运行Groovy脚本,这意味着您有一个熟悉的类似Java的语法,没有太多的样板代码。
您不需要使用CLI来使用Spring Boot,但它绝对是实现Spring应用程序的最快方法。
10.2.1手动安装
您可以从Spring软件库下载Spring CLI发行版:
还提供最先进的快照分发。
下载完成后,请按照 解压缩的存档中的INSTALL.txt说明进行操作。总结:文件中的目录中有一个spring
脚本(spring.bat
对于Windows),或者您也可以使用该文件(脚本可以帮助您确保正确设置类路径)。bin/
.zip
java -jar
.jar
10.2.2使用SDKMAN安装!
SDKMAN!(软件开发工具包管理器)可用于管理各种二进制SDK的多个版本,包括Groovy和Spring Boot CLI。获取SDKMAN!来自sdkman.io并安装Spring Boot
$ sdk install springboot
$ spring --version
Spring Boot v2.0.0.M3
如果您正在为CLI开发功能并希望轻松访问刚构建的版本,请遵循这些额外说明。
$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.0.0.M3-bin/spring-2.0.0.M3/
$ sdk默认springboot dev
$ spring --version
Spring CLI v2.0.0.M3
这将安装一个spring
名为dev
实例的本地实例。它指向您的目标构建位置,因此每次重建Spring Boot时,spring
都将是最新的。
你可以通过这样做看到它:
$ sdk ls springboot ================================================== ==============================
可用的Springboot版本
================================================== ==============================
> + dev
* 2.0.0.M3 ================================================== ==============================
+ - 本地版本
* - 已安装
> - 目前正在使用中
================================================== ==============================
10.2.3 OSX Homebrew安装
如果您使用的是Mac并使用Homebrew,那么安装Spring Boot CLI所需要做的就是:
$ brew tap pivotal / tap
$ brew install springboot
Homebrew将安装spring
到/usr/local/bin
。
如果您没有看到公式,那么您的brew安装可能已过时。只需执行 |
10.2.4安装MacPorts
如果您使用的是Mac并使用MacPorts,那么安装Spring Boot CLI所需要做的就是:
$ sudo port install spring-boot-cli
10.2.5命令行完成
Spring Boot CLI附带了为BASH和 zsh shell 提供命令完成的脚本 。您可以在任何shell中创建source
脚本(也称为 spring
),或者将其放在个人或系统范围的bash完成初始化中。在Debian系统上,系统范围的脚本都在,/shell-completion/bash
并且当新shell启动时,该目录中的所有脚本都会被执行。要手动运行脚本,例如,如果已使用SDKMAN安装!
$。〜/ .sdkman /候选人/ springboot /电流/壳完成/庆典/弹簧
$ spring <HIT TAB HERE>
抓住帮助jar运行测试版
如果使用Homebrew或MacPorts安装Spring Boot CLI,命令行完成脚本将自动注册到shell。 |
10.2.6快速启动Spring CLI示例
这是一个非常简单的Web应用程序,可用于测试您的安装。创建一个名为的文件app.groovy
:
@RestController
类 ThisWillActuallyRun { @RequestMapping( “/”)
String home(){
“你好,世界!”
} }
然后只需从shell运行它:
$ spring run app.groovy
首次运行应用程序时需要一些时间,因为下载了依赖项。后续运行会更快。 |
在您喜欢的Web浏览器中打开localhost:8080,您应该看到以下输出:
你好,世界!
11.开发您的第一个Spring Boot应用程序
让我们用Java开发一个简单的“Hello World!”Web应用程序,它突出了一些Spring Boot的主要功能。我们将使用Maven来构建这个项目,因为大多数IDE都支持它。
该spring.io网站包含使用Spring的引导许多“入门”指南。如果你想解决一个特定的问题; 先检查那里。 您可以通过转到start.spring.io并 |
在开始之前,打开终端以检查您是否安装了有效的Java和Maven版本。
$ java -version
java版“1.8.0_102”
Java(TM)SE运行时环境(版本1.8.0_102-b14)
Java HotSpot(TM)64位服务器VM(版本25.102-b14,混合模式)
$ mvn -v
Apache Maven 3.3.9(bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47 + 00:00)
Maven home:/usr/local/Cellar/maven/3.3.9/libexec
Java版本:1.8.0_102,供应商:Oracle Corporation
此示例需要在其自己的文件夹中创建。后续说明假定您已创建合适的文件夹,并且它是您的“当前目录”。 |
11.1创建POM
我们需要从创建Maven 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.example </ groupId>
<artifactId> myproject </ artifactId>
<version> 0.0.1-SNAPSHOT </ version> <parent>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-parent </ artifactId>
<version> 2.0.0.M3 </ version>
</ parent> <! - 这里要添加的其他行...... - > <! - (如果您使用的是.RELEASE版本,则不需要此项) - >
<repositories>
<repository>
<id> spring-snapshots </ id>
<url> http://repo.spring。 io / snapshot </ url>
<snapshots> <enabled> true </ enabled> </ snapshots>
</ repository>
<repository>
<id> spring-milestones </ id>
<url> http://repo.spring。 io / milestone </ url>
</ repository>
</ repositories>
<pluginRepositories>
<pluginRepository>
<id> spring-snapshots </ id>
<url> http://repo.spring.io/snapshot </ url>
</ pluginRepository>
<pluginRepository>
<id> spring-milestones </ id>
<url> http://repo.spring.io/milestone </ url>
</ pluginRepository>
</ pluginRepositories>
</ project>
这应该给你一个工作的构建,你可以通过运行测试它mvn package
(你可以忽略“jar将是空的 - 没有内容被标记为包含!”警告现在)。
此时,您可以将项目导入IDE(大多数现代Java IDE包含对Maven的内置支持)。为简单起见,我们将继续为此示例使用纯文本编辑器。 |
11.2添加类路径依赖项
Spring Boot提供了许多“Starters”,可以轻松地将jar添加到类路径中。我们的示例应用程序已经spring-boot-starter-parent
在parent
POM部分中使用过 。这spring-boot-starter-parent
是一个特殊的启动器,提供有用的Maven默认值。它还提供了一个 dependency-management
部分,以便您可以省略version
“祝福”依赖项的标记。
其他“Starters”只提供在开发特定类型的应用程序时可能需要的依赖项。由于我们正在开发一个Web应用程序,我们将添加一个spring-boot-starter-web
依赖项 - 但在此之前,让我们看看我们目前拥有的内容。
$ mvn依赖:树 [INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
该mvn dependency:tree
命令打印项目依赖项的树表示。您可以看到它spring-boot-starter-parent
本身不提供依赖关系。让我们编辑我们pom.xml
并spring-boot-starter-web
在该parent
部分下面添加依赖项:
<dependencies>
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-web </ artifactId>
</ dependency>
</ dependencies>
如果mvn dependency:tree
再次运行,您将看到现在有许多其他依赖项,包括Tomcat Web服务器和Spring Boot本身。
11.3编写代码
要完成我们的应用程序,我们需要创建一个Java文件。Maven将src/main/java
默认编译源代码,因此您需要创建该文件夹结构,然后添加一个名为的文件src/main/java/Example.java
:
import org.springframework.boot。*;
import org.springframework.boot.autoconfigure。*;
import org.springframework.stereotype。*;
import org.springframework.web.bind.annotation。*; @RestController
@EnableAutoConfiguration
公共 类示例{ @RequestMapping( “/”)
String home(){
返回 “Hello World!” ;
} public static void main(String [] args)throws Exception {
SpringApplication.run(例如.class,args);
} }
虽然这里的代码不多,但还是有很多代码。让我们逐步完成重要部分。
11.3.1 @RestController和@RequestMapping注释
我们Example
班上的第一个注释是@RestController
。这被称为 构造型注释。它为阅读代码的人提供了提示,对于Spring,该类扮演着特定的角色。在这种情况下,我们的类是一个Web,@Controller
所以Spring在处理传入的Web请求时会考虑它。
该@RequestMapping
注释提供“路由”的信息。它告诉Spring,任何带有路径“/”的HTTP请求都应该映射到该home
方法。该 @RestController
注解告诉Spring使得到的字符串直接返回给调用者。
在 |
11.3.2 @EnableAutoConfiguration注释
The second class-level annotation is @EnableAutoConfiguration
. This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web
added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.
Starters and Auto-Configuration
Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You are free to pick-and-choose jar dependencies outside of the starters and Spring Boot will still do its best to auto-configure your application.
11.3.3 The “main” method
The final part of our application is the main
method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication
class by calling run
. SpringApplication
will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server. We need to pass Example.class
as an argument to the run
method to tell SpringApplication
which is the primary Spring component. The args
array is also passed through to expose any command-line arguments.
11.4 Running the example
At this point our application should work. Since we have used the spring-boot-starter-parent
POM we have a useful run
goal that we can use to start the application. Type mvn spring-boot:run
from the root project directory to start the application:
$ mvn spring-boot:run 。____ _ __ _ _
/ \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
(()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \
\\ / ___)| | _)| | | | | || (_ | |))))
'| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / /
========= | _ | ============== | ___ / = / _ / _ / _ /
:: Spring Boot ::(v2.0.0.M3)
....... 。。
....... 。。(此处输出日志)
....... 。。
........ 2.222秒启动示例(JVM运行6.514)
如果您打开到localhost:8080的Web浏览器,您应该看到以下输出:
你好,世界!
要优雅地退出应用程序命中ctrl-c
。
11.5创建可执行jar
让我们通过创建一个完全自包含的可执行jar文件来完成我们的示例,我们可以在生产中运行它。可执行jar(有时称为“fat jar”)是包含已编译类以及代码需要运行的所有jar依赖项的归档。
可执行的jar和Java
Java没有提供任何标准方法来加载嵌套的jar文件(即jar文件本身包含在jar中)。如果您要分发自包含的应用程序,这可能会有问题。
为了解决这个问题,许多开发人员使用“超级”罐子。一个超级jar简单地将所有类中的所有类打包成一个存档。这种方法的问题在于,很难看到您在应用程序中实际使用的库。如果在多个罐子中使用相同的文件名(但具有不同的内容),也可能会有问题。
Spring Boot采用不同的方法,允许您直接嵌套jar。
要创建一个可执行jar,我们需要添加spring-boot-maven-plugin
到我们的 pom.xml
。在该dependencies
部分正下方插入以下行:
<build>
<plugins>
<plugin>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-maven-plugin </ artifactId>
</ plugin>
</ plugins>
</ build>
所述 |
保存pom.xml
并从命令行运行mvn package
:
$ mvn包 [INFO]扫描项目......
[信息]
[INFO] ----------------------------------------------- -------------------------
[INFO]构建myproject 0.0.1-SNAPSHOT
[INFO] ----------------------------------------------- -------------------------
[INFO] ....
[INFO] --- maven-jar-plugin:2.4:jar(default-jar)@ myproject ---
[INFO]构建jar:/Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[信息]
[INFO] --- spring-boot-maven-plugin:2.0.0.M3:重新打包(默认)@ myproject ---
[INFO] ----------------------------------------------- -------------------------
[信息]建立成功
[INFO] ----------------------------------------------- -------------------------
如果你查看target
目录,你应该看到myproject-0.0.1-SNAPSHOT.jar
。该文件大小应为10 MB左右。如果你想偷看内部,你可以使用jar tvf
:
$ jar tvf target / myproject-0.0.1-SNAPSHOT.jar
您还应该看到目录中命名myproject-0.0.1-SNAPSHOT.jar.original
的文件小得多target
。这是Maven在Spring Boot重新打包之前创建的原始jar文件。
要运行该应用程序,请使用以下java -jar
命令:
$ java -jar target / myproject-0.0.1-SNAPSHOT.jar 。____ _ __ _ _
/ \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
(()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \
\\ / ___)| | _)| | | | | || (_ | |))))
'| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / /
========= | _ | ============== | ___ / = / _ / _ / _ /
:: Spring Boot ::(v2.0.0.M3)
....... 。。
....... 。。(此处输出日志)
....... 。。
........ 2.536秒启动示例(JVM运行2.864)
和以前一样,优雅地退出应用程序命中ctrl-c
。
12.接下来要读什么
希望本节为您提供了一些Spring Boot基础知识,并帮助您编写自己的应用程序。如果您是面向任务的开发人员类型,您可能需要跳转到spring.io并查看一些 入门指南,这些指南解决了具体的“如何使用Spring执行此操作”问题; 我们还有Spring Boot特定 的操作方法参考文档。
在春季启动库也有 一堆样品可以运行。样本独立于其余代码(即您无需构建其余代码来运行或使用示例)。
否则,下一个逻辑步骤是阅读第III部分“使用Spring Boot”。如果你真的不耐烦,你也可以跳过去阅读 Spring Boot功能。
第三部分。使用Spring Boot
本节详细介绍了如何使用Spring Boot。它涵盖了诸如构建系统,自动配置以及如何运行应用程序等主题。我们还介绍了一些Spring Boot最佳实践。虽然Spring Boot没有什么特别之处(它只是你可以使用的另一个库),但有一些建议,如果遵循这些建议,将使您的开发过程更容易一些。
如果您刚刚开始使用Spring Boot,那么在深入了解本节之前,您应该阅读“ 入门指南”。
13.构建系统
强烈建议您选择支持依赖关系管理的构建系统 ,并且可以使用发布到“Maven Central”存储库的工件。我们建议您选择Maven或Gradle。可以让Spring Boot与其他构建系统(例如Ant)一起工作,但它们不会得到特别好的支持。
13.1依赖管理
每个版本的Spring Boot都提供了它支持的依赖项的精选列表。实际上,您不需要为构建配置中的任何这些依赖项提供版本,因为Spring Boot正在为您管理这些依赖项。当您升级Spring Boot时,这些依赖项也将以一致的方式升级。
You can still specify a version and override Spring Boot’s recommendations if you feel that’s necessary. |
The curated list contains all the spring modules that you can use with Spring Boot as well as a refined list of third party libraries. The list is available as a standard Bills of Materials (spring-boot-dependencies
) that can be used with both Maven and Gradle.
Each release of Spring Boot is associated with a base version of the Spring Framework so we highly recommend you to not specify its version on your own. |
13.2 Maven
Maven users can inherit from the spring-boot-starter-parent
project to obtain sensible defaults. The parent project provides the following features:
- Java 1.8 as the default compiler level.
- UTF-8 source encoding.
- A Dependency Management section, allowing you to omit
<version>
tags for common dependencies, inherited from thespring-boot-dependencies
POM. - Sensible resource filtering.
- Sensible plugin configuration (exec plugin, surefire, Git commit ID, shade).
- Sensible resource filtering for
application.properties
andapplication.yml
including profile-specific files (e.g.application-foo.properties
andapplication-foo.yml
)
On the last point: since the default config files accept Spring style placeholders (${…}
) the Maven filtering is changed to use @..@
placeholders (you can override that with a Maven property resource.delimiter
).
13.2.1 Inheriting the starter parent
To configure your project to inherit from the spring-boot-starter-parent
simply set the parent
:
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M3</version>
</parent>
You should only need to specify the Spring Boot version number on this dependency. If you import additional starters, you can safely omit the version number. |
With that setup, you can also override individual dependencies by overriding a property in your own project. For instance, to upgrade to another Spring Data release train you’d add the following to your pom.xml
.
<properties>
<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>
Check the |
13.2.2 Using Spring Boot without the parent POM
Not everyone likes inheriting from the spring-boot-starter-parent
POM. You may have your own corporate standard parent that you need to use, or you may just prefer to explicitly declare all your Maven configuration.
If you don’t want to use the spring-boot-starter-parent
, you can still keep the benefit of the dependency management (but not the plugin management) by using a scope=import
dependency:
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.0.M3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
That setup does not allow you to override individual dependencies using a property as explained above. To achieve the same result, you’d need to add an entry in thedependencyManagement
of your project before the spring-boot-dependencies
entry. For instance, to upgrade to another Spring Data release train you’d add the following to your pom.xml
.
<dependencyManagement>
<dependencies>
<! - 覆盖Spring Boot提供的Spring Data版本系列 - >
<dependency>
<groupId> org.springframework.data </ groupId>
<artifactId> spring-data-releasetrain </ artifactId>
< version> Fowler-SR2 </ version>
<scope> import </ scope>
<type> pom </ type>
</ dependency>
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot -dependencies </ artifactId>
<version>2.0.0.M3 </ version>
<type> pom</ type>
<scope> import </ scope>
</ dependency>
</ dependencies>
</ dependencyManagement>
在上面的示例中,我们指定了BOM,但是可以通过这种方式覆盖任何依赖关系类型。 |
13.2.3使用Spring Boot Maven插件
Spring Boot包含一个Maven插件 ,可以将项目打包为可执行jar。<plugins>
如果要使用它,请将插件添加到您的部分:
<build>
<plugins>
<plugin>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-maven-plugin </ artifactId>
</ plugin>
</ plugins>
</ build>
如果使用Spring Boot启动程序父pom,则只需添加插件,除非要更改父项中定义的设置,否则无需对其进行配置。 |
13.4蚂蚁
可以使用Apache Ant + Ivy构建Spring Boot项目。该 spring-boot-antlib
“的antlib”模块还可以帮助蚂蚁创建可执行的JAR文件。
要声明依赖项,典型ivy.xml
文件将如下所示:
<ivy-module version = “2.0” >
<info organization = “org.springframework.boot” module = “spring-boot-sample-ant” />
<configurations>
<conf name = “compile” description = “所需的一切编译此模块“ />
<conf name = ”runtime“ extends = ”compile“ description = ”运行此模块所需的一切“ />
</ configurations>
<dependencies>
<依赖 org =“org.springframework.boot” name = “spring-boot-starter”
rev = “$ {spring-boot.version}” conf = “compile” />
</ dependencies>
</ ivy-module>
典型的build.xml
看起来像这样:
<project
xmlns:ivy = “antlib:org.apache.ivy.ant”
xmlns:spring-boot = “antlib:org.springframework.boot.ant”
name = “myapp” default = “build” > <property name = “spring-boot.version” value = “1.3.0.BUILD-SNAPSHOT” /> <target name = “resolve” description = “ - >使用常春藤检索依赖关系” >
<ivy:retrieve pattern = “lib / [conf] / [artifact] - [type] - [revision]。[ext]” />
</目标> <target name = “classpaths” depends = “resolve” >
<path id = “compile.classpath” >
<fileset dir = “lib / compile” includes = “* .jar” />
</ path>
</ target> <target name = “init” depends = “classpaths” >
<mkdir dir = “build / classes” />
</ target> <target name = “compile” depends = “init” description = “compile” >
<javac srcdir = “src / main / java” destdir = “build / classes” classpathref = “compile.classpath” />
</ target> <target name = “build” depends = “compile” >
<spring-boot:exejar destfile = “build / myapp.jar” classes = “build / classes” >
<spring-boot:lib>
<fileset dir = “lib / runtime“ />
</ spring-boot:lib>
</ spring-boot:exejar>
</ target>
</ project>
如果您不想使用该模块,请参见第85.9节“从Ant构建可执行存档而不使用spring-boot-antlib” “操作方法” |
13.5初学者
启动器是一组方便的依赖关系描述符,您可以在应用程序中包含这些描述符。您可以获得所需的所有Spring和相关技术的一站式服务,而无需搜索示例代码并复制粘贴的依赖描述符。例如,如果您想开始使用Spring和JPA进行数据库访问,只需spring-boot-starter-data-jpa
在项目中包含依赖项,就可以了。
启动器包含许多依赖项,这些依赖项是使项目快速启动和运行所需的依赖项,以及一组受支持的托管传递依赖项。
什么是名字
所有官方首发都遵循类似的命名模式; spring-boot-starter-*
,哪里*
是特定类型的应用程序。此命名结构旨在帮助您找到启动器。许多IDE中的Maven集成允许您按名称搜索依赖项。例如,安装了适当的Eclipse或STS插件后,您只需点击ctrl-space
POM编辑器并输入“spring-boot-starter”即可获得完整列表。
正如创建自己的启动程序 部分所述,第三方启动程序不应该spring-boot
以为官方Spring Boot工件保留的方式开头。acme
通常会命名 第三方启动器acme-spring-boot-starter
。
以下应用程序启动程序由Spring Boot在org.springframework.boot
组下提供 :
Table 13.1. Spring Boot application starters
Name | Description | Pom |
---|---|---|
|
Core starter, including auto-configuration support, logging and YAML |
|
|
Starter for JMS messaging using Apache ActiveMQ |
|
|
Starter for using Spring AMQP and Rabbit MQ |
|
|
Starter for aspect-oriented programming with Spring AOP and AspectJ |
|
|
Starter for JMS messaging using Apache Artemis |
|
|
Starter for using Spring Batch |
|
|
Starter for using Spring Framework’s caching support |
|
|
Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku |
|
|
Starter for using Cassandra distributed database and Spring Data Cassandra |
|
|
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive |
|
|
Starter for using Couchbase document-oriented database and Spring Data Couchbase |
|
|
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch |
|
|
Starter for using Spring Data JPA with Hibernate |
|
|
Starter for using Spring Data LDAP |
|
|
Starter for using MongoDB document-oriented database and Spring Data MongoDB |
|
|
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive |
|
|
Starter for using Neo4j graph database and Spring Data Neo4j |
|
|
Starter for using Redis key-value data store with Spring Data Redis and the Jedis client |
|
|
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client |
|
|
Starter for exposing Spring Data repositories over REST using Spring Data REST |
|
|
Starter for using the Apache Solr search platform with Spring Data Solr |
|
|
Starter for building MVC web applications using FreeMarker views |
|
|
Starter for building MVC web applications using Groovy Templates views |
|
|
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS |
|
|
Starter for using Spring Integration |
|
|
Starter for using JDBC with the Tomcat JDBC connection pool |
|
|
Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to |
|
|
Starter for using jOOQ to access SQL databases. An alternative to |
|
|
Starter for JTA transactions using Atomikos |
|
|
Starter for JTA transactions using Bitronix |
|
|
Spring Boot Narayana JTA Starter |
|
|
Starter for using Java Mail and Spring Framework’s email sending support |
|
|
Starter for building web applications using Spring Mobile |
|
|
Starter for building web applications using Mustache views |
|
|
Spring Boot Quartz Starter |
|
|
Starter for using Spring Security |
|
|
Starter for using Spring Social Facebook |
|
|
Stater for using Spring Social LinkedIn |
|
|
Starter for using Spring Social Twitter |
|
|
Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito |
|
|
Starter for building MVC web applications using Thymeleaf views |
|
|
Starter for using Java Bean Validation with Hibernate Validator |
|
|
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container |
|
|
Starter for using Spring Web Services |
|
|
Starter for building WebFlux applications using Spring Framework’s Reactive Web support |
|
|
Starter for building WebSocket applications using Spring Framework’s WebSocket support |
In addition to the application starters, the following starters can be used to add production ready features:
Table 13.2. Spring Boot production starters
Name | Description | Pom |
---|---|---|
|
Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application |
Finally, Spring Boot also includes some starters that can be used if you want to exclude or swap specific technical facets:
Table 13.3. Spring Boot technical starters
Name | Description | Pom |
---|---|---|
|
Starter for using Jetty as the embedded servlet container. An alternative to |
|
|
Starter for reading and writing json |
|
|
Starter for using Log4j2 for logging. An alternative to |
|
|
Starter for logging using Logback. Default logging starter |
|
|
Starter for using Reactor Netty as the embedded reactive HTTP server. |
|
|
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by |
|
|
Starter for using Undertow as the embedded servlet container. An alternative to |
有关其他社区的列表贡献首先,看 README文件中 |
14.构建代码
Spring Boot不需要任何特定的代码布局,但是,有一些最佳实践可以提供帮助。
14.1使用“默认”包
当一个类不包含package
声明时,它被认为是在“默认包”中。通常不鼓励使用“默认包”,应该避免使用。这可能会导致使用Spring的启动应用程序的特殊问题@ComponentScan
,@EntityScan
或@SpringBootApplication
注解,因为从每一个罐子每一个类,将被读取。
我们建议您遵循Java推荐的包命名约定并使用反向域名(例如, |
14.2找到主应用程序类
我们通常建议您将主应用程序类放在其他类之上的根包中。该@EnableAutoConfiguration
注解往往放在你的主类,它隐含地定义为某些项目一基地“搜索包”。例如,如果您正在编写JPA应用程序,@EnableAutoConfiguration
则将使用带注释的类的包 来搜索@Entity
项目。
使用根包还允许使用@ComponentScan
注释而无需指定basePackage
属性。@SpringBootApplication
如果主类位于根包中,也可以使用 注释。
这是一个典型的布局:
COM
+ - 例子
+ - myproject
+ - Application.java
|
+ - 域名
| + - Customer.java
| + - CustomerRepository.java
|
+ - 服务
| + - CustomerService.java
|
+ - 网络
+ - CustomerController.java
该Application.java
文件将声明该main
方法以及基本方法 @Configuration
。
package com.example.myproject; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application { public static void main(String [] args){
SpringApplication.run(Application.class, args);
} }
15. Configuration classes
Spring Boot favors Java-based configuration. Although it is possible to use SpringApplication
with an XML sources, we generally recommend that your primary source is a single @Configuration
class. Usually the class that defines the main
method is also a good candidate as the primary @Configuration
.
Many Spring configuration examples have been published on the Internet that use XML configuration. Always try to use the equivalent Java-based configuration if possible. Searching for |
15.1 Importing additional configuration classes
You don’t need to put all your @Configuration
into a single class. The @Import
annotation can be used to import additional configuration classes. Alternatively, you can use @ComponentScan
to automatically pick up all Spring components, including @Configuration
classes.
15.2 Importing XML configuration
If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration
class. You can then use an additional @ImportResource
annotation to load XML configuration files.
16. Auto-configuration
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDB
is on your classpath, and you have not manually configured any database connection beans, then we will auto-configure an in-memory database.
You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration
or @SpringBootApplication
annotations to one of your @Configuration
classes.
You should only ever add one |
16.1 Gradually replacing auto-configuration
Auto-configuration is noninvasive, at any point you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own DataSource
bean, the default embedded database support will back away.
If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug
switch. This will enable debug logs for a selection of core loggers and log an auto-configuration report to the console.
16.2禁用特定的自动配置
如果您发现正在应用您不想要的特定自动配置类,则可以使用exclude属性@EnableAutoConfiguration
来禁用它们。
import org.springframework.boot.autoconfigure。*;
import org.springframework.boot.autoconfigure.jdbc。*;
import org.springframework.context.annotation。*; @Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
如果类不在类路径上,则可以使用excludeName
注释的属性并指定完全限定名称。最后,您还可以控制要通过spring.autoconfigure.exclude
属性排除的自动配置类列表 。
您可以在注释级别和使用属性定义排除项。 |
17. Spring Beans和依赖注入
您可以*地使用任何标准的Spring Framework技术来定义bean及其注入的依赖项。为简单起见,我们经常发现使用@ComponentScan
找到你的bean,结合@Autowired
构造函数注入效果很好。
如果按照上面的建议构建代码(在根包中定位应用程序类),则可以添加@ComponentScan
不带任何参数的代码。您的所有应用程序组件(的@Component
,@Service
,@Repository
,@Controller
等)将自动注册为春豆。
下面是一个示例@Service
Bean,它使用构造函数注入来获取所需的RiskAssessor
bean。
package com.example.service; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class DatabaseAccountService实现 AccountService { 私人 最终 RiskAssessor riskAssessor; @Autowired
public DatabaseAccountService(RiskAssessor riskAssessor){
this .riskAssessor = riskAssessor;
} // ... }
如果bean有一个构造函数,你可以省略@Autowired
。
@Service
public class DatabaseAccountService实现 AccountService { 私人 最终 RiskAssessor riskAssessor; public DatabaseAccountService(RiskAssessor riskAssessor){
this .riskAssessor = riskAssessor;
} // ... }
请注意使用构造函数注入如何将 |
18.使用@SpringBootApplication批注
许多春季引导开发者总是有其主类注解为@Configuration
, @EnableAutoConfiguration
和@ComponentScan
。由于这些注释经常一起使用(特别是如果您遵循 上面的最佳实践),Spring Boot提供了一个方便的@SpringBootApplication
替代方案。
该@SpringBootApplication
注解相当于使用@Configuration
, @EnableAutoConfiguration
并@ComponentScan
与他们的默认属性:
package com.example.myproject; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication //与@Configuration相同@EnableAutoConfiguration @ComponentScan
public class Application { public static void main(String [] args){
SpringApplication.run(Application .class,args);
} }
|
19.运行您的应用程序
将应用程序打包为jar并使用嵌入式HTTP服务器的最大优势之一是,您可以像运行任何其他应用程序一样运行应用程序。调试Spring Boot应用程序也很容易; 您不需要任何特殊的IDE插件或扩展。
本节仅介绍基于jar的打包,如果选择将应用程序打包为war文件,则应参阅服务器和IDE文档。 |
19.1从IDE运行
您可以从IDE运行Spring Boot应用程序作为简单的Java应用程序,但是,首先您需要导入项目。导入步骤将根据您的IDE和构建系统而有所不同。大多数IDE可以直接导入Maven项目,例如Eclipse用户可以从菜单中选择Import…
→ 。Existing Maven Projects
File
如果无法将项目直接导入IDE,则可以使用构建插件生成IDE元数据。Maven包含Eclipse和 IDEA的插件 ; Gradle提供各种IDE的插件。
如果您不小心运行Web应用程序两次,您将看到“端口已在使用中”错误。STS用户可以使用该 |
19.2作为打包应用程序运行
如果您使用Spring Boot Maven或Gradle插件来创建可执行jar,则可以使用它来运行您的应用程序java -jar
。例如:
$ java -jar target / myproject-0.0.1-SNAPSHOT.jar
也可以运行启用了远程调试支持的打包应用程序。这允许您将调试器附加到打包的应用程序:
$ java -Xdebug -Xrunjdwp:server = y,transport = dt_socket,address = 8000,suspend = n \
-jar target / myproject-0.0.1-SNAPSHOT.jar
19.3使用Maven插件
Spring Boot Maven插件包含一个run
可用于快速编译和运行应用程序的目标。应用程序以分解形式运行,就像在IDE中一样。
$ mvn spring-boot:run
您可能还想使用有用的操作系统环境变量:
$ export MAVEN_OPTS = -Xmx1024m
19.4使用Gradle插件
Spring Boot Gradle插件还包含一个bootRun
任务,可用于以爆炸形式运行您的应用程序。该bootRun
每当你应用的任务添加org.springframework.boot
和java
插件:
$ gradle bootRun
您可能还想使用此有用的操作系统环境变量:
$ export JAVA_OPTS = -Xmx1024m
19.5热插拔
由于Spring Boot应用程序只是普通的Java应用程序,因此JVM热交换应该是开箱即用的。JVM热交换在某种程度上受限于它可以替换的字节码,因为可以使用更完整的解决方案 JRebel。该 spring-boot-devtools
模块还包括对快速应用程序重启的支持。
有关详细信息,请参阅下面的第20章“ 开发人员工具”部分和 热交换“操作方法”。
20.开发人员工具
Spring Boot包含一组额外的工具,可以使应用程序开发体验更加愉快。该spring-boot-devtools
模块可以包含在任何项目中,以提供额外的开发时间功能。要包含devtools支持,只需将模块依赖项添加到您的构建:
Maven的。
<dependencies>
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-devtools </ artifactId>
<optional> true </ optional>
</ dependency>
</ dependencies>
摇篮。
依赖{
compile(“org.springframework.boot:spring-boot-devtools”)
}
运行完全打包的应用程序时会自动禁用开发人员工具。如果您的应用程序是使用启动的, |
重新打包的归档默认情况下不包含devtools。如果要使用 某些远程devtools功能,则需要禁用 |
20.1财产违约
Several of the libraries supported by Spring Boot use caches to improve performance. For example, template engines will cache compiled templates to avoid repeatedly parsing template files. Also, Spring MVC can add HTTP caching headers to responses when serving static resources.
Whilst caching is very beneficial in production, it can be counter productive during development, preventing you from seeing the changes you just made in your application. For this reason, spring-boot-devtools will disable those caching options by default.
Cache options are usually configured by settings in your application.properties
file. For example, Thymeleaf offers the spring.thymeleaf.cache
property. Rather than needing to set these properties manually, the spring-boot-devtools
module will automatically apply sensible development-time configuration.
For a complete list of the properties that are applied see DevToolsPropertyDefaultsPostProcessor. |
20.2 Automatic restart
Applications that use spring-boot-devtools
will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.
Triggering a restart
As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath. The way in which you cause the classpath to be updated depends on the IDE that you are using. In Eclipse, saving a modified file will cause the classpath to be updated and trigger a restart. In IntelliJ IDEA, building the project (Build -> Make Project
) will have the same effect.
You can also start your application via the supported build plugins (i.e. Maven and Gradle) as long as forking is enabled since DevTools need an isolated application classloader to operate properly. Gradle and Maven do that by default when they detect DevTools on the classpath. |
Automatic restart works very well when used with LiveReload. See below for details. If you use JRebel automatic restarts will be disabled in favor of dynamic class reloading. Other devtools features (such as LiveReload and property overrides) can still be used. |
DevTools relies on the application context’s shutdown hook to close it during a restart. It will not work correctly if you have disabled the shutdown hook ( |
When deciding if an entry on the classpath should trigger a restart when it changes, DevTools automatically ignores projects named |
DevTools needs to customize the |
Restart vs Reload
The restart technology provided by Spring Boot works by using two classloaders. Classes that don’t change (for example, those from third-party jars) are loaded into a base classloader. Classes that you’re actively developing are loaded into a restart classloader. When the application is restarted, the restart classloader is thrown away and a new one is created. This approach means that application restarts are typically much faster than “cold starts” since the base classloader is already available and populated.
If you find that restarts aren’t quick enough for your applications, or you encounter classloading issues, you could consider reloading technologies such as JRebelfrom ZeroTurnaround. These work by rewriting classes as they are loaded to make them more amenable to reloading.
20.2.1 Excluding resources
Certain resources don’t necessarily need to trigger a restart when they are changed. For example, Thymeleaf templates can just be edited in-place. By default changing resources in /META-INF/maven
, /META-INF/resources
,/resources
,/static
,/public
or /templates
will not trigger a restart but will trigger a live reload. If you want to customize these exclusions you can use the spring.devtools.restart.exclude
property. For example, to exclude only /static
and /public
you would set the following:
spring.devtools.restart.exclude=static/**,public/**
if you want to keep those defaults and add additional exclusions, use the |
20.2.2 Watching additional paths
You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath. To do so, use thespring.devtools.restart.additional-paths
property to configure additional paths to watch for changes. You can use the spring.devtools.restart.exclude
property described above to control whether changes beneath the additional paths will trigger a full restart or just a live reload.
20.2.3 Disabling restart
If you don’t want to use the restart feature you can disable it using the spring.devtools.restart.enabled
property. In most cases you can set this in yourapplication.properties
(this will still initialize the restart classloader but it won’t watch for file changes).
If you need to completely disable restart support, for example, because it doesn’t work with a specific library, you need to set a System
property before callingSpringApplication.run(…)
. For example:
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(MyApp.class, args);
}
20.2.4 Using a trigger file
如果使用不断编译已更改文件的IDE,则可能更喜欢仅在特定时间触发重新启动。为此,您可以使用“触发器文件”,这是一个特殊文件,当您想要实际触发重新启动检查时,必须对其进行修改。更改文件只会触发检查,只有在Devtools检测到必须执行某些操作时才会重新启动。触发器文件可以手动更新,也可以通过IDE插件更新。
要使用触发器文件,请使用该spring.devtools.restart.trigger-file
属性。
您可能希望将其设置 |
20.2.5自定义重启类加载器
如上面的Restart vs Reload部分所述,使用两个类加载器实现了重启功能。对于大多数应用程序,此方法很有效,但有时它可能会导致类加载问题。
默认情况下,IDE中的任何打开项目都将使用“restart”类加载器加载,任何常规.jar
文件都将使用“base”类加载器加载。如果您处理多模块项目,而不是将每个模块导入IDE,则可能需要自定义项目。为此,您可以创建一个META-INF/spring-devtools.properties
文件。
该spring-devtools.properties
文件可以包含restart.exclude.
和 restart.include.
前缀属性。该include
元素是应该被拉高到“重启”的类加载器的项目,以及exclude
要素是应该向下推入“基地”类加载器的项目。属性的值是将应用于类路径的正则表达式模式。
例如:
restart.exclude.companycommonlibs = / MyCorp的共用- [\\瓦特- ]。+ \罐子
restart.include.projectcommon = / MyCorp的-的Myproj - [\\瓦特- ]。+ \罐
所有属性键必须是唯一的。只要房产开始 |
|
20.2.6已知限制
对于使用标准反序列化的对象,重新启动功能不起作用ObjectInputStream
。如果你需要反序列化的数据,你可能需要使用Spring的ConfigurableObjectInputStream
结合 Thread.currentThread().getContextClassLoader()
。
不幸的是,几个第三方库反序列化而不考虑上下文类加载器。如果您发现此类问题,则需要向原始作者请求修复。
20.3 LiveReload
该spring-boot-devtools
模块包括一个嵌入式LiveReload服务器,可用于在更改资源时触发浏览器刷新。LiveReload浏览器扩展程序可从livereload.com免费用于Chrome,Firefox和Safari 。
如果您不想在应用程序运行时启动LiveReload服务器,则可以将spring.devtools.livereload.enabled
属性设置为false
。
您一次只能运行一个LiveReload服务器。在启动应用程序之前,请确保没有其他LiveReload服务器正在运行。如果从IDE启动多个应用程序,则只有第一个应用程序具有LiveReload支持。 |
20.4全局设置
您可以通过添加一个文件名为配置全局devtools设置 .spring-boot-devtools.properties
你的$HOME
文件夹(注意:文件名开头“”)。添加到此文件的任何属性都将应用于计算机上使用devtools的所有 Spring Boot应用程序。例如,要将restart配置为始终使用触发器文件,请添加以下内容:
〜/ .spring引导-devtools.properties。
spring.devtools.reload.trigger-file = .reloadtrigger
20.5远程应用程序
Spring Boot开发人员工具不仅限于本地开发。远程运行应用程序时,您还可以使用多个功能。远程支持是选择加入,要启用它,您需要确保它devtools
包含在重新打包的存档中:
<build>
<plugins>
<plugin>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-maven-plugin </ artifactId>
<configuration>
<excludeDevtools> false </ excludeDevtools>
</ configuration>
</ plugin>
</ plugins>
</ build>
然后你需要设置一个spring.devtools.remote.secret
属性,例如:
spring.devtools.remote.secret = mysecret
|
远程devtools支持分为两部分; 有一个接受连接的服务器端端点,以及在IDE中运行的客户端应用程序。spring.devtools.remote.secret
设置属性后,将自动启用服务器组件。必须手动启动客户端组件。
20.5.1运行远程客户端应用程序
远程客户端应用程序旨在从IDE中运行。您需要org.springframework.boot.devtools.RemoteSpringApplication
使用与要连接的远程项目相同的类路径运行 。传递给应用程序的非选项参数应该是您要连接的远程URL。
例如,如果您使用的是Eclipse或STS,并且您有一个名为my-app
已部署到Cloud Foundry的项目,那么您将执行以下操作:
- 选择
Run Configurations…
从Run
菜单。 - 创建一个新的
Java Application
“启动配置”。 - 浏览
my-app
项目。 - 用
org.springframework.boot.devtools.RemoteSpringApplication
作主类。 - 添加
https://myapp.cfapps.io
到Program arguments
(或任何远程URL)。
正在运行的远程客户端将如下所示:
。____ _ __ _ _
/ \\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \
(()\ ___ |'_ |'_ ||'_ \ / _` | | _ \ ___ _ __ ___ | | _ ___ \ \ \ \
\\ / ___)| | _)| | | | | || (_ | [] :::::: [] / -_)'\ / _ \ _ / -_))))))
' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / /
=========|_|==============|___/===================================/_/_/_/
:: Spring Boot Remote :: 2.0.0.M3 2015-06-10 18:25:06.632 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication on pwmbp with PID 14938 (/Users/pwebb/projects/spring-boot/code/spring-boot-devtools/target/classes started by pwebb in /Users/pwebb/projects/spring-boot/code/spring-boot-samples/spring-boot-sample-devtools)
2015-06-10 18:25:06.671 INFO 14938 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a17b7b6: startup date [Wed Jun 10 18:25:06 PDT 2015]; root of context hierarchy
2015-06-10 18:25:07.043 WARN 14938 --- [ main] o.s.b.d.r.c.RemoteClientConfiguration : The connection to http://localhost:8080 is insecure. You should use a URL starting with 'https://'.
2015-06-10 18:25:07.074 INFO 14938 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2015-06-10 18:25:07.130 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105)
Because the remote client is using the same classpath as the real application it can directly read application properties. This is how the |
It’s always advisable to use |
If you need to use a proxy to access the remote application, configure the |
20.5.2 Remote update
The remote client will monitor your application classpath for changes in the same way as the local restart. Any updated resource will be pushed to the remote application and (if required) trigger a restart. This can be quite helpful if you are iterating on a feature that uses a cloud service that you don’t have locally. Generally remote updates and restarts are much quicker than a full rebuild and deploy cycle.
Files are only monitored when the remote client is running. If you change a file before starting the remote client, it won’t be pushed to the remote server. |
21. Packaging your application for production
Executable jars can be used for production deployment. As they are self-contained, they are also ideally suited for cloud-based deployment.
For additional “production ready” features, such as health, auditing and metric REST or JMX end-points; consider adding spring-boot-actuator
. See Part V, “Spring Boot Actuator: Production-ready features” for details.
22. What to read next
您现在应该很好地理解如何使用Spring Boot以及您应该遵循的一些最佳实践。您现在可以继续深入了解特定的 Spring Boot功能,或者您可以跳过并阅读Spring Boot 的“ 生产就绪 ”方面。
第四部分。Spring Boot功能
本节深入介绍Spring Boot的详细信息。在这里,您可以了解要使用和自定义的主要功能。如果您还没有,可能需要阅读第II部分“入门”和 第III部分“使用Spring Boot”部分,以便您掌握基础知识。
23. SpringApplication
本SpringApplication
类提供了一个方便的方式来引导,将来自启动Spring应用程序main()
的方法。在许多情况下,您可以委托静态SpringApplication.run
方法:
public static void main(String [] args){
SpringApplication.run(MySpringConfiguration 类,参数);
}
当您的应用程序启动时,您应该看到类似于以下内容:
。____ _ __ _ _
/ \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
(()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \
\\ / ___)| | _)| | | | | || (_ | |))))
'| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / /
========= | _ | ============== | ___ / = / _ / _ / _ /
:: Spring Boot :: v2.0.0.M3 2013-07-31 00:08:16.117 INFO 56603 --- [main] osbsapp.SampleApplication:在我的计算机上使用PID 56603启动SampleApplication v0.1.0(/ apps / myapp.jar由pwebb启动)
2013-07-31 00:08:16.166 INFO 56603 --- [main] ationConfigServletWebServerApplicationContext:刷新org.springframework.boot.web.ser vlet.context.AnnotationConfigServletWebServerApplicationContext @ 6e5a8246:启动日期[Wed Jul 31 00:08:16 PDT 2013]; 上下文层次结构的根
2014-03-04 13:09:54.912 INFO 41370 --- [main] .t.TomcatServletWebServerFactory:服务器初始化端口:8080
2014-03-04 13:09:56.501 INFO 41370 --- [main] osbsapp.SampleApplication:在2.992秒内启动SampleApplication(JVM运行3.658)
默认情况下,INFO
将显示日志消息,包括一些相关的启动详细信息,例如启动应用程序的用户。
23.1启动失败
如果您的应用程序无法启动,则已注册FailureAnalyzers
有机会提供专用错误消息和具体操作来解决问题。例如,如果您在端口上启动Web应用程序8080
并且该端口已在使用中,您应该看到类似于以下内容的内容:
***************************
应用程序未能启动
*************************** 描述: 嵌入式servlet容器无法启动。8080端口已经投入使用。 行动: 识别并停止正在侦听端口8080的进程或将此应用程序配置为侦听另一个端口。
Spring Boot提供了许多 |
如果没有故障分析器能够处理异常,您仍然可以显示完整的自动配置报告,以更好地了解出现了什么问题。要做到这一点,你需要 使debug
财产或 启用DEBUG
日志记录的 org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer
。
例如,如果您使用的是运行应用程序,则java -jar
可以debug
按如下方式启用该 属性:
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
23.2自定义横幅
The banner that is printed on start up can be changed by adding a banner.txt
file to your classpath, or by setting banner.location
to the location of such a file. If the file has an unusual encoding you can set banner.charset
(default is UTF-8
). In addition to a text file, you can also add a banner.gif
, banner.jpg
or banner.png
image file to your classpath, or set a banner.image.location
property. Images will be converted into an ASCII art representation and printed above any text banner.
Inside your banner.txt
file you can use any of the following placeholders:
Table 23.1. Banner variables
Variable | Description |
---|---|
|
The version number of your application as declared in |
|
为 |
|
您正在使用的Spring Boot版本。例如 |
|
您正在使用的Spring Boot版本用于显示(用括号括起来并带有前缀 |
|
|
|
您申请的标题 |
|
您还可以使用该spring.main.banner-mode
属性来确定是否必须使用配置的记录器()打印System.out
(console
),log
或者根本不打印横幅(off
)。
打印的横幅将在名称下注册为单个bean springBootBanner
。
YAML映射 spring: |
23.3自定义SpringApplication
如果SpringApplication
默认值不符合您的需要,您可以创建一个本地实例并进行自定义。例如,要关闭您要写的横幅:
public static void main(String [] args){
SpringApplication应用= 新 SpringApplication(MySpringConfiguration。类);
app.setBannerMode(Banner.Mode.OFF);
app.run(参数);
}
传递给的构造函数参数 |
也可以配置SpringApplication
使用application.properties
文件。有关详细信息,请参见第24章,外部化配置。
有关配置选项的完整列表,请参阅 SpringApplication
Javadoc。
23.4 Fluent构建器API
如果您需要构建ApplicationContext
层次结构(具有父/子关系的多个上下文),或者您只是喜欢使用'流畅'构建器API,则可以使用SpringApplicationBuilder
。
将SpringApplicationBuilder
让您链在一起的多个方法调用,包括parent
和child
,让您创建一个层次结构的方法。
例如:
新的 SpringApplicationBuilder()
.sources(家长。类)
.child(申请。班)
.bannerMode(Banner.Mode.OFF)
.RUN(参数);
创建 |
23.5应用程序事件和监听器
除了通常的Spring Framework事件之外,例如 ContextRefreshedEvent
,SpringApplication
发送一些额外的应用程序事件。
某些事件实际上 如果您希望自动注册这些侦听器而不管应用程序的创建方式如何,您可以将 org.springframework.context.ApplicationListener = com.example.project.MyListener |
应用程序运行时,应按以下顺序发送应用程序事件:
- 一个
ApplicationStartingEvent
是在一个运行开始发送,但除了听众和初始化的登记任何处理之前。 - 一个
ApplicationEnvironmentPreparedEvent
当被发送Environment
到在上下文已知被使用,但是在创建上下文之前。 - 一个
ApplicationPreparedEvent
被发送刷新开始之前,但经过bean定义已经被加载。 -
ApplicationReadyEvent
在刷新之后发送一个并且已经处理了任何相关的回调以指示应用程序已准备好服务请求。 - 一个
ApplicationFailedEvent
如果在启动时异常发送。
您通常不需要使用应用程序事件,但知道它们存在可能很方便。在内部,Spring Boot使用事件来处理各种任务。 |
23.6 Web环境
A SpringApplication
将尝试ApplicationContext
代表您创建正确的类型。默认情况下,将使用AnnotationConfigApplicationContext
或AnnotationConfigServletWebServerApplicationContext
将使用,具体取决于您是否正在开发Web应用程序。
用于确定“web环境”的算法相当简单(基于几个类的存在)。setWebEnvironment(boolean webEnvironment)
如果需要覆盖默认值,则可以使用。
It is also possible to take complete control of the ApplicationContext
type that will be used by calling setApplicationContextClass(…)
.
It is often desirable to call |
23.7 Accessing application arguments
If you need to access the application arguments that were passed to SpringApplication.run(…)
you can inject aorg.springframework.boot.ApplicationArguments
bean. The ApplicationArguments
interface provides access to both the raw String[]
arguments as well as parsed option
and non-option
arguments:
import org.springframework.boot.*
import org.springframework.beans.factory.annotation.*
import org.springframework.stereotype.* @Component
public class MyBean { @Autowired
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
// if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
} }
Spring Boot will also register a |
23.8 Using the ApplicationRunner or CommandLineRunner
If you need to run some specific code once the SpringApplication
has started, you can implement the ApplicationRunner
or CommandLineRunner
interfaces. Both interfaces work in the same way and offer a single run
method which will be called just before SpringApplication.run(…)
completes.
The CommandLineRunner
interfaces provides access to application arguments as a simple string array, whereas the ApplicationRunner
uses the ApplicationArguments
interface discussed above.
import org.springframework.boot.*
import org.springframework.stereotype.* @Component
public class MyBean implements CommandLineRunner { public void run(String... args) {
// Do something...
} }
You can additionally implement the org.springframework.core.Ordered
interface or use the org.springframework.core.annotation.Order
annotation if several CommandLineRunner
or ApplicationRunner
beans are defined that must be called in a specific order.
23.9 Application exit
Each SpringApplication
will register a shutdown hook with the JVM to ensure that the ApplicationContext
is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean
interface, or the @PreDestroy
annotation) can be used.
In addition, beans may implement the org.springframework.boot.ExitCodeGenerator
interface if they wish to return a specific exit code when SpringApplication.exit()
is called. This exit code can then be passed to System.exit()
to return it as a status code.
@SpringBootApplication
public class ExitCodeApplication { @Bean
public ExitCodeGenerator exitCodeGenerator() {
return () -> 42;
} public static void main(String[] args) {
System.exit(SpringApplication
.exit(SpringApplication.run(ExitCodeApplication 类,参数)));
} }
此外,ExitCodeGenerator
可以通过例外来实现接口。遇到这种异常时,Spring Boot将返回实现getExitCode()
方法提供的退出代码。
23.10管理员功能
可以通过指定spring.application.admin.enabled
属性为应用程序启用与管理相关的功能 。这暴露 SpringApplicationAdminMXBean
了平台MBeanServer
。您可以使用此功能远程管理Spring Boot应用程序。这对任何服务包装器实现也很有用。
如果您想知道应用程序正在运行的HTTP端口,请使用密钥获取属性 |
启用此功能时要小心,因为MBean公开了一种关闭应用程序的方法。 |
24.外部化配置
Spring Boot允许您外部化配置,以便在不同环境中使用相同的应用程序代码。您可以使用属性文件,YAML文件,环境变量和命令行参数来外部化配置。可以使用@Value
注释将属性值直接注入到bean中,通过Spring的Environment
抽象访问或 通过绑定到结构化对象@ConfigurationProperties
。
Spring Boot使用一种非常特殊的PropertySource
顺序,旨在允许合理地覆盖值。按以下顺序考虑属性:
-
Devtools 主目录上的全局设置属性(
~/.spring-boot-devtools.properties
当devtools处于活动状态时)。 -
@TestPropertySource
你的测试注释。 -
@SpringBootTest#properties
测试中的注释属性。 - 命令行参数。
- 属性
SPRING_APPLICATION_JSON
(嵌入在环境变量或系统属性中的内联JSON) -
ServletConfig
init参数。 -
ServletContext
init参数。 - JNDI属性来自
java:comp/env
。 - Java系统属性(
System.getProperties()
)。 - OS环境变量。
- 一个
RandomValuePropertySource
只有属性的random.*
。 - 打包jar之外的特定于配置文件的应用程序属性(
application-{profile}.properties
以及YAML变体) - 打包在jar中的特定于配置文件的应用程序属性(
application-{profile}.properties
和YAML变体) - 打包jar之外的应用程序属性(
application.properties
以及YAML变体)。 - 打包在jar中的应用程序属性(
application.properties
和YAML变体)。 -
@PropertySource
你的@Configuration
课上的注释。 - 默认属性(使用指定
SpringApplication.setDefaultProperties
)。
为了提供一个具体的例子,假设你开发了一个@Component
使用 name
属性的东西:
import org.springframework.stereotype。*
import org.springframework.beans.factory.annotation。* @Component
公共 类 MyBean { @Value(“$ {name}”)
私有字符串名称; // ... }
在您的应用程序类路径(例如,在您的jar中),您可以拥有一个 application.properties
为其提供合理的默认属性值name
。在新环境中运行时,application.properties
可以在jar外部提供覆盖name
; 对于一次性测试,您可以使用特定的命令行开关启动(例如java -jar app.jar --name="Spring"
)。
该 $ SPRING_APPLICATION_JSON ='{“foo”:{“bar”:“spam”}}'java -jar myapp.jar 在这个例子中,你将 $ java -Dspring.application.json ='{“foo”:“bar”}'-jar myapp.jar 或命令行参数: $ java -jar myapp.jar --spring.application.json ='{“foo”:“bar”}' 或者作为JNDI变量 |
24.1配置随机值
这RandomValuePropertySource
对于注入随机值(例如,进入秘密或测试用例)非常有用。它可以产生整数,长整数,uuids或字符串,例如
my.secret = $ {random.value}
my.number = $ {random.int}
my.bignumber = $ {random.long}
my.uuid = $ {random.uuid}
my.number.less.than.ten = $ {random.int(10)}
my.number.in.range = $ {random.int [1024,65536]}
该random.int*
语法是OPEN value (,max) CLOSE
其中的OPEN,CLOSE
任何字符和value,max
是整数。如果max
提供则value
是最小值并且max
是最大值(不包括)。
24.2访问命令行属性
默认情况下,SpringApplication
将任何命令行选项参数(以' - '开头,例如--server.port=9000
)转换为a property
并将其添加到Spring Environment
。如上所述,命令行属性始终优先于其他属性源。
如果您不希望将命令行属性添加到Environment
您可以使用它们禁用它们SpringApplication.setAddCommandLineProperties(false)
。
24.3应用程序属性文件
SpringApplication
将从application.properties
以下位置的文件加载属性并将它们添加到Spring Environment
:
- 一个
/config
当前目录下的子目录。 - 当前目录
- 一个classpath
/config
包 - 类路径根
列表按优先级排序(在列表中较高位置定义的属性将覆盖在较低位置中定义的属性)。
您还可以使用YAML('。mil')文件替代'.properties'。 |
如果您不喜欢application.properties
配置文件名,可以通过指定spring.config.name
环境属性切换到另一个。您还可以使用spring.config.location
environment属性(以逗号分隔的目录位置列表或文件路径)来引用显式位置。
$ java -jar myproject.jar --spring.config.name = myproject
要么
$ java -jar myproject.jar --spring.config.location = classpath:/default.properties,classpath:/override.properties
|
如果spring.config.location
包含目录(而不是文件),则它们应该以/
(并且将附加spring.config.name
在加载之前生成的名称,包括特定于配置文件的文件名)附加。指定的文件 spring.config.location
按原样使用,不支持特定于配置文件的变体,并将被任何特定于配置文件的属性覆盖。
以相反的顺序搜索配置位置。默认情况下,配置的位置是 classpath:/,classpath:/config/,file:./,file:./config/
。生成的搜索顺序为:
file:./config/
file:./
classpath:/config/
classpath:/
配置自定义配置位置时,除默认位置外,还会使用它们。在默认位置之前搜索自定义位置。例如,如果classpath:/custom-config/,file:./custom-config/
配置了自定义位置,则搜索顺序将变为:
file:./custom-config/
classpath:custom-config/
file:./config/
file:./
classpath:/config/
classpath:/
This search ordering allows you to specify default values in one configuration file and then selectively override those values in another. You can provide default values for you application in application.properties
(or whatever other basename you choose with spring.config.name
) in one of the default locations. These default values can then be overriden at runtime with a different file located in one of the custom locations.
If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (e.g. |
If you are running in a container then JNDI properties (in |
24.4 Profile-specific properties
In addition to application.properties
files, profile-specific properties can also be defined using the naming convention application-{profile}.properties
. TheEnvironment
has a set of default profiles (by default [default]
) which are used if no active profiles are set (i.e. if no profiles are explicitly activated then properties from application-default.properties
are loaded).
Profile-specific properties are loaded from the same locations as standard application.properties
, with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.
If several profiles are specified, a last wins strategy applies. For example, profiles specified by the spring.profiles.active
property are added after those configured via the SpringApplication
API and therefore take precedence.
如果您已指定任何文件 |
24.5占位符属性
当使用它们时,application.properties
将通过现有值过滤这些值,Environment
以便您可以返回先前定义的值(例如,从系统属性)。
app.name = MyApp
app.description = $ {app.name}是一个Spring Boot应用程序
您还可以使用此技术创建现有Spring Boot属性的“短”变体。有关详细信息,请参见第73.4节“使用'短'命令行参数”操作方法。 |
24.6使用YAML代替属性
YAML是JSON的超集,因此是用于指定分层配置数据的非常方便的格式。该SpringApplication
课程将自动支持YAML作为一种替代性,只要你有 SnakeYAML在classpath库。
如果您使用'Starters',将自动提供SnakeYAML |
24.6.1加载YAML
Spring Framework提供了两个方便的类,可用于加载YAML文档。在YamlPropertiesFactoryBean
将加载YAML作为Properties
和 YamlMapFactoryBean
将加载YAML作为Map
。
例如,以下YAML文档:
环境:
dev:
url:http://dev.bar.com
名称:Developer Setup
prod:
url:http://foo.bar.com
name:My Cool App
将转化为这些属性:
environments.dev.url = http://dev.bar.com
environments.dev.name =开发人员设置
environment.prod.url = http://foo.bar.com
environments.prod.name =我的酷应用
YAML列表表示为具有[index]
解除引用的属性键,例如此YAML:
我的:
服务器:
- dev.bar.com
- foo.bar.com
将转化为这些属性:
my.servers [0] = dev.bar.com
my.servers [1] = foo.bar.com
要使用Spring DataBinder
实用程序绑定到类似的属性(这是什么 @ConfigurationProperties
),您需要在类型java.util.List
(或Set
)的目标bean中具有属性, 并且您需要提供一个setter,或者使用可变值初始化它,例如this将绑定到上面的属性
@ConfigurationProperties(prefix =“my”)
public class Config { private List <String> servers = new ArrayList <String>(); public List <String> getServers(){
return this .servers;
}
}
配置列表时需要格外小心,因为覆盖将无法正常工作。在上面的示例中,当 我的: |
24.6.2在Spring环境中公开YAML作为属性
本YamlPropertySourceLoader
类可用于暴露YAML作为PropertySource
在春节Environment
。这允许您使用熟悉的@Value
注释和占位符语法来访问YAML属性。
24.6.3多轮廓的YAML文档
您可以使用spring.profiles
键指定文档何时适用,从而在单个文件中指定多个特定于配置文件的YAML文档。例如:
服务器:
地址:192.168。1.100
---
spring:
profiles:开发
服务器:
地址:127.0。0.1
---
spring:
profiles:生产
服务器:
地址:192.168。1.120
在上面的示例中,如果 配置文件处于活动状态,则server.address
属性为。如果未 启用和配置文件,则属性的值将为。127.0.0.1
development
development
production
192.168.1.100
如果在应用程序上下文启动时没有显式活动,则激活默认配置文件。因此,在这个YAML我们设定的值security.user.password
是 只可在“默认”的个人资料:
server:
port:8000
---
spring:
profiles:默认
安全:
user:
密码:弱
whereas in this example, the password is always set because it isn’t attached to any profile, and it would have to be explicitly reset in all other profiles as necessary:
server:
port: 8000
security:
user:
password: weak
Spring profiles designated using the "spring.profiles" element may optionally be negated using the !
character. If both negated and non-negated profiles are specified for a single document, at least one non-negated profile must match and no negated profiles may match.
24.6.4 YAML shortcomings
YAML files can’t be loaded via the @PropertySource
annotation. So in the case that you need to load values that way, you need to use a properties file.
24.6.5 Merging YAML lists
As we have seen above, any YAML content is ultimately transformed to properties. That process may be counter intuitive when overriding “list” properties via a profile.
For example, assume a MyPojo
object with name
and description
attributes that are null
by default. Let’s expose a list of MyPojo
from FooProperties
:
@ConfigurationProperties("foo")
public class FooProperties { private final List<MyPojo> list = new ArrayList<>(); public List<MyPojo> getList() {
return this.list;
} }
Consider the following configuration:
foo:
list:
- name:my name
description:my description
---
spring:
profiles:dev
foo:
list:
- name:my another name
如果dev
配置文件未激活,FooProperties.list
将包含一个MyPojo
如上定义的条目。dev
但是,如果启用了配置文件,list
则仍将 只包含一个条目(名称为“我的另一个名称”和描述null
)。此配置不会MyPojo
向列表添加第二个实例,也不会合并项目。
在多个配置文件中指定集合时,将使用具有最高优先级的集合(并且仅使用该集合):
foo:
list:
- name:my name
description:my description
- name:another name
description:another description
---
spring:
profiles:dev
foo:
list:
- name:my another name
在上面的示例中,考虑到dev
配置文件处于活动状态,FooProperties.list
将包含一个 MyPojo
条目(名称为“我的另一个名称”和描述null
)。
24.7类型安全配置属性
使用@Value("${property}")
注释注入配置属性有时会很麻烦,尤其是在使用多个属性或数据本质上是分层的情况下。Spring Boot提供了一种使用属性的替代方法,允许强类型bean管理和验证应用程序的配置。
包 com.example; import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(“foo”)
公共 类 FooProperties { private boolean enabled; private InetAddress remoteAddress; private final Security security = new Security(); public boolean isEnabled(){...} public void setEnabled(boolean enabled){...} public InetAddress getRemoteAddress(){...} public void setRemoteAddress(InetAddress remoteAddress){...} 公共安全 getSecurity(){...} public static class Security { 私有 String用户名; 私有字符串密码; private List <String> roles = new ArrayList <>(Collections.singleton(“USER”)); public String getUsername(){...} public void setUsername(String username){...} public String getPassword(){...} public void setPassword(String password){...} public List <String> getRoles(){...} public void setRoles(List <String> roles){...} }
}
上面的POJO定义了以下属性:
-
foo.enabled
,false
默认情况下 -
foo.remote-address
,具有可以强制的类型String
-
foo.security.username
,带有嵌套的“安全性”,其名称由属性名称决定。特别是那里根本没有使用返回类型SecurityProperties
foo.security.password
-
foo.security.roles
,收集String
getter和setter通常是必需的,因为绑定是通过标准的Java Beans属性描述符,就像在Spring MVC中一样。有些情况下可能会省略setter:
Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok doesn’t generate any particular constructor for such type as it will be used automatically by the container to instantiate the object. |
See also the differences between |
You also need to list the properties classes to register in the @EnableConfigurationProperties
annotation:
@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class MyConfiguration {
}
When The bean name in the example above will be |
Even if the configuration above will create a regular bean for FooProperties
, we recommend that @ConfigurationProperties
only deal with the environment and in particular does not inject other beans from the context. Having said that, The @EnableConfigurationProperties
annotation is also automatically applied to your project so that any existing bean annotated with @ConfigurationProperties
will be configured from the Environment
. You could shortcut MyConfiguration
above by making sure FooProperties
is a already a bean:
@Component
@ConfigurationProperties(prefix="foo")
public class FooProperties { // ... see above }
This style of configuration works particularly well with the SpringApplication
external YAML configuration:
# application.yml foo:
remote-address: 192.168.1.1
security:
username: foo
roles:
- USER
- ADMIN # additional configuration as required
To work with @ConfigurationProperties
beans you can just inject them in the same way as any other bean.
@Service
public class MyService { private final FooProperties properties; @Autowired
public MyService(FooProperties properties) {
this.properties = properties;
} //... @PostConstruct
public void openConnection() {
Server server = new Server(this.properties.getRemoteAddress());
// ...
} }
Using |
24.7.1 Third-party configuration
As well as using @ConfigurationProperties
to annotate a class, you can also use it on public @Bean
methods. This can be particularly useful when you want to bind properties to third-party components that are outside of your control.
To configure a bean from the Environment
properties, add @ConfigurationProperties
to its bean registration:
@ConfigurationProperties(prefix = "bar")
@Bean
public BarComponent barComponent() {
...
}
Any property defined with the bar
prefix will be mapped onto that BarComponent
bean in a similar manner as the FooProperties
example above.
24.7.2 Relaxed binding
Spring Boot uses some relaxed rules for binding Environment
properties to @ConfigurationProperties
beans, so there doesn’t need to be an exact match between the Environment
property name and the bean property name. Common examples where this is useful include dashed separated (e.g. context-path
binds to contextPath
), and capitalized (e.g. PORT
binds to port
) environment properties.
For example, given the following @ConfigurationProperties
class:
@ConfigurationProperties(prefix =“person”)
public class OwnerProperties { private String firstName; public String getFirstName(){
return this .firstName;
} public void setFirstName(String firstName){
this .firstName = firstName;
} }
可以使用以下属性名称:
表24.1。轻松绑定
属性 | 注意 |
---|---|
|
标准的驼峰案例语法。 |
|
烤肉串,建议用于 |
|
下划线表示法,用于 |
|
大写格式。建议在使用系统环境变量时使用。 |
|
表24.2。每个属性源放宽绑定规则
物业来源 | 简单 | 名单 |
---|---|---|
属性文件 |
骆驼箱,烤肉串或下划线表示法 |
标准列表语法使用 |
YAML文件 |
骆驼箱,烤肉串或下划线表示法 |
标准YAML列表语法或逗号分隔值 |
环境变量 |
大写格式,下划线作为分隔符。 |
下划线包围的数字值。例如: |
系统属性 |
骆驼箱,烤肉串或下划线表示法 |
标准列表语法使用 |
我们建议,如果可能,属性以小写kebab格式存储。即 |
24.7.3属性转换
Spring will attempt to coerce the external application properties to the right type when it binds to the @ConfigurationProperties
beans. If you need custom type conversion you can provide a ConversionService
bean (with bean id conversionService
) or custom property editors (via a CustomEditorConfigurer
bean) or custom Converters
(with bean definitions annotated as @ConfigurationPropertiesBinding
).
As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your |
24.7.4 @ConfigurationProperties Validation
Spring Boot will attempt to validate @ConfigurationProperties
classes whenever they are annotated with Spring’s @Validated
annotation. You can use JSR-303 javax.validation
constraint annotations directly on your configuration class. Simply ensure that a compliant JSR-303 implementation is on your classpath, then add constraint annotations to your fields:
@ConfigurationProperties(prefix="foo")
@Validated
public class FooProperties { @NotNull
private InetAddress remoteAddress; // ... getters and setters }
In order to validate values of nested properties, you must annotate the associated field as @Valid
to trigger its validation. For example, building upon the aboveFooProperties
example:
@ConfigurationProperties(prefix="connection")
@Validated
public class FooProperties { @NotNull
private InetAddress remoteAddress; @Valid
private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty
public String username; // ... getters and setters } }
您还可以Validator
通过创建名为的bean定义 来添加自定义Spring configurationPropertiesValidator
。@Bean
应声明该方法static
。配置属性验证器是在应用程序生命周期的早期创建的,并将该@Bean
方法声明为static,允许创建bean而无需实例化@Configuration
该类。这避免了早期实例化可能导致的任何问题。有一个 属性验证示例,您可以看到如何设置。
该 |
24.7.5 @ConfigurationProperties与@Value
@Value
是一个核心容器功能,它不提供与类型安全的配置属性相同的功能。下表汇总了支持的功能@ConfigurationProperties
和@Value
:
如果为自己的组件定义一组配置键,我们建议您将它们分组到带注释的POJO中@ConfigurationProperties
。另请注意,由于@Value
不支持宽松绑定,因此如果需要使用环境变量提供值,则不是一个很好的选择。
最后,虽然您可以编写SpEL
表达式@Value
,但不会从Application属性文件处理此类表达式。
25.简介
Spring Profiles提供了一种隔离应用程序配置部分并使其仅在特定环境中可用的方法。任何@Component
或@Configuration
可以标记@Profile
以限制何时加载:
@Configuration
@Profile(“production”)
公共 类 ProductionConfiguration { // ... }
在常规Spring方式中,您可以使用spring.profiles.active
Environment
属性指定哪些配置文件处于活动状态。您可以通过任何常用方式指定属性,例如,您可以将其包含在application.properties
:
spring.profiles.active = dev,hsqldb
或使用开关在命令行上指定--spring.profiles.active=dev,hsqldb
。
25.1添加活动配置文件
该spring.profiles.active
物业遵循与其他物业相同的订购规则,最高PropertySource
将获胜。这意味着您可以指定活动配置文件,application.properties
然后使用命令行开关替换它们。
有时,将特定于配置文件的属性添加到活动配置文件而不是替换它们是有用的。该spring.profiles.include
属性可用于无条件添加活动配置文件。该SpringApplication
入口点还设置额外的配置文件(即对那些被激活顶部的Java API的 spring.profiles.active
属性):看setAdditionalProfiles()
方法。
例如,当与以下属性的应用程序正在使用开关运行 --spring.profiles.active=prod
的proddb
和prodmq
轮廓也将被激活:
---
my.property:fromyamlfile
---
spring.profiles:PROD
spring.profiles.include:
- proddb
- prodmq
请记住, |
25.2以编程方式设置配置文件
您可以SpringApplication.setAdditionalProfiles(…)
在应用程序运行之前通过调用以编程方式设置活动配置文 也可以使用Spring的ConfigurableEnvironment
界面激活配置文件。
26.记录
Spring Boot使用Commons Logging进行所有内部日志记录,但保留底层日志实现。为Java Util Logging, Log4J2和Logback提供了默认配置 。在每种情况下,记录器都预先配置为使用控制台输出,并且还提供可选的文件输出。
默认情况下,如果使用“启动器”,则将使用Logback进行日志记录。还包括适当的Logback路由,以确保使用Java Util Logging,Commons Logging,Log4J或SLF4J的依赖库都能正常工作。
Java有很多日志框架可供使用。如果以上列表看起来令人困惑,请不要担心。通常,您不需要更改日志记录依赖项,Spring Boot默认值也可以正常工作。 |
26。1日志格式
Spring Boot的默认日志输出如下所示:
2014-03-05 10:57:51.112 INFO 45469 --- [main] org.apache.catalina.core.StandardEngine:启动Servlet引擎:Apache Tomcat / 7.0.52
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] oaccC [Tomcat]。[localhost]。[/]:初始化Spring嵌入式WebApplicationContext
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] osweb.context.ContextLoader:Root WebApplicationContext:初始化在1358 ms完成
2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] osbceServletRegistrationBean:将servlet:'dispatcherServlet'映射到[/]
2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean:映射过滤器:'hiddenHttpMethodFilter'到:[/ *]
输出以下项目:
- 日期和时间 - 毫秒精度,易于排序。
- 日志级别- ,
ERROR
,,WARN
或。INFO
DEBUG
TRACE
- 进程ID。
- 一个
---
分离器来区分实际日志消息的开始。 - 线程名称 - 括在方括号中(可能会截断控制台输出)。
- Logger name — This is usually the source class name (often abbreviated).
- The log message.
Logback does not have a |
26.2 Console output
The default log configuration will echo messages to the console as they are written. By default ERROR
, WARN
and INFO
level messages are logged. You can also enable a “debug” mode by starting your application with a --debug
flag.
$ java -jar myapp.jar --debug
you can also specify |
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG
level.
Alternatively, you can enable a “trace” mode by starting your application with a --trace
flag (or trace=true
in your application.properties
). This will enable trace logging for a selection of core loggers (embedded container, Hibernate schema generation and the whole Spring portfolio).
26.2.1 Color-coded output
If your terminal supports ANSI, color output will be used to aid readability. You can set spring.output.ansi.enabled
to a supported value to override the auto detection.
Color coding is configured using the %clr
conversion word. In its simplest form the converter will color the output according to the log level, for example:
%clr(%5p)
The mapping of log level to a color is as follows:
Level | Color |
---|---|
|
Red |
|
Red |
|
Yellow |
|
Green |
|
Green |
|
Green |
Alternatively, you can specify the color or style that should be used by providing it as an option to the conversion. For example, to make the text yellow:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
The following colors and styles are supported:
blue
cyan
faint
green
magenta
red
yellow
26.3 File output
By default, Spring Boot will only log to the console and will not write log files. If you want to write log files in addition to the console output you need to set alogging.file
or logging.path
property (for example in your application.properties
).
The following table shows how the logging.*
properties can be used together:
Table 26.1. Logging properties
logging.file |
logging.path |
Example | Description |
---|---|---|---|
(none) |
(none) |
Console only logging. |
|
Specific file |
(none) |
|
Writes to the specified log file. Names can be an exact location or relative to the current directory. |
(none) |
Specific directory |
|
写入 |
日志文件将在达到10 MB时旋转,并且与控制台输出一样ERROR
,WARN
并且INFO
默认情况下会记录级别消息。
日志记录系统在应用程序生命周期的早期初始化,因此在通过 |
日志记录属性独立于实际的日志记录基础结构。因此, |
26。4日志级别
所有受支持的日志记录系统都可以使用'logging.level。* = LEVEL'在Spring中设置记录器级别 Environment
(例如application.properties
),其中'LEVEL'是TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF之一。该root
记录器可以通过以下方式配置logging.level.root
。示例application.properties
:
logging.level.root = WARN
logging.level.org.springframework.web = DEBUG
logging.level.org.hibernate = ERROR
默认情况下,Spring Boot会重新映射Thymeleaf |
26.5自定义日志配置
可以通过在类路径中包含适当的库来激活各种日志记录系统,并通过在类路径的根目录中或Spring Environment
属性 指定的位置提供合适的配置文件来进一步自定义logging.config
。
您可以使用org.springframework.boot.logging.LoggingSystem
系统属性强制Spring Boot使用特定的日志记录系统 。该值应该是实现的完全限定类名LoggingSystem
。您还可以通过使用值来完全禁用Spring Boot的日志记录配置none
。
由于记录被初始化之前的 |
根据您的日志记录系统,将加载以下文件:
记录系统 | 定制 |
---|---|
的logback |
|
Log4j2 |
|
JDK(Java Util Logging) |
|
如果可能,我们建议您使用 |
Java Util Logging存在已知的类加载问题,从“可执行jar”运行时会导致问题。我们建议您尽可能避免使用它。 |
为了帮助定制,一些其他属性从Spring转移 Environment
到System属性:
春天的环境 | 系统属性 | 评论 |
---|---|---|
|
|
记录异常时使用的转换字。 |
|
|
如果已定义,则用于默认日志配置。 |
|
|
如果已定义,则用于默认日志配置。 |
|
|
要在控制台上使用的日志模式(stdout)。(仅支持默认的logback设置。) |
|
|
要在文件中使用的日志模式(如果启用了LOG_FILE)。(仅支持默认的logback设置。) |
|
|
用于呈现日志级别的格式(默认 |
|
|
当前进程ID(如果可能,则在未定义为OS环境变量时发现)。 |
支持的所有日志记录系统在解析其配置文件时都可以参考系统属性。有关spring-boot.jar
示例,请参阅默认配置。
如果要在日志记录属性中使用占位符,则应使用 Spring Boot的语法而不是底层框架的语法。值得注意的是,如果您使用的是Logback,则应将其 |
您可以通过仅覆盖 2015-09-30 12:30:04.031用户:juergen INFO 22174 --- [nio-8080-exec-0] demo.Controller |
26.6 Logback扩展
Spring Boot包含许多Logback扩展,可以帮助进行高级配置。您可以在logback-spring.xml
配置文件中使用这些扩展名。
您不能在标准 |
扩展不能与Logback的 配置扫描一起使用。如果您尝试这样做,更改配置文件将导致类似于以下记录之一的错误: |
ch.qos.logback.core.joran.spi.Interpreter@4中的错误:71 - [springProperty]没有适用的操作,当前的ElementPath是[[configuration] [springProperty]]ch.qos.logback.core.joran.spi.Interpreter@4中的
错误:71 - [springProfile]没有适用的操作,当前的ElementPath是[[configuration] [springProfile]]
26.6.1特定于配置文件的配置
该<springProfile>
标签允许您有选择地包括或排除基于主动春型材配置的部分。在<configuration>
元素内的任何位置都支持配置文件节。使用该name
属性指定哪个配置文件接受配置。可以使用逗号分隔列表指定多个配置文件。
<springProfile name = “staging” >
<! - “暂存”配置文件处于活动状态时启用的配置 - >
</ springProfile> <springProfile name = “dev,staging” >
<! - 在“dev”或“staging”配置文件处于活动状态时启用的配置 - >
</ springProfile> <springProfile name = “!production” >
<! - “生产”配置文件未激活时要启用的配置 - >
</ springProfile>
26.6.2环境属性
The <springProperty>
tag allows you to surface properties from the Spring Environment
for use within Logback. This can be useful if you want to access values from your application.properties
file in your logback configuration. The tag works in a similar way to Logback’s standard <property>
tag, but rather than specifying a direct value
you specify the source
of the property (from the Environment
). You can use the scope
attribute if you need to store the property somewhere other than in local
scope. If you need a fallback value in case the property is not set in the Environment
, you can use the defaultValue
attribute.
<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
<remoteHost>${fluentHost}</remoteHost>
...
</appender>
The |
27. Developing web applications
Spring Boot is well suited for web application development. You can easily create a self-contained HTTP server using embedded Tomcat, Jetty, Undertow, or Netty. Most web applications will use the spring-boot-starter-web
module to get up and running quickly. You can also choose to use to build reactive web applications by using the spring-boot-starter-webflux
module.
If you haven’t yet developed a Spring Boot web application you can follow the "Hello World!" example in the Getting started section.
27.1 The ‘Spring Web MVC framework’
Spring Web MVC框架(通常简称为“Spring MVC”)是一个丰富的“模型视图控制器”Web框架。Spring MVC允许您创建特殊@Controller
或@RestController
bean来处理传入的HTTP请求。控制器中的方法使用@RequestMapping
注释映射到HTTP 。
以下是@RestController
提供JSON数据的典型示例:
@RestController
@RequestMapping(value =“/ users”)
public class MyRestController { @RequestMapping(value =“/ {user}”,method = RequestMethod.GET)
public User getUser( @PathVariable Long user){
// ...
} @RequestMapping(value =“/ {user} / customers”,method = RequestMethod.GET)
List <Customer> getUserCustomers( @PathVariable Long user){
// ...
} @RequestMapping(value =“/ {user}”,method = RequestMethod.DELETE)
public User deleteUser( @PathVariable Long user){
// ...
} }
Spring MVC是核心Spring Framework的一部分,详细信息可在参考文档中找到。Spring.io/guides还提供了几个涵盖Spring MVC的指南。
27.1.1 Spring MVC自动配置
Spring Boot为Spring MVC提供自动配置,适用于大多数应用程序。
自动配置在Spring的默认值之上添加了以下功能:
- 包含
ContentNegotiatingViewResolver
和BeanNameViewResolver
豆类。 - 支持提供静态资源,包括对WebJars的支持(见下文)。
- 自动登记
Converter
,GenericConverter
,Formatter
豆类。 - 支持
HttpMessageConverters
(见下文)。 - 自动注册
MessageCodesResolver
(见下文)。 - 静态
index.html
支持。 - 自定义
Favicon
支持(见下文)。 - 自动使用
ConfigurableWebBindingInitializer
bean(见下文)。
如果你想保留Spring Boot MVC功能,并且你只想添加额外的MVC配置(拦截器,格式化程序,视图控制器等),你可以添加自己的@Configuration
类类型WebMvcConfigurer
,但没有 @EnableWebMvc
。如果您希望提供自定义实例RequestMappingHandlerMapping
,RequestMappingHandlerAdapter
或者ExceptionHandlerExceptionResolver
您可以声明WebMvcRegistrationsAdapter
提供此类组件的实例。
如果您想完全控制Spring MVC,可以添加自己的@Configuration
注释@EnableWebMvc
。
27.1.2 HttpMessageConverters
Spring MVC使用该HttpMessageConverter
接口来转换HTTP请求和响应。灵敏的默认值包含在开箱即用中,例如,对象可以自动转换为JSON(使用Jackson库)或XML(如果可用则使用Jackson XML扩展,否则使用JAXB)。字符串UTF-8
默认使用。
如果您需要添加或自定义转换器,可以使用Spring Boot的 HttpMessageConverters
类:
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation。*;
import org.springframework.http.converter。*; @Configuration
公共 类 MyConfiguration { @Bean
public HttpMessageConverters customConverters(){
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another);
} }
Any HttpMessageConverter
bean that is present in the context will be added to the list of converters. You can also override default converters that way.
27.1.3 Custom JSON Serializers and Deserializers
If you’re using Jackson to serialize and deserialize JSON data, you might want to write your own JsonSerializer
and JsonDeserializer
classes. Custom serializers are usually registered with Jackson via a Module, but Spring Boot provides an alternative @JsonComponent
annotation which makes it easier to directly register Spring Beans.
You can use @JsonComponent
directly on JsonSerializer
or JsonDeserializer
implementations. You can also use it on classes that contains serializers/deserializers as inner-classes. For example:
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*; @JsonComponent
public class Example { public static class Serializer extends JsonSerializer<SomeObject> {
// ...
} public static class Deserializer extends JsonDeserializer<SomeObject> {
// ...
} }
All @JsonComponent
beans in the ApplicationContext
will be automatically registered with Jackson, and since @JsonComponent
is meta-annotated with @Component
, the usual component-scanning rules apply.
Spring Boot also provides JsonObjectSerializer
and JsonObjectDeserializer
base classes which provide useful alternatives to the standard Jackson versions when serializing Objects. See the Javadoc for details.
27.1.4 MessageCodesResolver
Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: MessageCodesResolver
. Spring Boot will create one for you if you set the spring.mvc.message-codes-resolver.format
property PREFIX_ERROR_CODE
or POSTFIX_ERROR_CODE
(see the enumeration in DefaultMessageCodesResolver.Format
).
27.1.5 Static Content
By default Spring Boot will serve static content from a directory called /static
(or /public
or /resources
or /META-INF/resources
) in the classpath or from the root of the ServletContext
. It uses the ResourceHttpRequestHandler
from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurer
and overriding the addResourceHandlers
method.
In a stand-alone web application the default servlet from the container is also enabled, and acts as a fallback, serving content from the root of the ServletContext
if Spring decides not to handle it. Most of the time this will not happen (unless you modify the default MVC configuration) because Spring will always be able to handle requests through the DispatcherServlet
.
By default, resources are mapped on /**
but you can tune that via spring.mvc.static-path-pattern
. For instance, relocating all resources to /resources/**
can be achieved as follows:
spring.mvc.static-path-pattern=/resources/**
You can also customize the static resource locations using spring.resources.static-locations
(replacing the default values with a list of directory locations). If you do this the default welcome page detection will switch to your custom locations, so if there is an index.html
in any of your locations on startup, it will be the home page of the application.
In addition to the ‘standard’ static resource locations above, a special case is made for Webjars content. Any resources with a path in /webjars/**
will be served from jar files if they are packaged in the Webjars format.
Do not use the |
Spring Boot also supports advanced resource handling features provided by Spring MVC, allowing use cases such as cache busting static resources or using version agnostic URLs for Webjars.
To use version agnostic URLs for Webjars, simply add the webjars-locator
dependency. Then declare your Webjar, taking jQuery for example, as "/webjars/jquery/dist/jquery.min.js"
which results in "/webjars/jquery/x.y.z/dist/jquery.min.js"
where x.y.z
is the Webjar version.
If you are using JBoss, you’ll need to declare the |
To use cache busting, the following configuration will configure a cache busting solution for all static resources, effectively adding a content hash in URLs, such as<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>
:
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
Links to resources are rewritten at runtime in template, thanks to a |
When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option. That’s why other strategies are also supported and can be combined. A "fixed" strategy will add a static version string in the URL, without changing the file name:
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/lib/
spring.resources.chain.strategy.fixed.version=v12
With this configuration, JavaScript modules located under "/js/lib/"
will use a fixed versioning strategy "/v12/js/lib/mymodule.js"
while other resources will still use the content one <link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>
.
有关ResourceProperties
更多支持的选项,请参阅。
27.1.6自定义Favicon
Spring Boot favicon.ico
在配置的静态内容位置和类路径的根(按此顺序)中查找a 。如果存在此类文件,则会自动将其用作应用程序的favicon。
27.1.7 ConfigurableWebBindingInitializer
Spring MVC使用a WebBindingInitializer
来初始化WebDataBinder
特定请求。如果您自己创建ConfigurableWebBindingInitializer
@Bean
,Spring Boot将自动配置Spring MVC以使用它。
27.1.8模板引擎
除REST Web服务外,您还可以使用Spring MVC来提供动态HTML内容。Spring MVC支持各种模板技术,包括Thymeleaf,FreeMarker和JSP。许多其他模板引擎也提供自己的Spring MVC集成。
Spring Boot包括对以下模板引擎的自动配置支持:
如果可能,应该避免使用JSP,将它们与嵌入式servlet容器一起使用时有几个 已知的限制。 |
当您使用默认配置的其中一个模板引擎时,您的模板将自动从中获取src/main/resources/templates
。
IntelliJ IDEA根据您运行应用程序的方式对类路径进行不同的排序。通过主方法在IDE中运行应用程序将导致与使用Maven或Gradle或其打包的jar运行应用程序时的顺序不同。这可能导致Spring Boot无法在类路径中找到模板。如果您受此问题的影响,可以在IDE中重新排序类路径,以便首先放置模块的类和资源。或者,您可以配置模板前缀以搜索类路径上的每个模板目录: |
27.1.9错误处理
Spring Boot /error
默认提供映射,以合理的方式处理所有错误,并在servlet容器中注册为“全局”错误页面。对于机器客户端,它将生成一个JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。对于浏览器客户端,有一个“whitelabel”错误视图,它以HTML格式呈现相同的数据(要自定义它,只需添加一个View
解析为'错误'的数据)。要完全替换默认行为,您可以实现 ErrorController
并注册该类型的bean定义,或者只是添加类型的bean ErrorAttributes
以使用现有机制但替换内容。
在 |
您还可以定义一个@ControllerAdvice
自定义JSON文档以返回特定控制器和/或异常类型。
@ControllerAdvice(basePackageClasses = FooController.class)
公共 类 FooControllerAdvice扩展 ResponseEntityExceptionHandler { @ExceptionHandler(YourException.class)
@ResponseBody
ResponseEntity <?> handleControllerException(HttpServletRequest request,Throwable ex){
HttpStatus status = getStatus(request);
返回 新的 ResponseEntity <>(new CustomErrorType(status.value(),ex.getMessage()),status);
} private HttpStatus getStatus(HttpServletRequest request){
整数statusCode =(整数)request.getAttribute(“javax.servlet.error.status_code”);
if(statusCode == null){
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
} }
在上面的示例中,如果YourException
由在同一个包中定义的控制器抛出,则将使用POJO FooController
的json表示CustomerErrorType
而不是ErrorAttributes
表示。
自定义错误页面
如果要为给定的状态代码显示自定义HTML错误页面,请将文件添加到文件/error
夹。错误页面可以是静态HTML(即添加到任何静态资源文件夹下),也可以使用模板构建。文件名应该是确切的状态代码或系列掩码。
例如,要映射404
到静态HTML文件,您的文件夹结构将如下所示:
SRC /
+ - 主要/
+ - java /
| + <源代码>
+ - 资源/
+ - 公共/
+ - 错误/
| + - 404.html
+ - <其他公共资产>
要5xx
使用FreeMarker模板映射所有错误,您将拥有如下结构:
SRC /
+ - 主要/
+ - java /
| + <源代码>
+ - 资源/
+ - 模板/
+ - 错误/
| + - 5xx.ftl
+ - <其他模板>
对于更复杂的映射,您还可以添加实现该ErrorViewResolver
接口的bean 。
公共 类 MyErrorViewResolver 实现 ErrorViewResolver { @覆盖
公共的ModelAndView resolveErrorView(HttpServletRequest的请求,
HttpStatus状态,Map <String,Object> model){
//使用请求或状态可选择返回ModelAndView
返回 ...
} }
您还可以使用常规的Spring MVC功能,如 @ExceptionHandler
方法和 @ControllerAdvice
。然后,ErrorController
将会发现任何未处理的异常。
映射Spring MVC之外的错误页面
对于不使用Spring MVC的应用程序,可以使用该ErrorPageRegistrar
接口直接注册ErrorPages
。这种抽象直接与底层嵌入式servlet容器一起工作,即使你没有Spring MVC也能工作 DispatcherServlet
。
@Bean
public ErrorPageRegistrar errorPageRegistrar(){
return new MyErrorPageRegistrar();
} // ... 私有 静态 类 MyErrorPageRegistrar 实现 ErrorPageRegistrar { @Override
public void registerErrorPages(ErrorPageRegistry registry){
registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST,“/ 400”));
} }
注意如果你注册的ErrorPage
路径最终会被a处理 Filter
(例如,像一些非Spring网页框架一样常见,比如Jersey和Wicket),那么Filter
必须明确注册为ERROR
调度程序,例如
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
...
registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
return registration;
}
(the default FilterRegistrationBean
does not include the ERROR
dispatcher type).
Error Handling on WebSphere Application Server
When deployed to a servlet container, a Spring Boot uses its error page filter to forward a request with an error status to the appropriate error page. The request can only be forwarded to the correct error page if the response has not already been committed. By default, WebSphere Application Server 8.0 and later commits the response upon successful completion of a servlet’s service method. You should disable this behaviour by setting com.ibm.ws.webcontainer.invokeFlushAfterService
to false
27.1.10 Spring HATEOAS
如果您正在开发一个使用超媒体的RESTful API,Spring Boot为Spring HATEOAS提供了自动配置,适用于大多数应用程序。自动配置取代了使用@EnableHypermediaSupport
和注册多个bean 的需要,以便于构建基于超媒体的应用程序,包括 LinkDiscoverers
(用于客户端支持)和ObjectMapper
配置为正确地将响应编组到所需表示中。在ObjectMapper
将根据定制spring.jackson.*
的属性或者Jackson2ObjectMapperBuilder
如果存在豆。
您可以使用控制Spring HATEOAS的配置 @EnableHypermediaSupport
。请注意,这将禁用上述ObjectMapper
自定义。
27.1.11 CORS支持
跨源资源共享 (CORS)是大多数浏览器实现 的W3C规范,允许您以灵活的方式指定授权何种类型的跨域请求,而不是使用一些安全性较低且功能较弱的方法,如IFRAME或JSONP。
从版本4.2开始,Spring MVC 支持开箱即用的CORS。 在Spring Boot应用程序中使用带有 注释的控制器方法CORS配置@CrossOrigin
不需要任何特定配置。 可以通过使用自定义 方法注册bean 来定义全局CORS配置:WebMvcConfigurer
addCorsMappings(CorsRegistry)
@Configuration
公共 类 MyConfiguration { @Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer(){
@
Override public void addCorsMappings(CorsRegistry registry){
registry.addMapping(“/ api / **”);
}
};
}
}
27.2'Spring WebFlux框架'
Spring WebFlux是Spring Framework 5.0中引入的新的响应式Web框架。与Spring MVC不同,它不需要Servlet API,完全异步且无阻塞,并 通过Reactor项目实现Reactive Streams规范。
Spring WebFlux有两种版本 - 基于注释的版本与我们所知道的Spring MVC模型非常接近:
@RestController
@RequestMapping(“/ users”)
公共 类 MyRestController { @GetMapping(“/ {user}”)
public Mono <User> getUser( @PathVariable Long user){
// ...
} @GetMapping(“/ {user} / customers”)
Flux <Customer> getUserCustomers( @PathVariable Long user){
// ...
} @DeleteMapping(“/ {user}”)
public Mono <User> deleteUser( @PathVariable Long user){
// ...
} }
'WebFlux.fn'是功能变体,它将路由配置与请求的实际处理分开:
@Configuration
public class RoutingConfiguration { @Bean
public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) {
return route(GET("/{user}").and(accept(APPLICATION_JSON)), userHandler::getUser)
.andRoute(GET("/{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers)
.andRoute(DELETE("/{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser);
} } @Component
public class UserHandler { public Mono<ServerResponse> getUser(ServerRequest request) {
// ...
} public Mono<ServerResponse> getUserCustomers(ServerRequest request) {
// ...
} public Mono<ServerResponse> deleteUser(ServerRequest request) {
// ...
}
}
WebFlux is part of the Spring Framework and detailed information is available in the reference documentation.
To get started, add the spring-boot-starter-webflux
module to your application.
Adding both |
27.2.1 Spring WebFlux auto-configuration
Spring Boot provides auto-configuration for Spring WebFlux that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
- Configuring codecs for
HttpMessageReader
andHttpMessageWriter
instances (see below). - Support for serving static resources, including support for WebJars (see below).
If you want to keep Spring Boot WebFlux features, and you just want to add additional WebFlux configuration you can add your own @Configuration
class of type WebFluxConfigurer
, but without @EnableWebFlux
.
If you want to take complete control of Spring WebFlux, you can add your own @Configuration
annotated with @EnableWebFlux
.
27.2.2 HTTP codecs with HttpMessageReaders and HttpMessageWriters
Spring WebFlux uses the HttpMessageReader
and HttpMessageWriter
interface to convert HTTP requests and responses. They are configured with CodecConfigurer
with sensible defaults, by looking at the libraries available in your classpath.
Spring Boot will apply further customization using CodecCustomizer
instances. For example, spring.jackson.*
configuration keys will be applied to the Jackson codec.
如果需要添加或自定义编解码器,可以创建自定义CodecCustomizer
组件:
import org.springframework.boot.web.codec.CodecCustomizer; @Configuration
公共 类 MyConfiguration { @Bean
public CodecCustomizer myCodecCustomizer(){
return codecConfigurer - > {
// ...
}
} }
您还可以利用Boot的自定义JSON序列化程序和反序列化程序。
27.2.3静态内容
默认情况下,Spring Boot将从类路径中名为/static
( /public
或/resources
或/META-INF/resources
)的目录中提供静态内容。它使用ResourceWebHandler
Spring WebFlux,因此您可以通过添加自己WebFluxConfigurer
的addResourceHandlers
方法来修改该行为并覆盖该 方法。
默认情况下,会映射资源,/**
但您可以通过调整该 资源spring.mvc.static-path-pattern
。例如,重新定位所有资源/resources/**
可以实现如下:
spring.mvc.static-path-pattern = / resources / **
您还可以使用spring.resources.static-locations
(使用目录位置列表替换默认值)自定义静态资源位置 。如果您这样做,默认的欢迎页面检测将切换到您的自定义位置,因此如果index.html
您在启动时的任何位置,它将是应用程序的主页。
除了上面的“标准”静态资源位置之外,还为Webjars内容制作了一个特例。具有路径的所有资源/webjars/**
如果以Webjars格式打包,将从jar文件中提供。
Spring WebFlux应用程序并不严格依赖于Servlet API,因此不能将它们部署为war并且不使用该 |
27.2.4模板引擎
除REST Web服务外,您还可以使用Spring WebFlux来提供动态HTML内容。Spring WebFlux支持各种模板技术,包括Thymeleaf,FreeMarker和Mustache。
Spring Boot包括对以下模板引擎的自动配置支持:
当您使用默认配置的其中一个模板引擎时,您的模板将自动从中获取src/main/resources/templates
。
27.3 JAX-RS和泽西岛
If you prefer the JAX-RS programming model for REST endpoints you can use one of the available implementations instead of Spring MVC. Jersey 1.x and Apache CXF work quite well out of the box if you just register their Servlet
or Filter
as a @Bean
in your application context. Jersey 2.x has some native Spring support so we also provide auto-configuration support for it in Spring Boot together with a starter.
To get started with Jersey 2.x just include the spring-boot-starter-jersey
as a dependency and then you need one @Bean
of type ResourceConfig
in which you register all the endpoints:
@Component
public class JerseyConfig extends ResourceConfig { public JerseyConfig() {
register(Endpoint.class);
} }
Jersey’s support for scanning executable archives is rather limited. For example, it cannot scan for endpoints in a package found in |
You can also register an arbitrary number of beans implementing ResourceConfigCustomizer
for more advanced customizations.
All the registered endpoints should be @Components
with HTTP resource annotations (@GET
etc.), e.g.
@Component
@Path("/hello")
public class Endpoint { @GET
public String message() {
return "Hello";
} }
Since the Endpoint
is a Spring @Component
its lifecycle is managed by Spring and you can @Autowired
dependencies and inject external configuration with @Value
. The Jersey servlet will be registered and mapped to /*
by default. You can change the mapping by adding @ApplicationPath
to your ResourceConfig
.
By default Jersey will be set up as a Servlet in a @Bean
of type ServletRegistrationBean
named jerseyServletRegistration
. By default, the servlet will be initialized lazily but you can customize it with spring.jersey.servlet.load-on-startup
.You can disable or override that bean by creating one of your own with the same name. You can also use a Filter instead of a Servlet by setting spring.jersey.type=filter
(in which case the @Bean
to replace or override isjerseyFilterRegistration
). The servlet has an @Order
which you can set with spring.jersey.filter.order
. Both the Servlet and the Filter registrations can be given init parameters using spring.jersey.init.*
to specify a map of properties.
There is a Jersey sample so you can see how to set things up. There is also a Jersey 1.x sample. Note that in the Jersey 1.x sample that the spring-boot maven plugin has been configured to unpack some Jersey jars so they can be scanned by the JAX-RS implementation (because the sample asks for them to be scanned in its Filter
registration). You may need to do the same if any of your JAX-RS resources are packaged as nested jars.
27.4 Embedded servlet container support
Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. Most developers will simply use the appropriate ‘Starter’ to obtain a fully configured instance. By default the embedded server will listen for HTTP requests on port 8080
.
If you choose to use Tomcat on CentOS be aware that, by default, a temporary directory is used to store compiled JSPs, file uploads etc. This directory may be deleted by |
27.4.1 Servlets, Filters, and listeners
When using an embedded servlet container you can register Servlets, Filters and all the listeners from the Servlet spec (e.g. HttpSessionListener
) either by using Spring beans or by scanning for Servlet components.
Registering Servlets, Filters, and listeners as Spring beans
Any Servlet
, Filter
or Servlet *Listener
instance that is a Spring bean will be registered with the embedded container. This can be particularly convenient if you want to refer to a value from your application.properties
during configuration.
By default, if the context contains only a single Servlet it will be mapped to /
. In the case of multiple Servlet beans the bean name will be used as a path prefix. Filters will map to /*
.
If convention-based mapping is not flexible enough you can use the ServletRegistrationBean
, FilterRegistrationBean
and ServletListenerRegistrationBean
classes for complete control.
27.4.2 Servlet Context Initialization
Embedded servlet containers will not directly execute the Servlet 3.0+ javax.servlet.ServletContainerInitializer
interface, or Spring’sorg.springframework.web.WebApplicationInitializer
interface. This is an intentional design decision intended to reduce the risk that 3rd party libraries designed to run inside a war will break Spring Boot applications.
If you need to perform servlet context initialization in a Spring Boot application, you should register a bean that implements theorg.springframework.boot.web.servlet.ServletContextInitializer
interface. The single onStartup
method provides access to the ServletContext
, and can easily be used as an adapter to an existing WebApplicationInitializer
if necessary.
Scanning for Servlets, Filters, and listeners
When using an embedded container, automatic registration of @WebServlet
, @WebFilter
, and @WebListener
annotated classes can be enabled using @ServletComponentScan
.
|
27.4.3 The ServletWebServerApplicationContext
Under the hood Spring Boot uses a new type of ApplicationContext
for embedded servlet container support. The ServletWebServerApplicationContext
is a special type of WebApplicationContext
that bootstraps itself by searching for a single ServletWebServerFactory
bean. Usually a TomcatServletWebServerFactory
, JettyServletWebServerFactory
, or UndertowServletWebServerFactory
will have been auto-configured.
You usually won’t need to be aware of these implementation classes. Most applications will be auto-configured and the appropriate |
27.4.4 Customizing embedded servlet containers
Common servlet container settings can be configured using Spring Environment
properties. Usually you would define the properties in your application.properties
file.
Common server settings include:
- Network settings: listen port for incoming HTTP requests (
server.port
), interface address to bind toserver.address
, etc. - Session settings: whether the session is persistent (
server.session.persistence
), session timeout (server.session.timeout
), location of session data (server.session.store-dir
) and session-cookie configuration (server.session.cookie.*
). - Error management: location of the error page (
server.error.path
), etc. - SSL
- HTTP compression
Spring Boot tries as much as possible to expose common settings but this is not always possible. For those cases, dedicated namespaces offer server-specific customizations (see server.tomcat
and server.undertow
). For instance, access logs can be configured with specific features of the embedded servlet container.
See the |
Programmatic customization
If you need to configure your embedded servlet container programmatically you can register a Spring bean that implements the WebServerFactoryCustomizer
interface. WebServerFactoryCustomizer
provides access to the ConfigurableServletWebServerFactory
which includes numerous customization setter methods. Dedicated variants exists for Tomcat, Jetty and Undertow.
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component; @Component
公共 类 CustomizationBean实现 WebServerFactoryCustomizer <ConfigurableServletWebServerFactory> { @Override
public void customize(ConfigurableServletWebServerFactory server){
server.setPort(9000);
} }
直接自定义ConfigurableServletWebServerFactory
如果上面的自定义方法太有限,你可以注册 TomcatServletWebServerFactory
,JettyServletWebServerFactory
或 UndertowServletWebServerFactory
豆你自己。
@Bean
public ConfigurableServletWebServerFactory webServerFactory(){
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.setPort(9000);
factory.setSessionTimeout(10,TimeUnit.MINUTES);
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,“/ notfound.html”));
返回工厂;
}
为许多配置选项提供了Setter。如果您需要做一些更具异国情调的事情,还会提供几种受保护的方法“挂钩”。有关详细信息,请参阅源代码文档。
28.安全
如果Spring Security位于类路径上,则默认情况下Web应用程序将在所有HTTP端点上使用“基本”身份验证。要向Web应用程序添加方法级安全性,您还可以@EnableGlobalMethodSecurity
使用所需的设置进行添加。其他信息可以在Spring Security Reference中找到。
默认设置AuthenticationManager
只有一个用户('用户'用户名和随机密码,在应用程序启动时以INFO级别打印)
使用默认安全密码:78fa095d-3f4c-48b1-ad50-e24c31d5cf35
如果您对日志记录配置进行微调,请确保将 |
您可以通过提供一个来更改密码security.user.password
。此属性和其他有用属性通过SecurityProperties
(属性前缀“security”)外部化 。
默认安全配置在SecurityAutoConfiguration
从那里导入的类中实现(SpringBootWebSecurityConfiguration
对于Web安全性和AuthenticationManagerConfiguration
用于非Web应用程序中相关的身份验证配置)。要完全关闭默认Web应用程序安全配置,您可以添加一个bean @EnableWebSecurity
(这不会禁用身份验证管理器配置或Actuator的安全性)。要自定义它,通常使用外部属性和类型的bean WebSecurityConfigurerAdapter
(例如,添加基于表单的登录)。
如果添加 |
要关闭身份验证管理器配置,您可以添加类型的bean AuthenticationManager
,或者AuthenticationManager
通过自动装配AuthenticationManagerBuilder
到其中一个@Configuration
类中的方法来配置全局。Spring Boot示例中有几个安全的应用程序可以帮助您开始使用常见的用例。
您在Web应用程序中开箱即用的基本功能包括:
-
AuthenticationManager
具有内存存储和单个用户的bean(请参阅用户SecurityProperties.User
的属性)。 - 常见的静态资源位置忽略(不安全的)路径(
/css/**
,/js/**
,/images/**
,/webjars/**
和**/favicon.ico
)。 - 所有其他端点的HTTP基本安全性。
- 发布到Spring的安全事件
ApplicationEventPublisher
(成功和不成功的身份验证和访问被拒绝)。 - Spring Security提供的常见低级功能(HSTS,XSS,CSRF,缓存)默认启用。
以上所有内容都可以使用外部属性(security.*
)打开或关闭或修改。要覆盖访问规则不改变任何其它的自动配置功能添加@Bean
型WebSecurityConfigurerAdapter
与 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
并对其进行配置,以满足您的需求。
默认情况下,a |
28.1 OAuth2
如果您具有spring-security-oauth2
类路径,则可以利用某些自动配置来轻松设置授权或资源服务器。有关完整详细信息,请参阅“ Spring Security OAuth 2开发人员指南”。
28.1.1授权服务器
要创建授权服务器并授予访问令牌,您需要使用 @EnableAuthorizationServer
和提供security.oauth2.client.client-id
和security.oauth2.client.client-secret]
属性。客户端将在内存存储库中为您注册。
完成后,您将能够使用客户端凭据创建访问令牌,例如:
$ curl client:secret @ localhost :8080 / oauth / token -d grant_type = password -d username = user -d password = pwd
/token
端点的基本身份验证凭据是client-id
和 client-secret
。用户凭据是正常的Spring Security用户详细信息(在Spring Boot中默认为“user”和随机密码)。
要关闭自动配置并自行配置授权服务器功能,只需添加一种@Bean
类型AuthorizationServerConfigurer
。
28.1.2资源服务器
To use the access token you need a Resource Server (which can be the same as the Authorization Server). Creating a Resource Server is easy, just add@EnableResourceServer
and provide some configuration to allow the server to decode access tokens. If your application is also an Authorization Server it already knows how to decode tokens, so there is nothing else to do. If your app is a standalone service then you need to give it some more configuration, one of the following options:
-
security.oauth2.resource.user-info-uri
to use the/me
resource (e.g.https://uaa.run.pivotal.io/userinfo
on PWS) -
security.oauth2.resource.token-info-uri
to use the token decoding endpoint (e.g.https://uaa.run.pivotal.io/check_token
on PWS).
If you specify both the user-info-uri
and the token-info-uri
then you can set a flag to say that one is preferred over the other (prefer-token-info=true
is the default).
Alternatively (instead of user-info-uri
or token-info-uri
) if the tokens are JWTs you can configure a security.oauth2.resource.jwt.key-value
to decode them locally (where the key is a verification key). The verification key value is either a symmetric secret or PEM-encoded RSA public key. If you don’t have the key and it’s public you can provide a URI where it can be downloaded (as a JSON object with a “value” field) with security.oauth2.resource.jwt.key-uri
. E.g. on PWS:
$ curl https://uaa.run.pivotal.io/token_key
{"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"}
If you use the |
OAuth2 resources are protected by a filter chain with order security.oauth2.resource.filter-order
and the default is after the filter protecting the actuator endpoints by default (so actuator endpoints will stay on HTTP Basic unless you change the order).
28.2 Token Type in User Info
Google, and certain other 3rd party identity providers, are more strict about the token type name that is sent in the headers to the user info endpoint. The default is “Bearer” which suits most providers and matches the spec, but if you need to change it you can set security.oauth2.resource.token-type
.
28.3 Customizing the User Info RestTemplate
If you have a user-info-uri
, the resource server features use an OAuth2RestTemplate
internally to fetch user details for authentication. This is provided as a @Bean
of type UserInfoRestTemplateFactory
. The default should be fine for most providers, but occasionally you might need to add additional interceptors, or change the request authenticator (which is how the token gets attached to outgoing requests). To add a customization just create a bean of type UserInfoRestTemplateCustomizer
- it has a single method that will be called after the bean is created but before it is initialized. The rest template that is being customized here is only used internally to carry out authentication. Alternatively, you could define your own UserInfoRestTemplateFactory
@Bean
to take full control.
To set an RSA key value in YAML use the “pipe” continuation marker to split it over multiple lines (“|”) and remember to indent the key value (it’s a standard YAML language feature). Example: security: |
28.3.1 Client
To make your web-app into an OAuth2 client you can simply add @EnableOAuth2Client
and Spring Boot will create a OAuth2ClientContext
and OAuth2ProtectedResourceDetails
that are necessary to create an OAuth2RestOperations
. Spring Boot does not automatically create such bean but you can easily create your own:
@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
OAuth2ProtectedResourceDetails details) {
return new OAuth2RestTemplate(details, oauth2ClientContext);
}
You may want to add a qualifier and review your configuration as more than one |
This configuration uses security.oauth2.client.*
as credentials (the same as you might be using in the Authorization Server), but in addition it will need to know the authorization and token URIs in the Authorization Server. For example:
application.yml.
security:
oauth2:
client:
clientId: bd1c0a783ccdd1c9b9e4
clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
accessTokenUri: https://github.com/login/oauth/access_token
userAuthorizationUri: https://github.com/login/oauth/authorize
clientAuthenticationScheme: form
An application with this configuration will redirect to Github for authorization when you attempt to use the OAuth2RestTemplate
. If you are already signed into Github you won’t even notice that it has authenticated. These specific credentials will only work if your application is running on port 8080 (register your own client app in Github or other provider for more flexibility).
To limit the scope that the client asks for when it obtains an access token you can set security.oauth2.client.scope
(comma separated or an array in YAML). By default the scope is empty and it is up to Authorization Server to decide what the defaults should be, usually depending on the settings in the client registration that it holds.
There is also a setting for |
In a non-web application you can still create an |
28.3.2 Single Sign On
An OAuth2 Client can be used to fetch user details from the provider (if such features are available) and then convert them into an Authentication
token for Spring Security. The Resource Server above support this via the user-info-uri
property This is the basis for a Single Sign On (SSO) protocol based on OAuth2, and Spring Boot makes it easy to participate by providing an annotation @EnableOAuth2Sso
. The Github client above can protect all its resources and authenticate using the Github /user/
endpoint, by adding that annotation and declaring where to find the endpoint (in addition to the security.oauth2.client.*
configuration already listed above):
application.yml.
security:
oauth2:
...
resource:
userInfoUri: https://api.github.com/user
preferTokenInfo: false
Since all paths are secure by default, there is no “home” page that you can show to unauthenticated users and invite them to login (by visiting the /login
path, or the path specified by security.oauth2.sso.login-path
).
To customize the access rules or paths to protect, so you can add a “home” page for instance, @EnableOAuth2Sso
can be added to a WebSecurityConfigurerAdapter
and the annotation will cause it to be decorated and enhanced with the necessary pieces to get the /login
path working. For example, here we simply allow unauthenticated access to the home page at "/" and keep the default for everything else:
@Configuration
static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override
public void init(WebSecurity web) {
web.ignoring().antMatchers("/");
} @Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().anyRequest().authenticated();
} }
28.4 Actuator Security
If the Actuator is also in use, you will find:
- The management endpoints are secure even if the application endpoints are insecure.
- Security events are transformed into
AuditEvent
instances and published to theAuditEventRepository
. - The default user will have the
ACTUATOR
role as well as theUSER
role.
The Actuator security features can be modified using external properties (management.security.*
). To override the application access rules add a @Bean
of type WebSecurityConfigurerAdapter
and use @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
if you don’t want to override the actuator access rules, or @Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
if you do want to override the actuator access rules.
29. Working with SQL databases
The Spring Framework provides extensive support for working with SQL databases. From direct JDBC access using JdbcTemplate
to complete ‘object relational mapping’ technologies such as Hibernate. Spring Data provides an additional level of functionality, creating Repository
implementations directly from interfaces and using conventions to generate queries from your method names.
29.1 Configure a DataSource
Java’s javax.sql.DataSource
interface provides a standard method of working with database connections. Traditionally a DataSource uses a URL
along with some credentials to establish a database connection.
Check also the ‘How-to’ section for more advanced examples, typically to take full control over the configuration of the DataSource. |
29.1.1 Embedded Database Support
It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.
The ‘How-to’ section includes a section on how to initialize a database |
Spring Boot can auto-configure embedded H2, HSQL and Derby databases. You don’t need to provide any connection URLs, simply include a build dependency to the embedded database that you want to use.
If you are using this feature in your tests, you may notice that the same database is reused by your whole test suite regardless of the number of application contexts that you use. If you want to make sure that each context has a separate embedded database, you should set |
For example, typical POM dependencies would be:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
You need a dependency on |
If, for whatever reason, you do configure the connection URL for an embedded database, care should be taken to ensure that the database’s automatic shutdown is disabled. If you’re using H2 you should use |
29.1.2 Connection to a production database
Production database connections can also be auto-configured using a pooling DataSource
. Here’s the algorithm for choosing a specific implementation:
- We prefer HikariCP for its performance and concurrency, so if that is available we always choose it.
- Otherwise, if the Tomcat pooling
DataSource
is available we will use it. - If neither HikariCP nor the Tomcat pooling datasource are available and if Commons DBCP2 is available we will use it.
If you use the spring-boot-starter-jdbc
or spring-boot-starter-data-jpa
‘starters’ you will automatically get a dependency to HikariCP
.
You can bypass that algorithm completely and specify the connection pool to use via the |
Additional connection pools can always be configured manually. If you define your own |
DataSource configuration is controlled by external configuration properties in spring.datasource.*
. For example, you might declare the following section inapplication.properties
:
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
You should at least specify the url using the |
You often won’t need to specify the |
For a pooling |
See DataSourceProperties
for more of the supported options. These are the standard options that work regardless of the actual implementation. It is also possible to fine-tune implementation-specific settings using their respective prefix (spring.datasource.hikari.*
, spring.datasource.tomcat.*
, and spring.datasource.dbcp2.*
). Refer to the documentation of the connection pool implementation you are using for more details.
For instance, if you are using the Tomcat connection pool you could customize many additional settings:
#如果没有可用连接,则在抛出异常之前要等待的ms数。
spring.datasource.tomcat.max-wait = 10000 #可以同时从该池分配的最大活动连接数。
spring.datasource.tomcat.max-active = 50 #在从池中借用连接之前验证连接。
spring.datasource.tomcat.test-on-borrow = true
29.1.3连接到JNDI数据源
如果要将Spring Boot应用程序部署到Application Server,则可能需要使用Application Server内置功能配置和管理DataSource,并使用JNDI访问它。
该spring.datasource.jndi-name
属性可以被用作一个替代 spring.datasource.url
,spring.datasource.username
和spring.datasource.password
属性来访问DataSource
从一个特定的JNDI位置。例如,以下部分application.properties
显示了如何访问定义的JBoss AS DataSource
:
spring.datasource.jndi-name = java:jboss / datasources / customers
29.2使用JdbcTemplate
Spring JdbcTemplate
和NamedParameterJdbcTemplate
类是自动配置的,你可以将@Autowire
它们直接放到你自己的bean中:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component; @Component
公共 类 MyBean { private final JdbcTemplate jdbcTemplate; @Autowired
public MyBean(JdbcTemplate jdbcTemplate){
this .jdbcTemplate = jdbcTemplate;
} // ... }
您可以使用以下spring.jdbc.template.*
属性自定义模板的某些属性:
spring.jdbc.template.max-rows = 500
在 |
29.3 JPA和'Spring Data'
Java Persistence API是一种标准技术,允许您将对象“映射”到关系数据库。该spring-boot-starter-data-jpa
POM提供了上手的快捷方式。它提供以下关键依赖项:
- Hibernate - 最受欢迎的JPA实现之一。
- Spring Data JPA - 使实现基于JPA的存储库变得容易。
- Spring ORMs - 来自Spring Framework的核心ORM支持。
我们不会在这里讨论太多关于JPA或Spring Data的细节。您可以按照 “使用JPA访问数据”从引导 spring.io并宣读了春天的数据JPA 和Hibernate的参考文档。 |
29.3.1实体类
传统上,JPA“实体”类在persistence.xml
文件中指定。使用Spring Boot,此文件不是必需的,而是使用“实体扫描”。默认情况下,将搜索主配置类下面的所有包(用@EnableAutoConfiguration
or 注释 @SpringBootApplication
)。
任何类注释用@Entity
,@Embeddable
或@MappedSuperclass
将予以考虑。典型的实体类看起来像这样:
package com.example.myapp.domain; import java.io.Serializable;
import javax.persistence。*; @Entity
公共 类 City实现 Serializable { @Id
@GeneratedValue
private Long id; @Column(nullable = false)
私有 String名称; @Column(nullable = false)
私有 String状态; // ...其他成员,通常包括@OneToMany映射 protected City(){
// JPA规范要求的no-args构造函数
//这个是受保护的,因为它不应该直接使用
} public City(String name,String state){
this .name = name;
这个 .country = country;
} public String getName(){
return this .name;
} public String getState(){
return this .state;
} //等等 }
您可以使用 |
29.3.2 Spring Data JPA存储库
Spring Data JPA存储库是您可以定义以访问数据的接口。JPA查询是从您的方法名称自动创建的。例如,CityRepository
接口可能会声明一种findAllByState(String state)
方法来查找给定状态中的所有城市。
对于更复杂的查询,您可以使用Spring Data的Query
注释来注释您的方法 。
Spring Data存储库通常从Repository
或 CrudRepository
接口扩展 。如果您使用的是自动配置,则将从包含主配置类(带有@EnableAutoConfiguration
或标注的类)的软件包中搜索存储库 @SpringBootApplication
。
这是一个典型的Spring Data存储库:
package com.example.myapp.domain; import org.springframework.data.domain。*;
import org.springframework.data.repository。*; 公共 接口 CityRepository 扩展了 Repository <City,Long> { Page <City> findAll(可分页可分页); City findByNameAndCountryAllIgnoringCase(String name,String country); }
我们几乎没有涉及Spring Data JPA的表面。有关详细信息,请查看其参考文档。 |
29.3.3创建和删除JPA数据库
默认情况下,仅当您使用嵌入式数据库(H2,HSQL或Derby)时,才会自动创建JPA数据库。您可以使用spring.jpa.*
属性显式配置JPA设置 。例如,要创建和删除表,您可以将以下内容添加到您的表中application.properties
。
spring.jpa.hibernate.ddl-AUTO =创造降
Hibernate自己的内部属性名称(如果你碰巧记得更好)是 |
spring.jpa.properties.hibernate.globally_quoted_identifiers =真
传递hibernate.globally_quoted_identifiers
给Hibernate实体管理器。
默认情况下,DDL执行(或验证)将延迟到ApplicationContext
启动。还有一个spring.jpa.generate-ddl
标志,但如果Hibernate autoconfig处于活动状态,则不会使用该标志,因为ddl-auto
设置更精细。
29.3.4在视图中打开EntityManager
如果您正在运行Web应用程序,Spring Boot将默认注册 OpenEntityManagerInViewInterceptor
以应用“在视图中打开EntityManager”模式,即允许在Web视图中进行延迟加载。如果你不希望这种行为,你应该设置spring.jpa.open-in-view
到 false
你application.properties
。
29.4使用H2的Web控制台
该H2数据库提供了一个 基于浏览器的控制台是春天开机即可自动为您配置。满足以下条件时,将自动配置控制台:
- 您正在开发Web应用程序
-
com.h2database:h2
在类路径上 - 您正在使用Spring Boot的开发人员工具
如果您没有使用Spring Boot的开发人员工具,但仍想使用H2的控制台,那么您可以通过配置 |
29.4.1更改H2控制台的路径
默认情况下,控制台将在/h2-console
。您可以使用spring.h2.console.path
属性自定义控制台的路径。
29.4.2固定H2控制台
当Spring Security在类路径上并且启用了基本身份验证时,H2控制台将使用基本身份验证自动保护。以下属性可用于自定义安全性配置:
security.user.role
security.basic.authorize-mode
security.basic.enabled
29.5使用jOOQ
Java面向对象查询(jOOQ)是Data Geekery的一个流行产品, 它从您的数据库生成Java代码,并允许您通过其流畅的API构建类型安全的SQL查询。商业版和开源版都可以与Spring Boot一起使用。
29.5.1代码生成
In order to use jOOQ type-safe queries, you need to generate Java classes from your database schema. You can follow the instructions in the jOOQ user manual. If you are using the jooq-codegen-maven
plugin (and you also use the spring-boot-starter-parent
“parent POM”) you can safely omit the plugin’s <version>
tag. You can also use Spring Boot defined version variables (e.g. h2.version
) to declare the plugin’s database dependency. Here’s an example:
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<executions>
...
</executions>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
<configuration>
<jdbc>
<driver>org.h2.Driver</driver>
<url>jdbc:h2:~/yourdatabase</url>
</jdbc>
<generator>
...
</generator>
</configuration>
</plugin>
29.5.2 Using DSLContext
The fluent API offered by jOOQ is initiated via the org.jooq.DSLContext
interface. Spring Boot will auto-configure a DSLContext
as a Spring Bean and connect it to your application DataSource
. To use the DSLContext
you can just @Autowire
it:
@Component
public class JooqExample implements CommandLineRunner { private final DSLContext create; @Autowired
public JooqExample(DSLContext dslContext) {
this.create = dslContext;
} }
The jOOQ manual tends to use a variable named |
You can then use the DSLContext
to construct your queries:
public List<GregorianCalendar> authorsBornAfter1980() {
return this.create.selectFrom(AUTHOR)
.where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1)))
.fetch(AUTHOR.DATE_OF_BIRTH);
}
29.5.3 jOOQ SQL dialect
Spring Boot determines the SQL dialect to use for your datasource unless the spring.jooq.sql-dialect
property has been configured. If the dialect couldn’t be detected, DEFAULT
is used.
Spring Boot can only auto-configure dialects supported by the open source version of jOOQ. |
29.5.4 Customizing jOOQ
More advanced customizations can be achieved by defining your own @Bean
definitions which will be used when the jOOQ Configuration
is created. You can define beans for the following jOOQ Types:
ConnectionProvider
TransactionProvider
RecordMapperProvider
RecordListenerProvider
ExecuteListenerProvider
VisitListenerProvider
You can also create your own org.jooq.Configuration
@Bean
if you want to take complete control of the jOOQ configuration.
30. Working with NoSQL technologies
Spring Data provides additional projects that help you access a variety of NoSQL technologies including MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire,Cassandra, Couchbase and LDAP. Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr Cassandra, Couchbase and LDAP; you can make use of the other projects, but you will need to configure them yourself. Refer to the appropriate reference documentation at projects.spring.io/spring-data.
30.1 Redis
Redis is a cache, message broker and richly-featured key-value store. Spring Boot offers basic auto-configuration for the Jedis and Lettuce client library and abstractions on top of it provided by Spring Data Redis.
There is a spring-boot-starter-data-redis
‘Starter’ for collecting the dependencies in a convenient way that uses Jedis by default. If you are building a reactive application, the spring-boot-starter-data-redis-reactive
‘Starter’ will get you going.
30.1.1 Connecting to Redis
You can inject an auto-configured RedisConnectionFactory
, StringRedisTemplate
or vanilla RedisTemplate
instance as you would any other Spring Bean. By default the instance will attempt to connect to a Redis server using localhost:6379
:
@Component
public class MyBean { 私有 StringRedisTemplate模板; @Autowired
public MyBean(StringRedisTemplate template){
this .template = template;
} // ... }
您还可以注册任意数量的bean,以实现 |
如果您添加@Bean
自己的任何自动配置类型,它将替换默认值(除非RedisTemplate
排除是基于bean名称'redisTemplate'而不是其类型)。如果commons-pool2
在类路径上,默认情况下您将获得池连接工厂。
30.2 MongoDB
MongoDB是一个开源的NoSQL文档数据库,它使用类似JSON的模式而不是传统的基于表的关系数据。Spring Boot提供了一些使用MongoDB的便利,包括spring-boot-starter-data-mongodb
和spring-boot-starter-data-mongodb-reactive
'Starters'。
30.2.1连接MongoDB数据库
您可以注入自动配置org.springframework.data.mongodb.MongoDbFactory
以访问Mongo数据库。默认情况下,实例将尝试使用URL连接到MongoDB服务器mongodb://localhost/test
:
import org.springframework.data.mongodb.MongoDbFactory;
import com.mongodb.DB; @Component
公共 类 MyBean { 私人 决赛 MongoDbFactory mongo; @Autowired
public MyBean(MongoDbFactory mongo){
this .mongo = mongo;
} // ... public void example(){
DB db = mongo.getDb();
// ...
} }
您可以设置spring.data.mongodb.uri
属性以更改URL并配置其他设置,例如副本集:
spring.data.mongodb.uri = mongodb:// user:secret@mongo1.example.com :12345,mongo2.example.com:23456 / test
或者,只要您使用Mongo 2.x,请指定host
/ port
。例如,您可以在以下内容中声明以下内容application.properties
:
spring.data.mongodb.host = mongoserver
spring.data.mongodb.port = 27017
|
如果 |
如果您不使用Spring Data Mongo,则可以注入 |
如果要完全控制建立MongoDB连接,也可以声明自己的bean MongoDbFactory
或Mongo
bean。
30.2.2 MongoTemplate
Spring Data Mongo提供了一个MongoTemplate
与Spring的设计非常相似的 类JdbcTemplate
。与JdbcTemplate
Spring Boot一样,自动配置一个bean,只需注入:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component; @Component
公共 类 MyBean { 私人 决赛 MongoTemplate mongoTemplate; @Autowired
public MyBean(MongoTemplate mongoTemplate){
this .mongoTemplate = mongoTemplate;
} // ... }
有关MongoOperations
完整的详细信息,请参阅Javadoc。
30.2.3 Spring Data MongoDB存储库
Spring Data包括MongoDB的存储库支持。与前面讨论的JPA存储库一样,基本原则是根据方法名称自动为您构建查询。
事实上,Spring Data JPA和Spring Data MongoDB共享相同的通用基础架构; 所以你可以从前面拿到JPA示例,假设它City
现在是一个Mongo数据类而不是JPA @Entity
,它将以相同的方式工作。
package com.example.myapp.domain; import org.springframework.data.domain。*;
import org.springframework.data.repository。*; 公共 接口 CityRepository 扩展了 Repository <City,Long> { Page <City> findAll(可分页可分页); City findByNameAndCountryAllIgnoringCase(String name,String country); }
有关Spring Data MongoDB的完整详细信息,包括其丰富的对象映射技术,请参阅其参考文档。 |
30.2.4嵌入式Mongo
Spring Boot为Embedded Mongo提供自动配置 。要在Spring Boot应用程序中使用它,请添加依赖项 de.flapdoodle.embed:de.flapdoodle.embed.mongo
。
可以使用该spring.data.mongodb.port
属性配置Mongo将侦听的端口。要使用随机分配的空闲端口,请使用零值。在MongoClient
由创建MongoAutoConfiguration
将被自动配置为使用随机分配的端口。
如果您不配置自定义端口,则默认情况下嵌入式支持将使用随机端口(而不是27017)。 |
如果类路径上有SLF4J,Mongo生成的输出将自动路由到名为的记录器org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo
。
您可以声明自己的bean IMongodConfig
和IRuntimeConfig
bean来控制Mongo实例的配置和日志记录路由。
30.3 Neo4j
Neo4j是一个开源的NoSQL图形数据库,它使用与第一类关系相关的节点的丰富数据模型,与传统的rdbms方法相比,它更适合于连接的大数据。Spring Boot为使用Neo4j提供了一些便利,包括spring-boot-starter-data-neo4j
“Starter”。
30.3.1连接到Neo4j数据库
你可以注入的自动配置Neo4jSession
,Session
或者Neo4jOperations
,就像任何其他的Spring Bean实例。默认情况下,实例将尝试使用以下命令连接到Neo4j服务器localhost:7474
:
@Component
公共 类 MyBean { private final Neo4jTemplate neo4jTemplate; @Autowired
public MyBean(Neo4jTemplate neo4jTemplate) {
this.neo4jTemplate = neo4jTemplate;
} // ... }
You can take full control of the configuration by adding a org.neo4j.ogm.config.Configuration
@Bean
of your own. Also, adding a @Bean
of typeNeo4jOperations
disables the auto-configuration.
You can configure the user and credentials to use via the spring.data.neo4j.*
properties:
spring.data.neo4j.uri=http://my-server:7474
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=secret
30.3.2 Using the embedded mode
如果添加org.neo4j:neo4j-ogm-embedded-driver
到应用程序的依赖项,Spring Boot将自动配置Neo4j的进程内嵌入式实例,在应用程序关闭时不会保留任何数据。您可以使用显式禁用该模式spring.data.neo4j.embedded.enabled=false
。您还可以为嵌入模式启用持久性:
spring.data.neo4j.uri =文件://var/tmp/graph.db
Neo4j OGM嵌入式驱动程序不提供Neo4j内核。用户需要手动提供此依赖关系, 有关详细信息,请参阅 文档。 |
30.3.3 Neo4jSession
默认情况下,如果您正在运行Web应用程序,则会话将绑定到线程以进行整个请求处理(即“在视图中打开会话”模式)。如果您不想要此行为,请将以下内容添加到您的application.properties
:
spring.data.neo4j.open式视=假
30.3.4 Spring Data Neo4j存储库
Spring Data包含对Neo4j的存储库支持。
事实上,Spring Data JPA和Spring Data Neo4j共享相同的通用基础架构; 所以你可以从前面拿到JPA例子,假设City
现在是Neo4j OGM @NodeEntity
而不是JPA @Entity
,它将以相同的方式工作。
您可以使用 |
要启用存储库支持(以及可选的支持@Transactional
),请在Spring配置中添加以下两个注释:
@ EnableNeo4jRepositories(basePackages =“com.example.myapp.repository”)
@EnableTransactionManagement
30.3.5存储库示例
package com.example.myapp.domain; import org.springframework.data.domain。*;
import org.springframework.data.repository。*; 公共 接口 CityRepository 扩展了 GraphRepository <City> { Page <City> findAll(可分页可分页); City findByNameAndCountry(String name,String country); }
有关Spring Data Neo4j的完整详细信息,包括其丰富的对象映射技术,请参阅其参考文档。 |
30.4 Gemfire
Spring Data Gemfire提供了方便的Spring友好工具,用于访问 Pivotal Gemfire数据管理平台。有一个spring-boot-starter-data-gemfire
'Starter'用于以方便的方式收集依赖项。目前没有对Gemfire的自动配置支持,但您可以使用单个注释(@EnableGemfireRepositories
)启用Spring Data Repositories 。
30.5 Solr
Apache Solr是一个搜索引擎。Spring Boot为Solr 5客户端库提供基本的自动配置,并在Spring Data Solr提供的基础上提供抽象 。有一个spring-boot-starter-data-solr
'Starter'用于以方便的方式收集依赖项。
30.5.1连接到Solr
You can inject an auto-configured SolrClient
instance as you would any other Spring bean. By default the instance will attempt to connect to a server usinglocalhost:8983/solr
:
@Component
public class MyBean { private SolrClient solr; @Autowired
public MyBean(SolrClient solr) {
this.solr = solr;
} // ... }
If you add a @Bean
of your own of type SolrClient
it will replace the default.
30.5.2 Spring Data Solr repositories
Spring Data includes repository support for Apache Solr. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.
In fact, both Spring Data JPA and Spring Data Solr share the same common infrastructure; so you could take the JPA example from earlier and, assuming that City
is now a @SolrDocument
class rather than a JPA @Entity
, it will work in the same way.
For complete details of Spring Data Solr, refer to their reference documentation. |
30.6 Elasticsearch
Elasticsearch is an open source, distributed, real-time search and analytics engine. Spring Boot offers basic auto-configuration for the Elasticsearch and abstractions on top of it provided by Spring Data Elasticsearch. There is a spring-boot-starter-data-elasticsearch
‘Starter’ for collecting the dependencies in a convenient way. Spring Boot also supports Jest.
30.6.1 Connecting to Elasticsearch using Jest
If you have Jest
on the classpath, you can inject an auto-configured JestClient
targeting localhost:9200
by default. You can further tune how the client is configured:
spring.elasticsearch.jest.uris=http://search.example.com:9200
spring.elasticsearch.jest.read-timeout=10000
spring.elasticsearch.jest.username=user
spring.elasticsearch.jest.password=secret
You can also register an arbitrary number of beans implementing HttpClientConfigBuilderCustomizer
for more advanced customizations. The example below tunes additional HTTP settings:
static class HttpSettingsCustomizer implements HttpClientConfigBuilderCustomizer { @Override
public void customize(HttpClientConfig.Builder builder) {
builder.maxTotalConnection(100).defaultMaxTotalConnectionPerRoute(5);
} }
To take full control over the registration, define a JestClient
bean.
30.6.2 Connecting to Elasticsearch using Spring Data
To connect to Elasticsearch you must provide the address of one or more cluster nodes. The address can be specified by setting the spring.data.elasticsearch.cluster-nodes
property to a comma-separated ‘host:port’ list. With this configuration in place, an ElasticsearchTemplate
or TransportClient
can be injected like any other Spring bean:
spring.data.elasticsearch.cluster-nodes=localhost:9300
@Component
public class MyBean { private final ElasticsearchTemplate template; public MyBean(ElasticsearchTemplate template) {
this.template = template;
} // ... }
If you add your own ElasticsearchTemplate
or TransportClient
@Bean
it will replace the default.
30.6.3 Spring Data Elasticsearch repositories
Spring Data includes repository support for Elasticsearch. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.
In fact, both Spring Data JPA and Spring Data Elasticsearch share the same common infrastructure; so you could take the JPA example from earlier and, assuming thatCity
is now an Elasticsearch @Document
class rather than a JPA @Entity
, it will work in the same way.
有关Spring Data Elasticsearch的完整详细信息,请参阅其 参考文档。 |
30.7卡桑德拉
Cassandra是一个开源的分布式数据库管理系统,旨在处理许多商用服务器上的大量数据。Spring Boot提供了由Spring Data Cassandra提供的Cassandra和抽象的自动配置 。有一个spring-boot-starter-data-cassandra
'Starter'用于以方便的方式收集依赖项。
30.7.1连接到Cassandra
您可以 像使用任何其他Spring Bean一样注入自动配置CassandraTemplate
或Cassandra Session
实例。这些spring.data.cassandra.*
属性可用于自定义连接。一般来说,您将提供 keyspace-name
和contact-points
属性:
spring.data.cassandra.keyspace-name = mykeyspace
spring.data.cassandra.contact-points = cassandrahost1,cassandrahost2
@Component
公共 类 MyBean { 私人 CassandraTemplate模板; @Autowired
public MyBean(CassandraTemplate模板){
this .template = template;
} // ... }
如果您添加@Bean
自己的类型CassandraTemplate
,它将替换默认值。
30.7.2 Spring Data Cassandra存储库
Spring Data包含对Cassandra的基本存储库支持。目前,这比前面讨论的JPA存储库更有限,并且需要使用注释方法注释@Query
。
有关Spring Data Cassandra的完整详细信息,请参阅其 参考文档。 |
30.8 Couchbase
Couchbase是一个开源的,分布式的多模型NoSQL面向文档的数据库,针对交互式应用程序进行了优化。Spring Boot提供了由Spring Data Couchbase提供的Couchbase和抽象的自动配置 。有一个spring-boot-starter-data-couchbase
'Starter'用于以方便的方式收集依赖项。
30.8.1连接Couchbase
您可以非常轻松地获得Bucket
并Cluster
添加Couchbase SDK和一些配置。这些spring.couchbase.*
属性可用于自定义连接。通常,您将提供引导主机,存储桶名称和密码:
spring.couchbase.bootstrap-hosts=my-host-1,192.168.1.123
spring.couchbase.bucket.name=my-bucket
spring.couchbase.bucket.password=secret
You need to provide at least the bootstrap host(s), in which case the bucket name is |
It is also possible to customize some of the CouchbaseEnvironment
settings. For instance the following configuration changes the timeout to use to open a new Bucket
and enables SSL support:
spring.couchbase.env.timeouts.connect = 3000
spring.couchbase.env.ssl.key-store = / location / of / keystore.jks
spring.couchbase.env.ssl.key-store-password = secret
检查spring.couchbase.env.*
属性以获取更多详细信息。
30.8.2 Spring Data Couchbase存储库
Spring Data包括对Couchbase的存储库支持。有关Spring Data Couchbase的完整详细信息,请参阅其 参考文档。
您可以CouchbaseTemplate
像使用任何其他Spring Bean一样注入自动配置的实例,只要默认 CouchbaseConfigurer
值可用(当您启用如上所述的couchbase支持时就会发生这种情况)。
@Component
公共 类 MyBean { 私人 决赛 CouchbaseTemplate模板; @Autowired
public MyBean(CouchbaseTemplate template){
this .template = template;
} // ... }
您可以在自己的配置中定义一些bean来覆盖自动配置提供的bean:
- 一个
CouchbaseTemplate
@Bean
名字couchbaseTemplate
- 一个
IndexManager
@Bean
名字couchbaseIndexManager
- 一个
CustomConversions
@Bean
名字couchbaseCustomConversions
为避免在您自己的配置中对这些名称进行硬编码,您可以重复使用BeanNames
Spring Data Couchbase。例如,您可以自定义要使用的转换器,如下所示:
@Configuration
公共 类 SomeConfiguration { @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
public CustomConversions myCustomConversions(){
return new CustomConversions(...);
} // ... }
如果要完全绕过Spring Data Couchbase的自动配置,请提供自己的 |
30.9 LDAP
LDAP(轻量级目录访问协议)是一种开放的,与供应商无关的行业标准应用程序协议,用于通过IP网络访问和维护分布式目录信息服务。Spring Boot为任何兼容的LDAP服务器提供自动配置,并为UnboundID支持嵌入式内存中LDAP服务器 。
LDAP抽象由 Spring Data LDAP提供。有一个spring-boot-starter-data-ldap
'Starter'用于以方便的方式收集依赖项。
30.9.1连接LDAP服务器
要连接到LDAP服务器,请确保声明对spring-boot-starter-data-ldap
“Starter” 的依赖关系, 或者spring-ldap-core
在application.properties中声明服务器的URL:
spring.ldap.urls = ldap:// myserver:1235
spring.ldap.username = admin
spring.ldap.password = secret
如果需要自定义连接设置,可以使用spring.ldap.base
和 spring.ldap.base-environment
属性。
30.9.2 Spring Data LDAP存储库
Spring Data includes repository support for LDAP. For complete details of Spring Data LDAP, refer to their reference documentation.
You can also inject an auto-configured LdapTemplate
instance as you would with any other Spring Bean.
@Component
public class MyBean { private final LdapTemplate template; @Autowired
public MyBean(LdapTemplate template) {
this.template = template;
} // ... }
30.9.3 Embedded in-memory LDAP server
For testing purposes Spring Boot supports auto-configuration of an in-memory LDAP server from UnboundID. To configure the server add a dependency to com.unboundid:unboundid-ldapsdk
and declare a base-dn
property:
spring.ldap.embedded.base-dn=dc=spring,dc=io
By default the server will start on a random port and they trigger the regular LDAP support (there is no need to specify a spring.ldap.urls
property).
If there is a schema.ldif
file on your classpath it will be used to initialize the server. You can also use the spring.ldap.embedded.ldif
property if you want to load the initialization script from a different resource.
By default, a standard schema will be used to validate LDIF
files, you can turn off validation altogether using the spring.ldap.embedded.validation.enabled
property. If you have custom attributes, you can use spring.ldap.embedded.validation.schema
to define your custom attribute types or object classes.
30.10 InfluxDB
InfluxDB is an open-source time series database optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet of Things sensor data, and real-time analytics.
30.10.1 Connecting to InfluxDB
Spring Boot auto-configures an InfluxDB
instance as long as the influxdb-java
client is on the classpath and the url of the database is set:
spring.influx.url=http://172.0.0.1:8086
If the connection to InfluxDB requires a user and password, you can set the spring.influx.user
and spring.influx.password
properties accordingly.
InfluxDB relies on OkHttp. If you need to tune the http client InfluxDB
uses behind the scenes, you can register a OkHttpClient.Builder
bean.
31. Caching
Spring Framework支持透明地向应用程序添加缓存。从本质上讲,抽象将缓存应用于方法,从而减少了基于缓存中可用信息的执行次数。缓存逻辑是透明应用的,不会对调用者造成任何干扰。只要通过@EnableCaching
注释启用了缓存支持,Spring Boot就会自动配置缓存基础结构。
简而言之,将缓存添加到服务操作就像在其方法中添加相关注释一样简单:
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Component; @Component
公共 类 MathService { @Cacheable(“piDecimals”)
public int computePiDecimal( int i){
// ...
} }
此示例演示了如何在可能代价高昂的操作上使用缓存。在调用之前computePiDecimal
,抽象将在piDecimals
与i
参数匹配的缓存中查找条目。如果找到条目,则缓存中的内容会立即返回给调用者,并且不会调用该方法。否则,在返回值之前调用该方法并更新缓存。
您还可以 |
如果您不添加任何特定的缓存库,Spring Boot将自动配置在内存中使用并发映射的 Simple提供程序。当需要缓存时(即piDecimals
在上面的示例中),此提供程序将为您即时创建它。简单的提供程序并不是真正推荐用于生产用途,但它非常适合入门并确保您了解这些功能。当您决定使用缓存提供程序时,请务必阅读其文档以了解如何配置应用程序使用的缓存。实际上,所有提供程序都要求您显式配置在应用程序中使用的每个缓存。有些提供了一种自定义spring.cache.cache-names
属性定义的默认缓存的方法。
如果您使用的缓存基础结构包含非基于接口的bean,请确保启用该 |
31.1支持的缓存提供程序
缓存抽象不提供实际存储,而是依赖于org.springframework.cache.Cache
和 org.springframework.cache.CacheManager
接口实现的抽象。
如果尚未定义类型的bean CacheManager
或CacheResolver
命名 的bean cacheResolver
(请参阅参考资料CachingConfigurer
),Spring Boot会尝试检测以下提供程序(按此顺序):
- 通用
- JCache(JSR-107)(EhCache 3,Hazelcast,Infinispan等)
- EhCache 2.x
- Hazelcast
- Infinispan的
- Couchbase
- Redis的
- 咖啡因
- 简单
It is also possible to force the cache provider to use via the |
Use the |
If the CacheManager
is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean implementing theCacheManagerCustomizer
interface. The following sets a flag to say that null values should be passed down to the underlying map.
@Bean
public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
return new CacheManagerCustomizer<ConcurrentMapCacheManager>() {
@Override
public void customize(ConcurrentMapCacheManager cacheManager) {
cacheManager.setAllowNullValues(false);
}
};
}
In the example above, an auto-configured |
31.1.1 Generic
Generic caching is used if the context defines at least one org.springframework.cache.Cache
bean. A CacheManager
wrapping all beans of that type is created.
31.1.2 JCache (JSR-107)
JCache is bootstrapped via the presence of a javax.cache.spi.CachingProvider
on the classpath (i.e. a JSR-107 compliant caching library) and the JCacheCacheManager
provided by the spring-boot-starter-cache
‘Starter’. There are various compliant libraries out there and Spring Boot provides dependency management for Ehcache 3, Hazelcast and Infinispan. Any other compliant library can be added as well.
It might happen that more than one provider is present, in which case the provider must be explicitly specified. Even if the JSR-107 standard does not enforce a standardized way to define the location of the configuration file, Spring Boot does its best to accommodate with implementation details.
# Only necessary if more than one provider is present
spring.cache.jcache.provider=com.acme.MyCachingProvider
spring.cache.jcache.config=classpath:acme.xml
Since a cache library may offer both a native implementation and JSR-107 support Spring Boot will prefer the JSR-107 support so that the same features are available if you switch to a different JSR-107 implementation. |
Spring Boot has a general support for Hazelcast. If a single |
There are several ways to customize the underlying javax.cache.cacheManager
:
- Caches can be created on startup via the
spring.cache.cache-names
property. If a customjavax.cache.configuration.Configuration
bean is defined, it is used to customize them. -
org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer
beans are invoked with the reference of theCacheManager
for full customization.
If a standard |
31.1.3 EhCache 2.x
EhCache 2.x is used if a file named ehcache.xml
can be found at the root of the classpath. If EhCache 2.x, the EhCacheCacheManager
provided by thespring-boot-starter-cache
‘Starter’ and such file is present it is used to bootstrap the cache manager. An alternate configuration file can be provided as well using:
spring.cache.ehcache.config=classpath:config/another-config.xml
31.1.4 Hazelcast
Spring Boot has a general support for Hazelcast. If a HazelcastInstance
has been auto-configured, it is automatically wrapped in a CacheManager
.
31.1.5 Infinispan
Infinispan has no default configuration file location so it must be specified explicitly (or the default bootstrap is used).
spring.cache.infinispan.config=infinispan.xml
Caches can be created on startup via the spring.cache.cache-names
property. If a custom ConfigurationBuilder
bean is defined, it is used to customize them.
The support of Infinispan in Spring Boot is restricted to the embedded mode and is quite basic. If you want more options you should use the official Infinispan Spring Boot starter instead, check the documentation for more details. |
31.1.6 Couchbase
If the Couchbase java client and the couchbase-spring-cache
implementation are available and Couchbase is configured, a CouchbaseCacheManager
will be auto-configured. It is also possible to create additional caches on startup using the spring.cache.cache-names
property. These will operate on the Bucket
that was auto-configured. You can also create additional caches on another Bucket
using the customizer: assume you need two caches on the "main" Bucket
(foo
and bar
) and one biz
cache with a custom time to live of 2sec on the another
Bucket
. First, you can create the two first caches simply via configuration:
spring.cache.cache-names=foo,bar
Then define this extra @Configuration
to configure the extra Bucket
and the biz
cache:
@Configuration
public class CouchbaseCacheConfiguration { private final Cluster cluster; public CouchbaseCacheConfiguration(Cluster cluster) {
this.cluster = cluster;
} @Bean
public Bucket anotherBucket() {
return this.cluster.openBucket("another", "secret");
} @Bean
public CacheManagerCustomizer<CouchbaseCacheManager> cacheManagerCustomizer() {
return c -> {
c.prepareCache("biz", CacheBuilder.newInstance(anotherBucket())
.withExpiration(2));
};
} }
This sample configuration reuses the Cluster
that was created via auto-configuration.
31.1.7 Redis
If Redis is available and configured, the RedisCacheManager
is auto-configured. It is also possible to create additional caches on startup using the spring.cache.cache-names
property.
By default, a key prefix is added to prevent that if two separate caches use the same key, Redis would have overlapping keys and be likely to return invalid values. We strongly recommend to keep this setting enabled if you create your own |
31.1.8 Caffeine
Caffeine is a Java 8 rewrite of Guava’s cache that supersede the Guava support. If Caffeine is present, a CaffeineCacheManager
(provided by thespring-boot-starter-cache
‘Starter’) is auto-configured. Caches can be created on startup using the spring.cache.cache-names
property and customized by one of the following (in this order):
- A cache spec defined by
spring.cache.caffeine.spec
- A
com.github.benmanes.caffeine.cache.CaffeineSpec
bean is defined - A
com.github.benmanes.caffeine.cache.Caffeine
bean is defined
For instance, the following configuration creates a foo
and bar
caches with a maximum size of 500 and a time to live of 10 minutes
spring.cache.cache-names=foo,bar
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
此外,如果com.github.benmanes.caffeine.cache.CacheLoader
定义了bean,它会自动关联到CaffeineCacheManager
。由于CacheLoader
它将与缓存管理器管理的所有缓存相关联,因此必须将其定义为CacheLoader<Object, Object>
。自动配置将忽略任何其他泛型类型。
31.1.9简单
如果找不到其他提供程序,ConcurrentHashMap
则配置使用as cache store 的简单实现 。如果应用程序中不存在缓存库,则这是默认值。默认情况下,即时创建缓存,但您可以使用该cache-names
属性限制可用缓存的列表。例如,如果您只想foo
和bar
缓存:
spring.cache.cache-names = foo,bar
如果执行此操作并且您的应用程序使用未列出的缓存,那么在运行时需要缓存时它将失败,但在启动时则不会。这类似于“真实”缓存提供程序在使用未声明的缓存时的行为方式。
31.1.10无
如果@EnableCaching
配置中存在,则还需要合适的缓存配置。如果您需要在某些环境中完全禁用缓存,请强制缓存类型none
使用no-op实现:
spring.cache.type = none
32.消息传递
Spring Framework为与消息传递系统的集成提供了广泛的支持:从简化使用JMS API JmsTemplate
到完整的基础架构,以异步接收消息。Spring AMQP为“高级消息队列协议”提供了类似的功能集,Spring Boot还为RabbitTemplate
RabbitMQ 提供了自动配置选项。Spring WebSocket本身也支持STOMP消息传递,Spring Boot通过启动器和少量自动配置支持。Spring Boot也支持Apache Kafka。
32.1 JMS
该javax.jms.ConnectionFactory
接口提供了一种创建javax.jms.Connection
与JMS代理交互的标准方法 。虽然Spring需要 ConnectionFactory
使用JMS,但您通常不需要自己直接使用它,而是可以依赖于更高级别的消息传递抽象(有关详细信息,请参阅Spring Framework参考文档的 相关部分)。Spring Boot还自动配置发送和接收消息所需的基础结构。
32.1.1 ActiveMQ支持
Spring Boot还可以ConnectionFactory
在检测到ActiveMQ在类路径上可用时进行配置。如果代理存在,则会自动启动并配置嵌入式代理(只要通过配置未指定代理URL)。
如果您正在使用 |
ActiveMQ配置由外部配置属性控制 spring.activemq.*
。例如,您可以在以下部分声明以下部分 application.properties
:
spring.activemq.broker-url = tcp://192.168.1.210:9876
spring.activemq.user = admin
spring.activemq.password = secret
您还可以通过添加依赖项org.apache.activemq:activemq-pool
并相应地配置来池化JMS资源 PooledConnectionFactory
:
spring.activemq.pool.enabled = true
spring.activemq.pool.max-connections = 50
有关 |
默认情况下,ActiveMQ会创建一个目标(如果它尚不存在),因此目标将根据其提供的名称进行解析。
32.1.2阿尔忒弥斯支持
Spring Boot can auto-configure a ConnectionFactory
when it detects that Artemis is available on the classpath. If the broker is present, an embedded broker is started and configured automatically (unless the mode property has been explicitly set). The supported modes are: embedded
(to make explicit that an embedded broker is required and should lead to an error if the broker is not available in the classpath), and native
to connect to a broker using the netty
transport protocol. When the latter is configured, Spring Boot configures a ConnectionFactory
connecting to a broker running on the local machine with the default settings.
If you are using |
Artemis configuration is controlled by external configuration properties in spring.artemis.*
. For example, you might declare the following section inapplication.properties
:
spring.artemis.mode=native
spring.artemis.host=192.168.1.210
spring.artemis.port=9876
spring.artemis.user=admin
spring.artemis.password=secret
When embedding the broker, you can choose if you want to enable persistence, and the list of destinations that should be made available. These can be specified as a comma-separated list to create them with the default options; or you can define bean(s) of typeorg.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration
or org.apache.activemq.artemis.jms.server.config.TopicConfiguration
, for advanced queue and topic configurations respectively.
See ArtemisProperties
for more of the supported options.
No JNDI lookup is involved at all and destinations are resolved against their names, either using the ‘name’ attribute in the Artemis configuration or the names provided through configuration.
32.1.3 Using a JNDI ConnectionFactory
If you are running your application in an Application Server Spring Boot will attempt to locate a JMS ConnectionFactory
using JNDI. By default the locations java:/JmsXA
and java:/XAConnectionFactory
will be checked. You can use the spring.jms.jndi-name
property if you need to specify an alternative location:
spring.jms.jndi-name=java:/MyConnectionFactory
32.1.4 Sending a message
Spring’s JmsTemplate
is auto-configured and you can autowire it directly into your own beans:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component; @Component
public class MyBean { private final JmsTemplate jmsTemplate; @Autowired
public MyBean(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
} // ... }
|
32.1.5 Receiving a message
When the JMS infrastructure is present, any bean can be annotated with @JmsListener
to create a listener endpoint. If no JmsListenerContainerFactory
has been defined, a default one is configured automatically. If a DestinationResolver
or MessageConverter
beans are defined, they are associated automatically to the default factory.
The default factory is transactional by default. If you are running in an infrastructure where a JtaTransactionManager
is present, it will be associated to the listener container by default. If not, the sessionTransacted
flag will be enabled. In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding @Transactional
on your listener method (or a delegate thereof). This will make sure that the incoming message is acknowledged once the local transaction has completed. This also includes sending response messages that have been performed on the same JMS session.
The following component creates a listener endpoint on the someQueue
destination:
@Component
public class MyBean { @JmsListener(destination =“someQueue”)
public void processMessage(String content){
// ...
} }
查看Javadoc以 |
如果您需要创建更多JmsListenerContainerFactory
实例,或者如果要覆盖默认实例,则Spring Boot提供了一个DefaultJmsListenerContainerFactoryConfigurer
可用于初始化a DefaultJmsListenerContainerFactory
的设置,其设置与自动配置的设置相同。
例如,以下公开了另一个使用特定的工厂 MessageConverter
:
@Configuration
静态 类 JmsConfiguration { @Bean
public DefaultJmsListenerContainerFactory myFactory(
DefaultJmsListenerContainerFactoryConfigurer configurer){
DefaultJmsListenerContainerFactory factory =
new DefaultJmsListenerContainerFactory();
configurer.configure(factory,connectionFactory());
factory.setMessageConverter(myMessageConverter());
返回工厂;
} }
然后您可以在任何@JmsListener
注释方法中使用如下:
@Component
公共 类 MyBean { @JmsListener(destination = “someQueue”,containerFactory =“myFactory”)
public void processMessage(String content){
// ...
} }
32.2 AMQP
高级消息队列协议(AMQP)是面向消息的中间件的平台中立的线级协议。Spring AMQP项目将核心Spring概念应用于基于AMQP的消息传递解决方案的开发。Spring Boot提供了几种通过RabbitMQ使用AMQP的便利,包括 spring-boot-starter-amqp
'Starter'。
32.2.1 RabbitMQ支持
RabbitMQ是一个基于AMQP协议的轻量级,可靠,可扩展且可移植的消息代理。Spring使用RabbitMQ
AMQP协议进行通信。
RabbitMQ配置由外部配置属性控制 spring.rabbitmq.*
。例如,您可以在以下部分声明以下部分 application.properties
:
spring.rabbitmq.host = localhost
spring.rabbitmq.port = 5672
spring.rabbitmq.username = admin
spring.rabbitmq.password = secret
有关RabbitProperties
更多支持的选项,请参阅。
检查了解AMQP,RabbitMQ使用的协议以 获取更多详细信息。 |
32.2.2发送消息
Spring的AmqpTemplate
并AmqpAdmin
配置自动,您可以直接自动装配它们变成你自己的豆:
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component
public class MyBean { private final AmqpAdmin amqpAdmin;
private final AmqpTemplate amqpTemplate; @Autowired
public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
this.amqpAdmin = amqpAdmin;
this.amqpTemplate = amqpTemplate;
} // ... }
|
Any org.springframework.amqp.core.Queue
that is defined as a bean will be automatically used to declare a corresponding queue on the RabbitMQ instance if necessary.
您可以在AmqpTemplate
重试操作上启用重试,例如在代理连接丢失的情况下。默认情况下禁用重试。
32.2.3接收消息
当Rabbit基础结构存在时,可以使用任何bean来注释 @RabbitListener
以创建侦听器端点。如果RabbitListenerContainerFactory
未定义,SimpleRabbitListenerContainerFactory
则会自动配置默认值,您可以使用该spring.rabbitmq.listener.type
属性切换到直接容器 。如果 定义了一个MessageConverter
或MessageRecoverer
bean,它们将自动关联到默认工厂。
以下组件在someQueue
队列上创建侦听器端点:
@Component
公共 类 MyBean { @RabbitListener(queues =“someQueue”)
public void processMessage(String content){
// ...
} }
查看Javadoc以 |
如果您需要创建更多的RabbitListenerContainerFactory
实例或如果要覆盖默认,春天启动提供了一个 SimpleRabbitListenerContainerFactoryConfigurer
和DirectRabbitListenerContainerFactoryConfigurer
你可以用它来初始化 SimpleRabbitListenerContainerFactory
,并DirectRabbitListenerContainerFactory
使用相同的设置,通过自动配置中使用的一个。
您选择的容器类型无关紧要,这两个bean通过自动配置公开。 |
例如,以下公开了另一个使用特定的工厂 MessageConverter
:
@Configuration
静态 类 RabbitConfiguration { @Bean
public SimpleRabbitListenerContainerFactory myFactory(
SimpleRabbitListenerContainerFactoryConfigurer configurer){
SimpleRabbitListenerContainerFactory factory =
new SimpleRabbitListenerContainerFactory();
configurer.configure(factory,connectionFactory);
factory.setMessageConverter(myMessageConverter());
返回工厂;
} }
然后您可以在任何@RabbitListener
注释方法中使用如下:
@Component
公共 类 MyBean { @RabbitListener(queues = “someQueue”,containerFactory =“myFactory”)
public void processMessage(String content){
// ...
} }
You can enable retries to handle situations where your listener throws an exception. By default RejectAndDontRequeueRecoverer
is used but you can define a MessageRecoverer
of your own. When retries are exhausted, the message will be rejected and either dropped or routed to a dead-letter exchange if the broker is configured so. Retries are disabled by default.
Important | |
---|---|
If retries are not enabled and the listener throws an exception, by default the delivery will be retried indefinitely. You can modify this behavior in two ways; set the |
32.3 Apache Kafka Support
Apache Kafka is supported by providing auto-configuration of the spring-kafka
project.
Kafka configuration is controlled by external configuration properties in spring.kafka.*
. For example, you might declare the following section inapplication.properties
:
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup
See KafkaProperties
for more of the supported options.
32.3.1 Sending a Message
Spring’s KafkaTemplate
is auto-configured and you can autowire them directly in your own beans:
@Component
public class MyBean { private final KafkaTemplate kafkaTemplate; @Autowired
public MyBean(KafkaTemplate kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
} // ... }
32.3.2 Receiving a Message
When the Apache Kafka infrastructure is present, any bean can be annotated with @KafkaListener
to create a listener endpoint. If no KafkaListenerContainerFactory
has been defined, a default one is configured automatically with keys defined in spring.kafka.listener.*
.
The following component creates a listener endpoint on the someTopic
topic:
@Component
public class MyBean { @KafkaListener(topics = "someTopic")
public void processMessage(String content) {
// ...
} }
32.3.3 Additional Kafka Properties
The properties supported by auto configuration are shown in Appendix A, Common application properties. Note that these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties for the most part, refer to the Apache Kafka documentation for details.
The first few of these properties apply to both producers and consumers, but can be specified at the producer or consumer level if you wish to use different values for each. Apache Kafka designates properties with an importance: HIGH, MEDIUM and LOW. Spring Boot auto configuration supports all HIGH importance properties, some selected MEDIUM and LOW, and any that do not have a default value.
只有Kafka支持的属性的子集可通过KafkaProperties
该类获得。如果您希望使用不直接支持的其他属性配置生产者或使用者,请使用以下命令:
spring.kafka.properties.foo.bar = baz
spring.kafka.consumer.properties.fiz.buz = qux
spring,kafka.producer.properties.baz.qux = fiz
这将常见的foo.bar
Kafka属性设置为baz
(适用于生产者和使用者),将消费者fiz.buz
属性设置qux
为baz.qux
生产者属性fiz
。
重要 | |
---|---|
以这种方式设置的属性将覆盖Spring Boot明确支持的任何配置项。 |
33.使用'RestTemplate'调用REST服务
如果需要从应用程序调用远程REST服务,可以使用Spring Framework的RestTemplate
类。由于RestTemplate
实例在使用之前通常需要自定义,因此Spring Boot不提供任何单个自动配置的 RestTemplate
bean。但是,它会自动配置a RestTemplateBuilder
,可RestTemplate
在需要时用于创建实例。自动配置RestTemplateBuilder
将确保将敏感HttpMessageConverters
应用于RestTemplate
实例。
这是一个典型的例子:
@Service
public class MyService { 私人 决赛 RestTemplate restTemplate; public MyBean(RestTemplateBuilder restTemplateBuilder){
this .restTemplate = restTemplateBuilder.build();
} 公众详细someRestCall(字符串名称){
返回 此 .restTemplate.getForObject(“/ {名} /详细信息”,详细信息。类,名);
} }
|
33.1 RestTemplate定制
RestTemplate
自定义有三种主要方法,具体取决于您希望自定义应用的广泛程度。
要使任何自定义的范围尽可能窄,请注入自动配置 RestTemplateBuilder
,然后根据需要调用其方法。每个方法调用都返回一个新RestTemplateBuilder
实例,因此自定义只会影响构建器的使用。
为了实现应用程序范围的附加定制,RestTemplateCustomizer
可以使用bean。所有这些bean都自动注册自动配置 RestTemplateBuilder
,并将应用于使用它构建的任何模板。
这是一个定制器的示例,它为所有主机配置代理的使用,除了 192.168.0.5
:
静态 类 ProxyCustomizer 实现 RestTemplateCustomizer { @Override
public void customize(RestTemplate restTemplate){
HttpHost proxy = new HttpHost(“proxy.example.com”);
HttpClient httpClient = HttpClientBuilder.create()
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy){ @覆盖
公共 HttpHost determineProxy(HttpHost目标,
HttpRequest请求,HttpContext上下文)
抛出 HttpException {
if(target.getHostName()。equals(“192.168.0.5”)){
return null;
}
return super .determineProxy(target,request,context);
} })。建立();
restTemplate.setRequestFactory(
新的 HttpComponentsClientHttpRequestFactory(httpClient));
} }
最后,最极端(也很少使用)的选项是创建自己的 RestTemplateBuilder
bean。这将关闭a的自动配置, RestTemplateBuilder
并将阻止使用任何RestTemplateCustomizer
bean。
34.使用'WebClient'调用REST服务
如果你的类路径上有Spring WebFlux,你也可以选择WebClient
用来调用远程REST服务; 相比之下RestTemplate
,这个客户端具有更多的功能感,并且完全被动。您可以使用构建器创建自己的客户端实例,该构建器WebClient.create()
已经提供了良好的开箱即用体验。请参阅WebClient上的 相关部分。
Spring Boot将为您创建和预配置这样的构建器; 例如,客户端HTTP编解码器将像服务器一样配置(请参阅WebFlux HTTP编解码器自动配置)。
这是一个典型的例子:
@Service
public class MyService { 私有 最终 WebClient webClient; public MyBean(WebClient.Builder webClientBuilder){
this .webClient = webClientBuilder.baseUrl(“http://example.org”)。build();
} public Mono <Details> someRestCall(String name){
return this .webClient.get()。url(“/ {name} / details”,name)
。.retrieve()bodyToMono(详情。类);
} }
34.1 WebClient自定义
WebClient
自定义有三种主要方法,具体取决于您希望自定义应用的广泛程度。
要使任何自定义的范围尽可能窄,请注入自动配置 WebClient.Builder
,然后根据需要调用其方法。WebClient.Builder
实例是有状态的; 对构建器的任何更改都将反映在随后使用它创建的所有客户端中。如果您想使用相同的构建器创建多个客户端,还可以考虑使用克隆构建器WebClient.Builder other = builder.clone();
。
To make an application-wide, additive customization to all WebClient.Builder
instances, you can declare WebClientCustomizer
beans and change the WebClient.Builder
as you would do locally at the point of injection.
Lastly, you can fall back to the original API and just use WebClient.create()
. In that case, no auto-configuration nor WebClientCustomizer
will be applied.
35. Validation
The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (e.g. Hibernate validator) is on the classpath. This allows bean methods to be annotated with javax.validation
constraints on their parameters and/or on their return value. Target classes with such annotated methods need to be annotated with the @Validated
annotation at the type level for their methods to be searched for inline constraint annotations.
For instance, the following service triggers the validation of the first argument, making sure its size is between 8 and 10
@Service
@Validated
public class MyBean { public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code,
Author author) {
...
} }
36. Sending email
The Spring Framework provides an easy abstraction for sending email using the JavaMailSender
interface and Spring Boot provides auto-configuration for it as well as a starter module.
Check the reference documentation for a detailed explanation of how you can use |
如果spring.mail.host
和相关库(由定义的 spring-boot-starter-mail
)可用,JavaMailSender
则创建默认值(如果不存在)。发件人可以通过spring.mail
命名空间中的配置项进一步自定义,MailProperties
有关详细信息,请参阅 。
特别是,某些默认超时值是无限的,您可能希望更改它以避免线程被无响应的邮件服务器阻止:
spring.mail.properties.mail.smtp.connectiontimeout = 5000
spring.mail.properties.mail.smtp.timeout = 3000
spring.mail.properties.mail.smtp.writetimeout = 5000
37.使用JTA的分布式事务
Spring Boot使用Atomikos或Bitronix 嵌入式事务管理器支持跨多个XA资源的分布式JTA事务。部署到合适的Java EE Application Server时,也支持JTA事务。
当检测到JTA环境时,Spring JtaTransactionManager
将用于管理事务。自动配置的JMS,DataSource和JPA bean将升级为支持XA事务。您可以使用标准的Spring惯用语@Transactional
来参与分布式事务。如果您在JTA环境中并仍想使用本地事务,则可以将该spring.jta.enabled
属性设置false
为禁用JTA自动配置。
37.1使用Atomikos事务管理器
Atomikos是一个流行的开源事务管理器,可以嵌入到Spring Boot应用程序中。您可以使用spring-boot-starter-jta-atomikos
Starter引入相应的Atomikos库。Spring Boot将自动配置Atomikos,并确保depends-on
对Spring bean应用适当的设置,以便正确启动和关闭命令。
默认情况下,Atomikos事务日志将写入transaction-logs
应用程序主目录(应用程序jar文件所在的目录)中的目录。您可以通过spring.jta.log-dir
在application.properties
文件中设置属性来自定义此目录。属性启动spring.jta.atomikos.properties
也可用于自定义Atomikos UserTransactionServiceImp
。有关 完整的详细信息,请参阅 AtomikosProperties
Javadoc。
为确保多个事务管理器可以安全地协调相同的资源管理器,必须使用唯一ID配置每个Atomikos实例。默认情况下,此ID是运行Atomikos的计算机的IP地址。要确保生产中的唯一性,应 |
37.2使用Bitronix事务管理器
Bitronix是流行的开源JTA事务管理器实现。您可以使用spring-boot-starter-jta-bitronix
starter将适当的Bitronix依赖项添加到项目中。与Atomikos一样,Spring Boot将自动配置Bitronix并对bean进行后处理,以确保启动和关闭顺序正确。
默认情况下,Bitronix事务日志文件(part1.btm
和part2.btm
)将写入transaction-logs
应用程序主目录中的目录。您可以使用该spring.jta.log-dir
属性自定义此目录。属性启动 spring.jta.bitronix.properties
也绑定到bitronix.tm.Configuration
bean,允许完全自定义。有关 详细信息,请参阅 Bitronix文档。
为确保多个事务管理器可以安全地协调相同的资源管理器,必须为每个Bitronix实例配置唯一ID。默认情况下,此ID是运行Bitronix的计算机的IP地址。要确保生产中的唯一性,应 |
37.3使用Narayana事务管理器
Narayana是JBoss支持的流行的开源JTA事务管理器实现。您可以使用spring-boot-starter-jta-narayana
starter将相应的Narayana依赖项添加到项目中。与Atomikos和Bitronix一样,Spring Boot将自动配置Narayana并对bean进行后处理,以确保启动和关闭顺序正确。
默认情况下,Narayana事务日志将写入transaction-logs
应用程序主目录(应用程序jar文件所在的目录)中的目录。您可以通过spring.jta.log-dir
在application.properties
文件中设置属性来自定义此目录。属性启动spring.jta.narayana.properties
也可用于自定义Narayana配置。有关 完整的详细信息,请参阅 NarayanaProperties
Javadoc。
为确保多个事务管理器可以安全地协调相同的资源管理器,必须使用唯一ID配置每个Narayana实例。默认情况下,此ID设置为 |
37.4使用Java EE托管事务管理器
如果您正在打包春季启动应用程序作为war
或ear
文件,并将其部署到Java EE应用服务器,您可以使用内置的事务管理器应用程序服务器。春天开机时会试图通过寻找共同的JNDI位置(自动配置一个事务管理器java:comp/UserTransaction
, java:comp/TransactionManager
等等)。如果您使用的是应用程序服务器提供的事务服务,通常还需要确保所有资源都由服务器管理并通过JNDI公开。Spring Boot将尝试通过ConnectionFactory
在JNDI路径上查找来自动配置JMS,java:/JmsXA
或者java:/XAConnectionFactory
您可以使用该 spring.datasource.jndi-name
属性 来配置您的DataSource
。
37.5混合XA和非XA JMS连接
使用JTA时,主JMS ConnectionFactory
bean将支持XA并参与分布式事务。在某些情况下,您可能希望使用非XA处理某些JMS消息ConnectionFactory
。例如,您的JMS处理逻辑可能需要比XA超时更长的时间。
如果你想使用非XA,ConnectionFactory
你可以注入 nonXaJmsConnectionFactory
bean而不是@Primary
jmsConnectionFactory
bean。为了保持一致性,jmsConnectionFactory
还使用bean别名提供bean xaJmsConnectionFactory
。
例如:
//注入主(XA感知)ConnectionFactory
@Autowired
私有 ConnectionFactory defaultConnectionFactory; //注入XA感知ConnectionFactory(使用别名并注入与上面相同的内容)
@Autowired
@Qualifier(“xaJmsConnectionFactory”)
private ConnectionFactory xaConnectionFactory; //注入非XA感知的ConnectionFactory
@Autowired
@Qualifier(“nonXaJmsConnectionFactory”)
私有 ConnectionFactory nonXaConnectionFactory;
37.6支持替代嵌入式事务管理器
该XAConnectionFactoryWrapper
和XADataSourceWrapper
接口可用于支持替代嵌入式事务经理。接口负责包装XAConnectionFactory
和XADataSource
bean,并将它们作为常规ConnectionFactory
和DataSource
bean 公开,它们将透明地注册到分布式事务中。只要您有一个JtaTransactionManager
bean和在您的域中注册的相应XA包装bean,DataSource和JMS自动配置将使用JTA变体ApplicationContext
。
该BitronixXAConnectionFactoryWrapper 和BitronixXADataSourceWrapper 提供了如何编写XA包装很好的例子。
38. Hazelcast
如果Hazelcast位于类路径上并找到合适的配置,Spring Boot将自动配置HazelcastInstance
您可以在应用程序中注入的配置。
You can define a com.hazelcast.config.Config
bean and we’ll use that. If your configuration defines an instance name, we’ll try to locate an existing instance rather than creating a new one.
You could also specify the hazelcast.xml
configuration file to use via configuration:
spring.hazelcast.config=classpath:config/my-hazelcast.xml
Otherwise, Spring Boot tries to find the Hazelcast configuration from the default locations, that is hazelcast.xml
in the working directory or at the root of the classpath. We also check if the hazelcast.config
system property is set. Check the Hazelcast documentation for more details.
If hazelcast-client
is present on the classpath, Spring Boot will first attempt to create a client with similar rules as above, that is:
- The presence of a
com.hazelcast.client.config.ClientConfig
bean - A configuration file defined by the
spring.hazelcast.config
property - The presence of the
hazelcast.client.config
system property - A
hazelcast-client.xml
in the working directory or at the root of the classpath
Spring Boot also has an explicit caching support for Hazelcast. The |
39. Quartz Scheduler
Spring Boot offers several conveniences for working with the Quartz scheduler, including the spring-boot-starter-quartz
‘Starter’. If Quartz is available, a Scheduler
will be auto-configured (via the SchedulerFactoryBean
abstraction).
Beans of the following types will be automatically picked up and associated with the the Scheduler
:
-
JobDetail
: defines a particular Job.JobDetail
instance can easily be built with theJobBuilder
API Calendar
-
Trigger
:定义何时触发特定作业
默认情况下,JobStore
将使用内存。但是,如果DataSource
应用程序中有bean,并且相应地spring.quartz.job-store-type
配置了 属性,则可以配置基于JDBC的存储:
spring.quartz.job-store-type = jdbc
使用jdbc存储时,可以在启动时初始化架构:
spring.quartz.jdbc.initialize-schema = true
默认情况下会检测数据库,并使用Quartz库提供的标准脚本进行初始化。也可以使用该 |
可以使用Quartz配置属性(请参阅参考资料spring.quartz.properties.*
)和SchedulerFactoryBeanCustomizer
允许编程SchedulerFactoryBean
自定义的bean来自定义Quartz Scheduler配置 。
Job可以定义setter以注入数据映射属性。也可以以类似的方式注入常规豆类:
公共 类 SampleJob 扩展了 QuartzJobBean { private MyService myService;
私有字符串名称; //注入“MyService”bean
public void setMyService(MyService myService){...} //注入“name”作业数据属性
public void setName(String name){...} @Override
protected void executeInternal(JobExecutionContext context)
抛出 JobExecutionException {
...
} }
40.春季整合
Spring Boot提供了一些使用Spring Integration的便利,包括spring-boot-starter-integration
'Starter'。Spring Integration提供了消息传递以及其他传输(如HTTP,TCP等)的抽象。如果类路径上有Spring Integration,它将通过@EnableIntegration
注释进行初始化 。
Spring Boot还将配置由于存在其他Spring Integration模块而触发的一些功能。如果'spring-integration-jmx'
也在类路径上,则将通过JMX发布消息处理统计信息。如果 'spring-integration-jdbc'
可用,则可以在启动时创建默认数据库模式:
spring.integration.jdbc.initializer.enabled = true
有关 详细信息,请参阅 IntegrationAutoConfiguration
和IntegrationProperties
类。
41.春季会议
Spring Boot provides Spring Session auto-configuration for a wide range of stores:
- JDBC
- Redis
- Hazelcast
- HashMap
If Spring Session is available, you must choose the StoreType
that you wish to use to store the sessions. For instance to use JDBC as backend store, you’d configure your application as follows:
spring.session.store-type=jdbc
You can disable Spring Session by setting the |
Each store has specific additional settings. For instance it is possible to customize the name of the table for the jdbc store:
spring.session.jdbc.table-name=SESSIONS
42. Monitoring and management over JMX
Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default Spring Boot will create an MBeanServer
with bean id ‘mbeanServer’ and expose any of your beans that are annotated with Spring JMX annotations (@ManagedResource
, @ManagedAttribute
, @ManagedOperation
).
See the JmxAutoConfiguration
class for more details.
43. Testing
Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules; spring-boot-test
contains core items, and spring-boot-test-autoconfigure
supports auto-configuration for tests.
Most developers will just use the spring-boot-starter-test
‘Starter’ which imports both Spring Boot test modules as well has JUnit, AssertJ, Hamcrest and a number of other useful libraries.
43.1 Test scope dependencies
If you use the spring-boot-starter-test
‘Starter’ (in the test
scope
), you will find the following provided libraries:
- JUnit — The de-facto standard for unit testing Java applications.
- Spring Test & Spring Boot Test — Utilities and integration test support for Spring Boot applications.
- AssertJ — A fluent assertion library.
- Hamcrest — A library of matcher objects (also known as constraints or predicates).
- Mockito — A Java mocking framework.
- JSONassert — An assertion library for JSON.
- JsonPath — XPath for JSON.
These are common libraries that we generally find useful when writing tests. You are free to add additional test dependencies of your own if these don’t suit your needs.
43.2 Testing Spring applications
One of the major advantages of dependency injection is that it should make your code easier to unit test. You can simply instantiate objects using the new
operator without even involving Spring. You can also use mock objects instead of real dependencies.
Often you need to move beyond ‘unit testing’ and start ‘integration testing’ (with a Spring ApplicationContext
actually involved in the process). It’s useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure.
The Spring Framework includes a dedicated test module for just such integration testing. You can declare a dependency directly to org.springframework:spring-test
or use the spring-boot-starter-test
‘Starter’ to pull it in transitively.
If you have not used the spring-test
module before you should start by reading the relevant section of the Spring Framework reference documentation.
43.3 Testing Spring Boot applications
A Spring Boot application is just a Spring ApplicationContext
, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. One thing to watch out for though is that the external properties, logging and other features of Spring Boot are only installed in the context by default if you use SpringApplication
to create it.
Spring Boot provides a @SpringBootTest
annotation which can be used as an alternative to the standard spring-test
@ContextConfiguration
annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext
used in your tests via SpringApplication
.
You can use the webEnvironment
attribute of @SpringBootTest
to further refine how your tests will run:
-
MOCK
— Loads aWebApplicationContext
and provides a mock servlet environment. Embedded servlet containers are not started when using this annotation. If servlet APIs are not on your classpath this mode will transparently fallback to creating a regular non-webApplicationContext
. Can be used in conjunction with@AutoConfigureMockMvc
forMockMvc
-based testing of your application. -
RANDOM_PORT
— Loads anServletWebServerApplicationContext
and provides a real servlet environment. Embedded servlet containers are started and listening on a random port. -
DEFINED_PORT
— Loads anServletWebServerApplicationContext
and provides a real servlet environment. Embedded servlet containers are started and listening on a defined port (i.e from yourapplication.properties
or on the default port8080
). -
NONE
- 加载ApplicationContext
使用SpringApplication
但不提供 任何 servlet环境(模拟或其他)。
如果您的测试是 |
除了 |
不要忘记也添加 |
43.3.1检测测试配置
如果您熟悉Spring Test Framework,那么您可能习惯使用 @ContextConfiguration(classes=…)
它来指定@Configuration
要加载的Spring 。或者,您可能经常@Configuration
在测试中使用嵌套类。
在测试Spring Boot应用程序时,通常不需要这样做。@*Test
只要您没有明确定义,Spring Boot的注释就会自动搜索您的主要配置。
搜索算法从包含测试的包开始工作,直到找到一个 @SpringBootApplication
或带@SpringBootConfiguration
注释的类。只要您 以合理的方式构建代码,通常就会找到主要配置。
如果要自定义主要配置,可以使用嵌套 @TestConfiguration
类。与@Configuration
将用于代替应用程序主要配置的嵌套@TestConfiguration
类不同,除了应用程序的主要配置之外,还将使用嵌套类。
Spring的测试框架将在测试之间缓存应用程序上下文。因此,只要您的测试共享相同的配置(无论它如何被发现),加载上下文的潜在耗时过程将只发生一次。 |
43.3.2排除测试配置
如果您的应用程序使用组件扫描,例如,如果您使用 @SpringBootApplication
或@ComponentScan
,您可能会发现仅为特定测试创建的*配置类偶然会在任何地方被拾取。
正如我们在前面看到的, @TestConfiguration
可以在一个内部类的测试的用于定制的主配置。放置在*类时,@TestConfiguration
表示src/test/java
不应通过扫描拾取类。然后,您可以在需要的位置显式导入该类:
@RunWith(SpringRunner.class)
@SpringBootTest @Import
(MyTestsConfiguration.class)
public class MyTests { @Test
public void exampleTest(){
...
} }
如果您直接使用 |
43.3.3使用随机端口
If you need to start a full running server for tests, we recommend that you use random ports. If you use @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
an available port will be picked at random each time your test runs.
The @LocalServerPort
annotation can be used to inject the actual port used into your test. For convenience, tests that need to make REST calls to the started server can additionally @Autowire
a TestRestTemplate
which will resolve relative links to the running server.
import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomPortExampleTests { @Autowired
private TestRestTemplate restTemplate; @Test
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World");
} }
43.3.4 Mocking and spying beans
It’s sometimes necessary to mock certain components within your application context when running tests. For example, you may have a facade over some remote service that’s unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment.
Spring Boot includes a @MockBean
annotation that can be used to define a Mockito mock for a bean inside your ApplicationContext
. You can use the annotation to add new beans, or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on @Configuration
classes and fields. When used on a field, the instance of the created mock will also be injected. Mock beans are automatically reset after each test method.
This feature is automatically enabled as long as your test uses one of Spring Boot’s test annotations (i.e. @TestExecutionListeners(MockitoTestExecutionListener.class) |
Here’s a typical example where we replace an existing RemoteService
bean with a mock implementation:
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.context.*;
import org.springframework.boot.test.mock.mockito.*;
import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*; @RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests { @MockBean
private RemoteService remoteService; @Autowired
private Reverser reverser; @Test
public void exampleTest() {
// RemoteService has been injected into the reverser bean
given(this.remoteService.someCall()).willReturn("mock");
String reverse = reverser.reverseSomeCall();
assertThat(reverse).isEqualTo("kcom");
} }
Additionally you can also use @SpyBean
to wrap any existing bean with a Mockito spy
. See the Javadoc for full details.
43.3.5 Auto-configured tests
Spring Boot’s auto-configuration system works well for applications, but can sometimes be a little too much for tests. It’s often helpful to load only the parts of the configuration that are required to test a ‘slice’ of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you don’t want to involve database calls in those tests; or you might be wanting to test JPA entities, and you’re not interested in web layer when those tests run.
The spring-boot-test-autoconfigure
module includes a number of annotations that can be used to automatically configure such ‘slices’. Each of them works in a similar way, providing a @…Test
annotation that loads the ApplicationContext
and one or more @AutoConfigure…
annotations that can be used to customize auto-configuration settings.
Each slice loads a very restricted set of auto-configuration classes. If you need to exclude one of them, most |
It’s also possible to use the |
43.3.6 Auto-configured JSON tests
To test that Object JSON serialization and deserialization is working as expected you can use the @JsonTest
annotation. @JsonTest
will auto-configure Jackson ObjectMapper
, any @JsonComponent
beans and any Jackson Modules
. It also configures Gson
if you happen to be using that instead of, or as well as, Jackson. If you need to configure elements of the auto-configuration you can use the @AutoConfigureJsonTesters
annotation.
Spring Boot includes AssertJ based helpers that work with the JSONassert and JsonPath libraries to check that JSON is as expected. The JacksonTester
, GsonTester
and BasicJsonTester
classes can be used for Jackson, Gson and Strings respectively. Any helper fields on the test class can be @Autowired
when using @JsonTest
.
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.autoconfigure.json.*;
import org.springframework.boot.test.context.*;
import org.springframework.boot.test.json.*;
import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*; @RunWith(SpringRunner.class)
@JsonTest
public class MyJsonTests { @Autowired
private JacksonTester<VehicleDetails> json; @Test
public void testSerialize() throws Exception {
VehicleDetails details = new VehicleDetails("Honda", "Civic");
// Assert against a `.json` file in the same package as the test
assertThat(this.json.write(details)).isEqualToJson("expected.json");
// Or use JSON path based assertions
assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");
assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make")
.isEqualTo("Honda");
} @Test
public void testDeserialize() throws Exception {
String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
assertThat(this.json.parse(content))
.isEqualTo(new VehicleDetails("Ford", "Focus"));
assertThat(this .json.parseObject(content).getMake())。isEqualTo(“Ford”);
} }
JSON帮助程序类也可以直接在标准单元测试中使用。如果您不使用,只需在 |
@JsonTest
可以 在附录中找到启用的自动配置列表。
43.3.7自动配置的Spring MVC测试
要测试Spring MVC控制器是否正常工作,您可以使用@WebMvcTest
注释。@WebMvcTest
将自动配置Spring MVC的基础设施和限制扫描豆@Controller
,@ControllerAdvice
,@JsonComponent
,Filter
, WebMvcConfigurer
和HandlerMethodArgumentResolver
。@Component
使用此批注时,不会扫描常规bean。
通常@WebMvcTest
将限于单个控制器并与其结合使用 @MockBean
,以便为所需的协作者提供模拟实现。
@WebMvcTest
还自动配置MockMvc
。Mock MVC提供了一种快速测试MVC控制器的强大方法,无需启动完整的HTTP服务器。
您也可以通过使用注释来 |
import org.junit。*;
import org.junit.runner。*;
import org.springframework.beans.factory.annotation。*;
import org.springframework.boot.test.autoconfigure.web.servlet。*;
import org.springframework.boot.test.mock.mockito。*; import static org.assertj.core.api.Assertions。*;
import static org.mockito.BDDMockito。*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders。*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers。*; @RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class MyControllerTests { @Autowired
私人 MockMvc mvc; @MockBean
private UserVehicleService userVehicleService; @Test
public void testExample()抛出异常{
给定(此 .userVehicleService.getVehicleDetails(“sboot”))
.willReturn(new VehicleDetails(“Honda”,“Civic”));
这个 .mvc.perform(get(“/ sboot / vehicle”)。accept(MediaType.TEXT_PLAIN))
.andExpect(status()。isOk())。andExpect(content()。string(“Honda Civic”));
} }
如果需要配置自动配置的元素(例如,应该应用servlet过滤器时),则可以使用 |
如果您使用HtmlUnit或Selenium,自动配置还将提供HTMLUnit WebClient
bean和/或WebDriver
bean。这是一个使用HtmlUnit的示例:
import com.gargoylesoftware.htmlunit。*;
import org.junit。*;
import org.junit.runner。*;
import org.springframework.beans.factory.annotation。*;
import org.springframework.boot.test.autoconfigure.web.servlet。*;
import org.springframework.boot.test.mock.mockito。*; import static org.assertj.core.api.Assertions。*;
import static org.mockito.BDDMockito。*; @RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class MyHtmlUnitTests { @Autowired
私有 WebClient webClient; @MockBean
private UserVehicleService userVehicleService; @Test
public void testExample()抛出异常{
给定(此 .userVehicleService.getVehicleDetails(“sboot”))
.willReturn(new VehicleDetails(“Honda”,“Civic”));
HtmlPage page = this .webClient.getPage(“/sboot/vehicle.html”);
assertThat(page.getBody()。getTextContent())。isEqualTo(“Honda Civic”);
} }
默认情况下,Spring Boot会将 |
@WebMvcTest
可以 在附录中找到启用的自动配置列表。
43.3.8自动配置Spring WebFlux测试
要测试Spring WebFlux控制器是否正常工作,您可以使用@WebFluxTest
注释。@WebFluxTest
将自动配置Spring WebFlux基础设施和限制扫描豆@Controller
,@ControllerAdvice
,@JsonComponent
,和 WebFluxConfigurer
。@Component
使用此批注时,不会扫描常规bean。
通常@WebFluxTest
将限于单个控制器并与其结合使用 @MockBean
,以便为所需的协作者提供模拟实现。
@WebFluxTest
还有自动配置WebTestClient
,这提供了一种快速测试WebFlux控制器的强大方法,无需启动完整的HTTP服务器。
您也可以通过使用注释来 |
import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class)
@WebFluxTest(UserVehicleController.class)
public class MyControllerTests { @Autowired
私有 WebTestClient webClient; @MockBean
private UserVehicleService userVehicleService; @Test
public void testExample()抛出异常{
给定(此 .userVehicleService.getVehicleDetails(“sboot”))
.willReturn(new VehicleDetails(“Honda”,“Civic”));
这个 .webClient.get()。uri(“/ sboot / vehicle”)。accept(MediaType.TEXT_PLAIN)
。交换()
.expectStatus()。ISOK()
.expectBody(String .class).isEqualTo(“Honda Civic”);
} }
A list of the auto-configuration that is enabled by @WebFluxTest
can be found in the appendix.
43.3.9 Auto-configured Data JPA tests
@DataJpaTest
can be used if you want to test JPA applications. By default it will configure an in-memory embedded database, scan for @Entity
classes and configure Spring Data JPA repositories. Regular @Component
beans will not be loaded into the ApplicationContext
.
Data JPA tests are transactional and rollback at the end of each test by default, see the relevant section in the Spring Reference Documentation for more details. If that’s not what you want, you can disable transaction management for a test or for the whole class as follows:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class)
@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ExampleNonTransactionalTests { }
数据JPA测试也可以注入一个 TestEntityManager
bean,它提供了EntityManager
专门为测试设计的标准JPA的替代方法。如果你想在TestEntityManager
外面使用@DataJpaTests
你也可以使用@AutoConfigureTestEntityManager
注释。JdbcTemplate
如果您需要,也可以使用A.
import org.junit。*;
import org.junit.runner。*;
import org.springframework.boot.test.autoconfigure.orm.jpa。*; import static org.assertj.core.api.Assertions。*; @RunWith(SpringRunner.class)
@DataJpaTest
public class ExampleRepositoryTests { @Autowired
私有 TestEntityManager entityManager; @Autowired
私有 UserRepository存储库; @Test
public void testExample()抛出 Exception {
this .entityManager.persist( new User( “sboot”, “1234”));
User user = this .repository.findByUsername(“sboot”);
assertThat(user.getUsername())。isEqualTo(“sboot”);
assertThat(user.getVin())。isEqualTo(“1234”);
} }
内存中的嵌入式数据库通常可以很好地用于测试,因为它们很快并且不需要任何开发人员安装。但是,如果您更喜欢对真实数据库运行测试,则可以使用@AutoConfigureTestDatabase
注释:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class ExampleRepositoryTests { // ... }
@DataJpaTest
可以 在附录中找到启用的自动配置列表。
43.3.10自动配置的JDBC测试
@JdbcTest
类似于@DataJpaTest
纯jdbc相关测试。默认情况下,它还将配置内存中的嵌入式数据库和JdbcTemplate
。常规 @Component
bean不会被加载到ApplicationContext
。
默认情况下,JDBC测试在每个测试结束时都是事务性和回滚,有关详细信息,请参阅Spring Reference Documentation中的相关部分。如果这不是您想要的,您可以为测试或整个类禁用事务管理,如下所示:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class)
@JdbcTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ExampleNonTransactionalTests { }
如果您希望测试针对真实数据库运行,则可以使用与@AutoConfigureTestDatabase
注释相同的方式使用 注释DataJpaTest
。
@JdbcTest
可以 在附录中找到启用的自动配置列表。
43.3.11自动配置的jOOQ测试
@JooqTest
可以以与@JdbcTest
jOOQ相关的测试类似的方式使用。由于jOOQ严重依赖于与数据库模式相对应的基于Java的模式,因此DataSource
将使用现有模式。如果要通过内存数据库替换它,可以使用@AutoconfigureTestDatabase
覆盖这些设置。
@JooqTest
将配置一个DSLContext
。常规@Component
bean不会加载到ApplicationContext
:
import org.jooq.DSLContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.jooq.JooqTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@JooqTest
public class ExampleJooqTests { @Autowired
private DSLContext dslContext;
}
默认情况下,JOOQ测试在每个测试结束时都是事务性和回滚。如果这不是您想要的,您可以禁用测试或整个测试类的事务管理,如上例所示。
@JooqTest
可以 在附录中找到启用的自动配置列表。
43.3.12自动配置的数据MongoDB测试
@DataMongoTest
如果要测试MongoDB应用程序,可以使用它。默认情况下,它将配置内存中嵌入式MongoDB(如果可用),配置MongoTemplate
,扫描@Document
类并配置Spring Data MongoDB存储库。常规 @Component
bean不会加载到ApplicationContext
:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@DataMongoTest
public class ExampleDataMongoTests { @Autowired
private MongoTemplate mongoTemplate; //
}
In-memory embedded MongoDB generally works well for tests since it is fast and doesn’t require any developer installation. If, however, you prefer to run tests against a real MongoDB server you should exclude the embedded MongoDB auto-configuration:
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
public class ExampleDataMongoNonEmbeddedTests { }
A list of the auto-configuration that is enabled by @DataMongoTest
can be found in the appendix.
43.3.13 Auto-configured Data Neo4j tests
@DataNeo4jTest
can be used if you want to test Neo4j applications. By default, it will use an in-memory embedded Neo4j (if the embedded driver is available), scan for@NodeEntity
classes and configure Spring Data Neo4j repositories. Regular @Component
beans will not be loaded into the ApplicationContext
:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@DataNeo4jTest
public class ExampleDataNeo4jTests { @Autowired
private YourRepository repository; //
}
Data Neo4j tests are transactional and rollback at the end of each test by default, see the relevant section in the Spring Reference Documentation for more details. If that’s not what you want, you can disable transaction management for a test or for the whole class as follows:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class)
@DataNeo4jTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ExampleNonTransactionalTests { }
A list of the auto-configuration that is enabled by @DataNeo4jTest
can be found in the appendix.
43.3.14 Auto-configured Data Redis tests
@DataRedisTest
can be used if you want to test Redis applications. By default, it will scan for @RedisHash
classes and configure Spring Data Redis repositories. Regular @Component
beans will not be loaded into the ApplicationContext
:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@DataRedisTest
public class ExampleDataRedisTests { @Autowired
private YourRepository repository; //
}
@DataRedisTest
可以 在附录中找到启用的自动配置列表。
43.3.15自动配置的数据LDAP测试
@DataLdapTest
如果要测试LDAP应用程序,可以使用它。默认情况下,它将配置内存中嵌入式LDAP(如果可用),a LdapTemplate
,扫描@Entry
类并配置Spring Data LDAP存储库。常规@Component
bean不会加载到ApplicationContext
:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@DataLdapTest
public class ExampleDataLdapTests { @Autowired
private LdapTemplate ldapTemplate; //
}
内存中嵌入式LDAP通常适用于测试,因为它速度快,不需要任何开发人员安装。但是,如果您希望针对真实LDAP服务器运行测试,则应排除嵌入式LDAP自动配置:
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration;
import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@DataLdapTest(excludeAutoConfiguration = EmbeddedLdapAutoConfiguration.class)
public class ExampleDataLdapNonEmbeddedTests { }
@DataLdapTest
可以 在附录中找到启用的自动配置列表。
43.3.16自动配置的REST客户端
的@RestClientTest
,如果你想测试REST客户注释可以使用。默认情况下,它将自动配置Jackson和GSON支持,配置RestTemplateBuilder
并添加支持MockRestServiceServer
。应使用value
或components
属性指定要测试的特定bean @RestClientTest
:
@RunWith(SpringRunner.class)
@RestClientTest(RemoteVehicleDetailsService.class)
public class ExampleRestClientTest { @Autowired
私有 RemoteVehicleDetailsService服务; @Autowired
私有 MockRestServiceServer服务器; @Test
public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails()
抛出异常{
this .server.expect(requestTo( “/ greet / details”))
.andRespond(withSuccess(“hello”,MediaType.TEXT_PLAIN));
String greeting = this .service.callRestService();
断言(问候).isEqualTo(“你好”);
} }
A list of the auto-configuration that is enabled by @RestClientTest
can be found in the appendix.
43.3.17 Auto-configured Spring REST Docs tests
The @AutoConfigureRestDocs
annotation can be used if you want to use Spring REST Docs in your tests. It will automatically configure MockMvc
to use Spring REST Docs and remove the need for Spring REST Docs' JUnit rule.
import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@AutoConfigureRestDocs
public class UserDocumentationTests { @Autowired
private MockMvc mvc; @Test
public void listUsers() throws Exception {
this.mvc.perform(get("/users").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andDo(document("list-users"));
} }
@AutoConfigureRestDocs
can be used to override the default output directory (target/generated-snippets
if you are using Maven or build/generated-snippets
if you are using Gradle). It can also be used to configure the host, scheme, and port that will appear in any documented URIs. If you require more control over Spring REST Docs' configuration a RestDocsMockMvcConfigurationCustomizer
bean can be used:
@TestConfiguration
static class CustomizationConfiguration
implements RestDocsMockMvcConfigurationCustomizer { @Override
public void customize(MockMvcRestDocumentationConfigurer configurer) {
configurer.snippets().withTemplateFormat(TemplateFormats.markdown());
} }
If you want to make use of Spring REST Docs' support for a parameterized output directory, you can create a RestDocumentationResultHandler
bean. The auto-configuration will call alwaysDo
with this result handler, thereby causing each MockMvc
call to automatically generate the default snippets:
@TestConfiguration
static class ResultHandlerConfiguration { @Bean
public RestDocumentationResultHandler restDocumentation() {
return MockMvcRestDocumentation.document("{method-name}");
} }
43.3.18 Using Spock to test Spring Boot applications
If you wish to use Spock to test a Spring Boot application you should add a dependency on Spock’s spock-spring
module to your application’s build. spock-spring
integrates Spring’s test framework into Spock. It is recommended that you use Spock 1.1 or later to benefit from a number of recent improvements to Spock’s Spring Framework and Spring Boot integration. Please refer to the documentation for Spock’s Spring module for further details.
43.4 Test utilities
A few test utility classes are packaged as part of spring-boot
that are generally useful when testing your application.
43.4.1 ConfigFileApplicationContextInitializer
ConfigFileApplicationContextInitializer
is an ApplicationContextInitializer
that can apply to your tests to load Spring Boot application.properties
files. You can use this when you don’t need the full features provided by @SpringBootTest
.
@ContextConfiguration(classes = Config.class,
initializers = ConfigFileApplicationContextInitializer.class)
Using |
43.4.2 EnvironmentTestUtils
EnvironmentTestUtils
allows you to quickly add properties to a ConfigurableEnvironment
or ConfigurableApplicationContext
. Simply call it withkey=value
strings:
EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot");
43.4.3 OutputCapture
OutputCapture
is a JUnit Rule
that you can use to capture System.out
and System.err
output. Simply declare the capture as a @Rule
then use toString()
for assertions:
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.test.rule.OutputCapture; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; public class MyTest { @Rule
public OutputCapture capture = new OutputCapture(); @Test
public void testName() throws Exception {
System.out.println("Hello World!");
assertThat(capture.toString(), containsString("World"));
} }
43.4.4 TestRestTemplate
TestRestTemplate
is a convenience alternative to Spring’s RestTemplate
that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case the template will behave in a test-friendly way by not throwing exceptions on server-side errors. It is recommended, but not mandatory, to use Apache HTTP Client (version 4.3.2 or better), and if you have that on your classpath the TestRestTemplate
will respond by configuring the client appropriately. If you do use Apache’s HTTP client some additional test-friendly features will be enabled:
- Redirects will not be followed (so you can assert the response location)
- Cookies will be ignored (so the template is stateless)
TestRestTemplate
can be instantiated directly in your integration tests:
public class MyTest { private TestRestTemplate template = new TestRestTemplate(); @Test
public void testRequest() throws Exception {
HttpHeaders headers = template.getForEntity("http://myhost.com/example", String.class).getHeaders();
assertThat(headers.getLocation().toString(), containsString("myotherhost"));
} }
Alternatively, if you are using the @SpringBootTest
annotation with WebEnvironment.RANDOM_PORT
or WebEnvironment.DEFINED_PORT
, you can just inject a fully configured TestRestTemplate
and start using it. If necessary, additional customizations can be applied via the RestTemplateBuilder
bean. Any URLs that do not specify a host and port will automatically connect to the embedded server:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest { @Autowired
private TestRestTemplate template; @Test
public void testRequest() throws Exception {
HttpHeaders headers = template.getForEntity("/example", String.class).getHeaders();
assertThat(headers.getLocation().toString(), containsString("myotherhost"));
} @TestConfiguration
static class Config { @Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.additionalMessageConverters(...)
.customizers(...);
} } }
44. WebSockets
Spring Boot provides WebSockets auto-configuration for embedded Tomcat (8 and 7), Jetty 9 and Undertow. If you’re deploying a war file to a standalone container, Spring Boot assumes that the container will be responsible for the configuration of its WebSocket support.
Spring Framework provides rich WebSocket support that can be easily accessed via the spring-boot-starter-websocket
module.
45. Web Services
Spring Boot provides Web Services auto-configuration so that all is required is defining your Endpoints
.
The Spring Web Services features can be easily accessed via the spring-boot-starter-webservices
module.
46. Creating your own auto-configuration
If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot.
自动配置可以与“启动器”相关联,该“启动器”提供自动配置代码以及您将使用它的典型库。我们将首先介绍构建自己的自动配置所需的知识,然后我们将继续介绍创建自定义启动器所需的 典型步骤。
可以使用演示项目 来展示如何逐步创建启动器。 |
46.1了解自动配置的bean
在引擎盖下,自动配置使用标准@Configuration
类实现。其他@Conditional
注释用于约束何时应用自动配置。通常自动配置类使用@ConditionalOnClass
和@ConditionalOnMissingBean
注释。这可确保自动配置仅在找到相关类时以及未声明自己的类时应用@Configuration
。
您可以浏览源代码spring-boot-autoconfigure
以查看@Configuration
我们提供的类(请参阅 META-INF/spring.factories
文件)。
46.2查找自动配置候选项
Spring Boot会检查META-INF/spring.factories
已发布jar中是否存在文件。该文件应列出EnableAutoConfiguration
密钥下的配置类 。
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\
com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration
如果需要按特定顺序应用配置,则可以使用 @AutoConfigureAfter
或 @AutoConfigureBefore
注释。例如,如果您提供特定于Web的配置,则可能需要在之后应用您的类 WebMvcAutoConfiguration
。
如果您想订购某些不应该彼此直接了解的自动配置,您也可以使用@AutoconfigureOrder
。该注释与常规注释具有相同的语义,@Order
但为自动配置类提供了专用顺序。
自动配置,必须加载的方式只。确保它们在特定的包空间中定义,并且它们永远不是组件扫描的目标。 |
46.3条件注释
您几乎总是希望@Conditional
在自动配置类中包含一个或多个注释。这@ConditionalOnMissingBean
是一个常见的示例,用于允许开发人员“覆盖”自动配置,如果他们对您的默认值不满意。
Spring Boot包含许多@Conditional
注释,您可以通过注释@Configuration
类或单个@Bean
方法在自己的代码中重用这些注释。
46.3.1类别条件
The @ConditionalOnClass
and @ConditionalOnMissingClass
annotations allows configuration to be included based on the presence or absence of specific classes. Due to the fact that annotation metadata is parsed using ASM you can actually use the value
attribute to refer to the real class, even though that class might not actually appear on the running application classpath. You can also use the name
attribute if you prefer to specify the class name using a String
value.
If you are using |
46.3.2 Bean conditions
The @ConditionalOnBean
and @ConditionalOnMissingBean
annotations allow a bean to be included based on the presence or absence of specific beans. You can use the value
attribute to specify beans by type, or name
to specify beans by name. The search
attribute allows you to limit the ApplicationContext
hierarchy that should be considered when searching for beans.
When placed on a @Bean
method, the target type defaults to the return type of the method, for instance:
@Configuration
public class MyAutoConfiguration { @Bean
@ConditionalOnMissingBean
public MyService myService() { ... } }
In the example above, the myService
bean is going to be created if no bean of type MyService
is already contained in the ApplicationContext
.
You need to be very careful about the order that bean definitions are added as these conditions are evaluated based on what has been processed so far. For this reason, we recommend only using |
|
46.3.3 Property conditions
The @ConditionalOnProperty
annotation allows configuration to be included based on a Spring Environment property. Use the prefix
and name
attributes to specify the property that should be checked. By default any property that exists and is not equal to false
will be matched. You can also create more advanced checks using the havingValue
and matchIfMissing
attributes.
46.3.4 Resource conditions
The @ConditionalOnResource
annotation allows configuration to be included only when a specific resource is present. Resources can be specified using the usual Spring conventions, for example, file:/home/user/test.dat
.
46.3.5 Web application conditions
The @ConditionalOnWebApplication
and @ConditionalOnNotWebApplication
annotations allow configuration to be included depending on whether the application is a 'web application'. A web application is any application that is using a Spring WebApplicationContext
, defines a session
scope or has a StandardServletEnvironment
.
46.3.6 SpEL expression conditions
The @ConditionalOnExpression
annotation allows configuration to be included based on the result of a SpEL expression.
46.4 Creating your own starter
A full Spring Boot starter for a library may contain the following components:
- The
autoconfigure
module that contains the auto-configuration code. - 该
starter
模块提供对autoconfigure模块以及库的依赖关系以及通常有用的任何其他依赖项。简而言之,添加启动器应该足以开始使用该库。
如果您不需要将这两个问题分开,则可以将自动配置代码和依赖关系管理组合在一个模块中。 |
46.4.1命名
请确保为您的启动器提供适当的命名空间。spring-boot
即使您使用的是其他Maven groupId,也不要使用它来启动模块名称。我们可能会为您将来自动配置的内容提供官方支持。
这是一条经验法则。假设您正在为“acme”创建启动器,将自动配置模块acme-spring-boot-autoconfigure
和启动器 命名为acme-spring-boot-starter
。如果您只有一个模块将两者合并,请使用 acme-spring-boot-starter
。
此外,如果您的启动器提供配置密钥,请为它们使用适当的命名空间。特别是,不包括你在春天开机使用的命名空间(如按键 server
,management
,spring
,等)。这些是“我们的”,我们可能会在未来改进/修改它们,这样可能会破坏你的东西。
确保 触发元数据生成,以便为您的密钥提供IDE帮助。您可能希望查看生成的元数据(META-INF/spring-configuration-metadata.json
)以确保正确记录您的密钥。
46.4.2自动配置模块
autoconfigure模块包含开始使用库所需的所有内容。它还可以包含配置键定义(@ConfigurationProperties
)和任何可用于进一步自定义组件初始化方式的回调接口。
您应该将库的依赖项标记为可选,以便您可以更轻松地在项目中包含autoconfigure模块。如果你这样做,将不提供库,默认情况下Spring Boot将退回。 |
46.4.3启动器模块
真的,起动器是一个空罐子。它的唯一目的是为库提供必要的依赖关系; 将其视为开始所需要的观点。
不要对添加启动器的项目做出假设。如果您自动配置的库通常需要其他启动器,请同时提及它们。如果可选依赖项的数量很高,则提供一组适当的默认依赖项可能很难,因为您应该避免为库的典型用法带来不必要的依赖项。
47.接下来要读什么
如果您想了解本节中讨论的任何类的更多信息,可以查看Spring Boot API文档,也可以直接浏览 源代码。如果您有具体问题,请查看 操作方法部分。
If you are comfortable with Spring Boot’s core features, you can carry on and read about production-ready features.
Part V. Spring Boot Actuator: Production-ready features
Spring Boot includes a number of additional features to help you monitor and manage your application when it’s pushed to production. You can choose to manage and monitor your application using HTTP endpoints or with JMX. Auditing, health and metrics gathering can be automatically applied to your application.
Actuator HTTP endpoints are only available with a Spring MVC-based application. In particular, it will not work with Jersey unless you enable Spring MVC as well.
48. Enabling production-ready features
The spring-boot-actuator
module provides all of Spring Boot’s production-ready features. The simplest way to enable the features is to add a dependency to the spring-boot-starter-actuator
‘Starter’.
Definition of Actuator
An actuator is a manufacturing term, referring to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change.
To add the actuator to a Maven based project, add the following ‘Starter’ dependency:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
For Gradle, use the declaration:
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}
49. Endpoints
Actuator endpoints allow you to monitor and interact with your application. Spring Boot includes a number of built-in endpoints and you can also add your own. For example the health
endpoint provides basic application health information.
The way that endpoints are exposed will depend on the type of technology that you choose. Most applications choose HTTP monitoring, where the ID of the endpoint along with a prefix of /application
is mapped to a URL. For example, by default, the health
endpoint will be mapped to /application/health
.
The following technology agnostic endpoints are available:
ID | Description | Sensitive Default |
---|---|---|
|
Provides a hypermedia-based “discovery page” for the other endpoints. Requires Spring HATEOAS to be on the classpath. |
true |
|
Exposes audit events information for the current application. |
true |
|
Displays an auto-configuration report showing all auto-configuration candidates and the reason why they ‘were’ or ‘were not’ applied. |
true |
|
Displays a complete list of all the Spring beans in your application. |
true |
|
Displays a collated list of all |
true |
|
Performs a thread dump. |
true |
|
Exposes properties from Spring’s |
true |
|
Shows any Flyway database migrations that have been applied. |
true |
|
Shows application health information (when the application is secure, a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated). |
false |
|
Displays arbitrary application info. |
false |
|
Shows and modifies the configuration of loggers in the application. |
true |
|
Shows any Liquibase database migrations that have been applied. |
true |
|
Shows ‘metrics’ information for the current application. |
true |
|
Displays a collated list of all |
true |
|
Allows the application to be gracefully shutdown (not enabled by default). |
true |
|
Displays trace information (by default the last 100 HTTP requests). |
true |
If you are using Spring MVC, the following additional endpoints can also be used:
ID | Description | Sensitive Default |
---|---|---|
|
Displays documentation, including example requests and responses, for the Actuator’s endpoints. Requires |
false |
|
Returns a GZip compressed |
true |
|
Exposes JMX beans over HTTP (when Jolokia is on the classpath). |
true |
|
Returns the contents of the logfile (if |
true |
Depending on how an endpoint is exposed, the |
49.1 Customizing endpoints
Endpoints can be customized using Spring properties. You can change if an endpoint is enabled
, if it is considered sensitive
and even its id
.
For example, here is an application.properties
that changes the sensitivity and id of the beans
endpoint and also enables shutdown
.
endpoints.beans.id=springbeans
endpoints.beans.sensitive=false
endpoints.shutdown.enabled=true
The prefix ‟ |
By default, all endpoints except for shutdown
are enabled. If you prefer to specifically “opt-in” endpoint enablement you can use the endpoints.enabled
property. For example, the following will disable all endpoints except for info
:
endpoints.enabled=false
endpoints.info.enabled=true
Likewise, you can also choose to globally set the “sensitive” flag of all endpoints. By default, the sensitive flag depends on the type of endpoint (see the table above). For example, to mark all endpoints as sensitive except info
:
endpoints.sensitive=true
endpoints.info.sensitive=false
49.2 Hypermedia for actuator MVC endpoints
If endpoints.hypermedia.enabled
is set to true
and Spring HATEOAS is on the classpath (e.g. through the spring-boot-starter-hateoas
or if you are usingSpring Data REST) then the HTTP endpoints from the Actuator are enhanced with hypermedia links, and a “discovery page” is added with links to all the endpoints. The “discovery page” is available on /application
by default. It is implemented as an endpoint, allowing properties to be used to configure its path (endpoints.actuator.path
) and whether or not it is enabled (endpoints.actuator.enabled
).
When a custom management context path is configured, the “discovery page” will automatically move from /application
to the root of the management context. For example, if the management context path is /management
then the discovery page will be available from /management
.
如果HAL浏览器通过其webjar(org.webjars:hal-browser
)位于类路径上,或者通过spring-data-rest-hal-browser
HAL浏览器的形式通过HTML“发现页面”提供。
49.3 CORS支持
跨源资源共享 (CORS)是一种W3C规范,允许您以灵活的方式指定授权的跨域请求类型。Actuator的MVC端点可以配置为支持此类方案。
默认情况下禁用CORS支持,并且仅endpoints.cors.allowed-origins
在设置了属性后才启用CORS支持 。下面许可的配置 GET
和POST
从电话example.com
域:
endpoints.cors.allowed-origins = http://example.com
endpoints.cors.allowed-methods = GET,POST
检查EndpointCorsProperties 以获取完整的选项列表。 |
49.4添加自定义端点
如果添加一个@Bean
类型Endpoint
,它将自动通过JMX和HTTP公开(如果有可用的服务器)。可以通过创建类型的bean来进一步自定义HTTP端点MvcEndpoint
。您MvcEndpoint
不是,@Controller
但它可以使用@RequestMapping
(和@Managed*
)来公开资源。
如果你这样做是为库特征考虑增加带注释的配置类 |
49.5健康信息
运行状况信息可用于检查正在运行的应用程序的状态。监视软件经常使用它来提醒某人生产系统是否出现故障。health
端点公开的默认信息取决于访问方式。对于安全应用程序中未经身份验证的连接,将返回简单的“状态”消息,对于经过身份验证的连接,还会显示其他详细信息(有关HTTP详细信息,请参见 第50.7节“HTTP健康端点格式和访问限制”)。
健康信息是从HealthIndicator
您定义的所有bean中收集 的ApplicationContext
。Spring Boot包括一些自动配置 HealthIndicators
,你也可以编写自己的。默认情况下,最终系统状态是通过 基于有序状态列表对HealthAggregator
每个状态进行排序来派生的HealthIndicator
。排序列表中的第一个状态用作整体运行状况。如果否,则HealthIndicator
返回已知 HealthAggregator
的UNKNOWN
状态,则使用状态。
49.6 HealthIndicators的安全性
Information returned by HealthIndicators
is often somewhat sensitive in nature. For example, you probably don’t want to publish details of your database server to the world. For this reason, by default, only the health status is exposed over an unauthenticated HTTP connection. If you are happy for complete health information to always be exposed you can set endpoints.health.sensitive
to false
.
Health responses are also cached to prevent “denial of service” attacks. Use the endpoints.health.time-to-live
property if you want to change the default cache period of 1000 milliseconds.
49.6.1 Auto-configured HealthIndicators
The following HealthIndicators
are auto-configured by Spring Boot when appropriate:
Name | Description |
---|---|
Checks that a Cassandra database is up. |
|
Checks for low disk space. |
|
Checks that a connection to |
|
Checks that an Elasticsearch cluster is up. |
|
Checks that a JMS broker is up. |
|
Checks that a mail server is up. |
|
Checks that a Mongo database is up. |
|
Checks that a Rabbit server is up. |
|
Checks that a Redis server is up. |
|
Checks that a Solr server is up. |
It is possible to disable them all using the |
49.6.2 Writing custom HealthIndicators
To provide custom health information you can register Spring beans that implement the HealthIndicator
interface. You need to provide an implementation of the health()
method and return a Health
response. The Health
response should include a status and can optionally include additional details to be displayed.
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component; @Component
public class MyHealthIndicator implements HealthIndicator { @Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
} }
给定的标识符 |
除了Spring Boot的预定义Status
类型之外,还可以Health
返回Status
表示新系统状态的自定义。在这种情况下,HealthAggregator
还需要提供接口的自定义实现,或者必须使用management.health.status.order
配置属性配置默认实现。
例如,假设在您的某个实现中使用了 Status
带代码的新代码。要配置严重性顺序,请将以下内容添加到应用程序属性中:FATAL
HealthIndicator
management.health.status.order = FATAL,DOWN,OUT_OF_SERVICE,UNKNOWN,UP
响应中的HTTP状态代码反映了整体运行状况(例如,UP
映射到200 OUT_OF_SERVICE
或DOWN
503)。HealthMvcEndpoint
如果通过HTTP访问运行状况端点,您可能还希望注册自定义状态映射。例如,以下映射FATAL
到HttpStatus.SERVICE_UNAVAILABLE
:
endpoints.health.mapping.FATAL = 503
内置状态的默认状态映射是:
状态 | 制图 |
---|---|
下 |
SERVICE_UNAVAILABLE(503) |
停止服务 |
SERVICE_UNAVAILABLE(503) |
UP |
默认情况下没有映射,因此http状态为200 |
未知 |
默认情况下没有映射,因此http状态为200 |
49.7申请信息
应用程序信息公开从InfoContributor
您的中定义的所有bean 收集的各种信息 ApplicationContext
。Spring Boot包括一些自动配置 InfoContributors
,你也可以编写自己的。
49.7.1自动配置的InfoContributors
InfoContributors
适当时,Spring Boot会自动配置以下内容:
名称 | 描述 |
---|---|
从钥匙 |
|
如果 |
|
如果 |
可以使用 |
49.7.2自定义应用程序信息信息
您可以info
通过设置info.*
Spring属性来自定义端点公开的数据。Environment
信息键下的所有属性都将自动公开。例如,您可以将以下内容添加到您的application.properties
:
info.app.encoding = UTF-8
info.app.java.source = 1.8
info.app.java.target = 1.8
您可以在构建时扩展信息属性,而不是对这些值进行硬编码 。 假设您正在使用Maven,您可以按如下方式重写上面的示例: info.app.encoding =@project.build.sourceEncoding @ |
49.7.3 Git提交信息
info
端点的另一个有用功能是它能够git
在构建项目时发布有关源代码存储库状态的信息。如果 GitProperties
豆可用,git.branch
,git.commit.id
和git.commit.time
属性将被暴露出来。
如果要显示完整的git信息(即完整内容 git.properties
),请使用以下management.info.git.mode
属性:
management.info.git.mode =已满
49.7.4构建信息
info
如果BuildProperties
bean可用,端点还可以发布有关构建的信息。如果META-INF/build-info.properties
类路径中有文件可用,则会发生这种情况。
49.7.5编写自定义InfoContributors
要提供自定义应用程序信息,您可以注册实现该InfoContributor
接口的Spring bean 。
下面的示例提供了example
具有单个值的条目:
import java.util.Collections; import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component; @Component
公共 类 ExampleInfoContributor实现 InfoContributor { @Override
public void contribution(Info.Builder builder){
builder.withDetail(“example”,
Collections.singletonMap(“key”,“value”));
} }
如果您点击info
端点,您应该看到包含以下附加条目的响应:
{
“example”:{
“key”:“value”
}
}
50.通过HTTP监控和管理
If you are developing a Spring MVC application, Spring Boot Actuator will auto-configure all enabled endpoints to be exposed over HTTP. The default convention is to use the id
of the endpoint with a prefix of /application
as the URL path. For example, health
is exposed as /application/health
.
50.1 Accessing sensitive endpoints
By default all sensitive HTTP endpoints are secured such that only users that have an ACTUATOR
role may access them. Security is enforced using the standardHttpServletRequest.isUserInRole
method.
Use the |
If you are deploying applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do this by changing the management.security.enabled
property:
application.properties.
management.security.enabled=false
By default, actuator endpoints are exposed on the same port that serves regular HTTP traffic. Take care not to accidentally expose sensitive information if you change the |
If you’re deploying applications publicly, you may want to add ‘Spring Security’ to handle user authentication. When ‘Spring Security’ is added, by default ‘basic’ authentication will be used with the username user
and a generated password (which is printed on the console when the application starts).
Generated passwords are logged as the application starts. Search for ‘Using default security password’. |
您可以使用Spring属性更改用户名和密码,以及更改访问端点所需的安全角色。例如,您可以在以下位置设置以下内容application.properties
:
security.user.name = admin
security.user.password = secret
management.security.roles = SUPERUSER
如果您的应用程序具有自定义安全配置,并且您希望无需身份验证即可访问所有执行器端点,则需要在安全配置中明确配置该端点。除此之外,您还需要将management.security.enabled
属性更改为false
。
如果您的自定义安全配置可以保护您的执行器端点,则还需要确保经过身份验证的用户具有指定的角色management.security.roles
。
如果您没有用于向未经身份验证的用户公开基本运行状况信息的用例,并且已使用自定义安全性保护执行器端点,则可以设置 |
50.2自定义管理端点路径
有时,自定义管理端点的前缀很有用。例如,您的应用程序可能已/application
用于其他目的。您可以使用该management.context-path
属性更改管理端点的前缀:
management.context-path = / manage
application.properties
上面的示例将端点更改/application/{id}
为 /manage/{id}
(例如/manage/info
)。
您还可以更改端点的“路径”(使用endpoints.{name}.path
),然后更改MVC端点的默认资源路径。这些值没有验证(因此您可以使用URL路径中合法的任何内容)。例如,要更改/health
端点的位置,/ping/me
您可以设置 endpoints.health.path=/ping/me
。
即使端点路径是单独配置的,它仍然相对于 |
如果您提供自定义, |
50.3自定义管理服务器端口
使用默认HTTP端口公开管理端点是基于云的部署的明智选择。但是,如果您的应用程序在您自己的数据中心内运行,您可能更喜欢使用不同的HTTP端口公开端点。
该management.port
属性可用于更改HTTP端口。
management.port = 8081
由于您的管理端口通常受防火墙保护,并且未向公众公开,因此即使主应用程序是安全的,您也可能不需要管理端点上的安全性。在这种情况下,您将在类路径上安装Spring Security,并且可以像这样禁用管理安全性:
management.security.enabled = false
(如果类路径上没有Spring Security,则无需以这种方式显式禁用管理安全性,甚至可能会破坏应用程序。)
50.4配置特定于管理的SSL
配置为使用自定义端口时,还可以使用各种management.ssl.*
属性为管理服务器配置自己的SSL 。例如,这允许管理服务器在主应用程序使用HTTPS时通过HTTP可用:
server.port = 8443
server.ssl.enabled = true
server.ssl.key-store = classpath:store.jks
server.ssl.key-password = secret
management.port = 8080
management.ssl.enabled = false
或者,主服务器和管理服务器都可以使用SSL,但具有不同的密钥库:
server.port = 8443
server.ssl.enabled = true
server.ssl.key-store = classpath:main.jks
server.ssl.key-password = secret
management.port = 8080
management.ssl.enabled = true
management.ssl。 key-store = classpath:management.jks
management.ssl.key-password = secret
50.5自定义管理服务器地址
您可以通过设置management.address
属性来自定义管理端点可用的地址。如果您只想在内部或面向操作的网络上侦听,或仅侦听来自的连接,这将非常有用localhost
。
如果端口与主服务器端口不同,则只能侦听不同的地址。 |
以下是一个application.properties
不允许远程管理连接的示例:
management.port = 8081
management.address = 127.0.0.1
50.6禁用HTTP端点
如果您不想通过HTTP公开端点,可以将管理端口设置为-1
:
management.port = -1
50.7 HTTP健康端点格式和访问限制
健康终端公开的信息取决于是否匿名访问,以及封闭应用程序是否安全。默认情况下,在安全应用程序中匿名访问时,将隐藏有关服务器运行状况的任何详细信息,并且端点将仅指示服务器是启动还是关闭。此外,响应被缓存一段可配置的时间,以防止端点被用于拒绝服务攻击。该endpoints.health.time-to-live
属性用于配置缓存周期(以毫秒为单位)。它默认为1000,即一秒。
示例汇总HTTP响应(匿名请求的默认值):
$ curl -i localhost:8080 / health
HTTP / 1.1 200
X-Application-Context:应用程序
Content-Type:application / vnd.spring-boot.actuator.v2 + json; charset = UTF-8
内容长度:15 { “地位”: “UP”}
示例汇总状态为“DOWN”的HTTP响应(请注意503状态代码):
$ curl -i localhost:8080 / health
HTTP / 1.1 503
X-Application-Context:应用程序
Content-Type:application / vnd.spring-boot.actuator.v2 + json; charset = UTF-8
内容长度:17 { “地位”: “DOWN”}
示例详细的HTTP响应:
$ curl -i localhost:8080 / health
HTTP / 1.1 200好的
X-Application-Context:应用程序
Content-Type:application / vnd.spring-boot.actuator.v2 + json; charset = UTF-8
内容长度:221 {
“状态”:“UP”,
“磁盘空间” : {
“状态”:“UP”,
“总计”:63251804160,
“免费”:31316164608,
“threshold”:10485760
},
“D b” : {
“状态”:“UP”,
“数据库”:“H2”,
“你好”:1
}
}
The above-described restrictions can be enhanced, thereby allowing only authenticated users full access to the health endpoint in a secure application. To do so, setendpoints.health.sensitive
to true
. Here’s a summary of behavior (with default sensitive
flag value “false” indicated in bold):
management.security.enabled |
endpoints.health.sensitive |
Unauthenticated | Authenticated (with right role) |
---|---|---|---|
false |
* |
Full content |
Full content |
true |
false |
Status only |
Full content |
true |
true |
No content |
Full content |
51. Monitoring and management over JMX
Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default Spring Boot will expose management endpoints as JMX MBeans under the org.springframework.boot
domain.
51.1 Customizing MBean names
The name of the MBean is usually generated from the id
of the endpoint. For example the health
endpoint is exposed as org.springframework.boot/Endpoint/healthEndpoint
.
If your application contains more than one Spring ApplicationContext
you may find that names *. To solve this problem you can set the endpoints.jmx.unique-names
property to true
so that MBean names are always unique.
You can also customize the JMX domain under which endpoints are exposed. Here is an example application.properties
:
endpoints.jmx.domain=myapp
endpoints.jmx.unique-names=true
51.2 Disabling JMX endpoints
If you don’t want to expose endpoints over JMX you can set the endpoints.jmx.enabled
property to false
:
endpoints.jmx.enabled=false
51.3 Using Jolokia for JMX over HTTP
Jolokia is a JMX-HTTP bridge giving an alternative method of accessing JMX beans. To use Jolokia, simply include a dependency to org.jolokia:jolokia-core
. For example, using Maven you would add the following:
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
Jolokia can then be accessed using /jolokia
on your management HTTP server.
51.3.1 Customizing Jolokia
Jolokia has a number of settings that you would traditionally configure using servlet parameters. With Spring Boot you can use your application.properties
, simply prefix the parameter with jolokia.config.
:
jolokia.config.debug=true
51.3.2 Disabling Jolokia
If you are using Jolokia but you don’t want Spring Boot to configure it, simply set the endpoints.jolokia.enabled
property to false
:
endpoints.jolokia.enabled=false
52. Loggers
Spring Boot Actuator includes the ability to view and configure the log levels of your application at runtime. You can view either the entire list or an individual logger’s configuration which is made up of both the explicitly configured logging level as well as the effective logging level given to it by the logging framework. These levels can be:
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
OFF
null
with null
indicating that there is no explicit configuration.
52.1 Configure a Logger
In order to configure a given logger, you POST
a partial entity to the resource’s URI:
{
"configuredLevel": "DEBUG"
}
You can also pass a |
53. Metrics
Spring Boot Actuator includes a metrics service with ‘gauge’ and ‘counter’ support. A ‘gauge’ records a single value; and a ‘counter’ records a delta (an increment or decrement). Spring Boot Actuator also provides a PublicMetrics
interface that you can implement to expose metrics that you cannot record via one of those two mechanisms. Look at SystemPublicMetrics
for an example.
Metrics for all HTTP requests are automatically recorded, so if you hit the metrics
endpoint you should see a response similar to this:
{
"counter.status.200.root": 20,
"counter.status.200.metrics": 3,
"counter.status.200.star-star": 5,
"counter.status.401.root": 4,
"gauge.response.star-star": 6,
"gauge.response.root": 2,
"gauge.response.metrics": 3,
"classes": 5808,
"classes.loaded": 5808,
"classes.unloaded": 0,
"heap": 3728384,
"heap.committed": 986624,
"heap.init": 262144,
"heap.used": 52765,
"nonheap": 0,
"nonheap.committed": 77568,
"nonheap.init": 2496,
"nonheap.used": 75826,
"mem": 986624,
"mem.free": 933858,
"processors": 8,
"threads": 15,
"threads.daemon": 11,
"threads.peak": 15,
"threads.totalStarted": 42,
"uptime": 494836,
"instance.uptime": 489782,
"datasource.primary.active": 5,
"datasource.primary.usage": 0.25
}
Here we can see basic memory
, heap
, class loading
, processor
and thread pool
information along with some HTTP metrics. In this instance the root
(‘/’) and /metrics
URLs have returned HTTP 200
responses 20
and 3
times respectively. It also appears that the root
URL returned HTTP 401
(unauthorized) 4
times. The double asterisks (star-star
) comes from a request matched by Spring MVC as /**
(normally a static resource).
The gauge
shows the last response time for a request. So the last request to root
took 2ms
to respond and the last to /metrics
took 3ms
.
In this example we are actually accessing the endpoint over HTTP using the |
53.1系统指标
Spring Boot公开了以下系统指标:
- 系统总内存(KB
mem
) - 可用内存量(KB
mem.free
) - 处理器数量(
processors
) - 系统正常运行时间(毫秒
uptime
) - 应用程序上下文的正常运行时间(以毫秒为单位
instance.uptime
) - 平均系统负载(
systemload.average
) - 堆信息KB( ,
heap
,heap.committed
,)heap.init
heap.used
- 线程信息(
threads
,thread.peak
,thread.daemon
) - 类负载信息(
classes
,classes.loaded
,classes.unloaded
) - 垃圾收集信息(
gc.xxx.count
,gc.xxx.time
)
53.2 DataSource指标
为DataSource
应用程序中定义的每个受支持者公开以下度量标准:
- 活动连接数(
datasource.xxx.active
) - 连接池的当前用法(
datasource.xxx.usage
)。
所有数据源指标都共享datasource.
前缀。前缀进一步限定每个数据源:
- 如果数据源是主数据源(即唯一可用的数据源或现有数据源中标记的数据源
@Primary
),则前缀为datasource.primary
。 - 如果数据源bean名称以...结尾
DataSource
,则前缀是没有DataSource
(即datasource.batch
forbatchDataSource
)的bean的名称。 - 在所有其他情况下,使用bean的名称。
可以通过注册具有自定义版本的bean来覆盖部分或全部默认值DataSourcePublicMetrics
。默认情况下,Spring Boot为所有支持的数据源提供元数据; DataSourcePoolMetadataProvider
如果不支持您喜爱的数据源,则可以添加其他bean。请参阅 DataSourcePoolMetadataProvidersConfiguration
示例。
53.3缓存指标
为应用程序中定义的每个受支持的缓存公开以下度量标准:
- 缓存的当前大小(
cache.xxx.size
) - 命中率(
cache.xxx.hit.ratio
) - 错过率(
cache.xxx.miss.ratio
)
缓存提供程序不会以一致的方式公开命中/未命中率。虽然有些暴露了聚合值(即自上次清除统计数据以来的命中率),但其他人暴露了时间值(即最后一秒的命中率)。有关详细信息,请查看缓存提供程序文档。 |
如果两个不同的缓存管理器碰巧定义了相同的缓存,则缓存的名称以CacheManager
bean 的名称为前缀。
可以通过注册具有自定义版本的bean来覆盖部分或全部默认值CachePublicMetrics
。默认情况下,Spring Boot为EhCache,Hazelcast,Infinispan,JCache和Caffeine提供缓存统计信息。CacheStatisticsProvider
如果开箱即用不支持您喜欢的缓存库,则可以添加其他 bean。请参阅CacheStatisticsAutoConfiguration
示例。
53.4 Tomcat会话指标
如果您使用Tomcat作为嵌入式servlet容器,则会自动公开会话度量标准。在httpsessions.active
与httpsessions.max
键提供主动和最大会话数。
53.5记录您自己的指标
要记录您自己的指标,请注入 CounterService
和/或 GaugeService
注入您的bean。的CounterService
自曝increment
,decrement
和reset
方法; 在GaugeService
提供了一个submit
方法。
这是一个简单的示例,它计算调用方法的次数:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.stereotype.Service; @Service
public class MyService { 私人 最终 CounterService counterService; @Autowired
public MyService(CounterService counterService){
this .counterService = counterService;
} public void exampleMethod (){
this .counterService.increment(“services.system.myservice.invoked”);
} }
您可以使用任何字符串作为度量标准名称,但您应遵循所选商店/图形技术的指导原则。Matt Aimonetti博客上提供了一些有关Graphite的好指南 。 |
53.6添加自己的公共指标
要添加每次调用度量标准端点时计算的其他度量标准,只需注册其他PublicMetrics
实现bean 即可。默认情况下,端点会收集所有此类Bean。您可以通过定义自己的方式轻松更改它 MetricsEndpoint
。
53.7度量标准编写者,出口者和聚合
Spring Boot提供了一些标记接口的实现Exporter
,可以用来将内存缓冲区中的度量标准读数复制到可以分析和显示它们的位置。实际上,如果您提供@Bean
实现MetricWriter
接口(或GaugeWriter
简单用例)并标记它 @ExportMetricWriter
,那么它将自动连接到Exporter
每5秒一次的馈送指标更新(通过配置spring.metrics.export.delay-millis
)。此外,MetricReader
您定义和标记的任何内容都@ExportMetricReader
将使其值由默认导出器导出。
此功能在您的应用程序( |
The default exporter is a MetricCopyExporter
which tries to optimize itself by not copying values that haven’t changed since it was last called (the optimization can be switched off using a flag spring.metrics.export.send-latest
). Note also that the Dropwizard MetricRegistry
has no support for timestamps, so the optimization is not available if you are using Dropwizard metrics (all metrics will be copied on every tick).
The default values for the export trigger (delay-millis
, includes
, excludes
and send-latest
) can be set as spring.metrics.export.*
. Individual values for specific MetricWriters
can be set as spring.metrics.export.triggers.<name>.*
where <name>
is a bean name (or pattern for matching bean names).
The automatic export of metrics is disabled if you switch off the default |
53.7.1 Example: Export to Redis
If you provide a @Bean
of type RedisMetricRepository
and mark it @ExportMetricWriter
the metrics are exported to a Redis cache for aggregation. The RedisMetricRepository
has two important parameters to configure it for this purpose: prefix
and key
(passed into its constructor). It is best to use a prefix that is unique to the application instance (e.g. using a random value and maybe the logical name of the application to make it possible to correlate with other instances of the same application). The “key” is used to keep a global index of all metric names, so it should be unique “globally”, whatever that means for your system (e.g. two instances of the same system could share a Redis cache if they have distinct keys).
Example:
@Bean
@ExportMetricWriter
MetricWriter metricWriter(MetricExportProperties export) {
return new RedisMetricRepository(connectionFactory,
export.getRedis().getPrefix(), export.getRedis().getKey());
}
application.properties.
spring.metrics.export.redis.prefix: metrics.mysystem.${spring.application.name:application}.${random.value:0000}
spring.metrics.export.redis.key: keys.metrics.mysystem
The prefix is constructed with the application name and id at the end, so it can easily be used to identify a group of processes with the same logical name later.
It’s important to set both the |
The example above uses |
53.7.2 Example: Export to Open TSDB
If you provide a @Bean
of type OpenTsdbGaugeWriter
and mark it @ExportMetricWriter
metrics are exported to Open TSDB for aggregation. The OpenTsdbGaugeWriter
has a url
property that you need to set to the Open TSDB “/put” endpoint, e.g. localhost:4242/api/put
). It also has a namingStrategy
that you can customize or configure to make the metrics match the data structure you need on the server. By default it just passes through the metric name as an Open TSDB metric name, and adds the tags “domain” (with value “org.springframework.metrics”) and “process” (with the value equal to the object hash of the naming strategy). Thus, after running the application and generating some metrics you can inspect the metrics in the TSD UI (localhost:4242 by default).
Example:
curl localhost:4242 / api / query?start = 1h-ago&m = max:counter.status.200.root
[
{
“metric”:“counter.status.200.root”,
“tags”:{
“domain”:“org.springframework.metrics”,
“过程”:“b968a76”
},
“aggregateTags”:[],
“dps”:{
“1430492872”:2,
“1430492875”:6
}
}
]
53.7.3示例:导出到Statsd
要将度量标准导出到Statsd,请首先确保已添加 com.timgroup:java-statsd-client
为项目的依赖项(Spring Boot为其提供了依赖关系管理)。然后spring.metrics.export.statsd.host
为您的application.properties
文件添加一个值。8125
除非提供spring.metrics.export.statsd.port
覆盖,否则将打开连接到端口。spring.metrics.export.statsd.prefix
如果需要自定义前缀,可以使用 。
或者,您可以提供@Bean
类型StatsdMetricWriter
并标记它 @ExportMetricWriter
:
@value( “$ {spring.application.name:application}.${random.value:0000}”)
私人字符串前缀= “度量” ; @Bean
@ExportMetricWriter
MetricWriter metricWriter(){
返回 新的 StatsdMetricWriter(前缀,“localhost”,8125);
}
53.7.4示例:导出到JMX
如果您提供标记的@Bean
类型,则将度量标准导出为本地服务器的MBean(由Spring Boot JMX自动配置提供,只要它已打开)。然后可以使用任何了解JMX的工具(例如JConsole或JVisualVM)检查,绘制图表,提醒等指标。JmxMetricWriter
@ExportMetricWriter
MBeanExporter
例:
@Bean
@ExportMetricWriter
MetricWriter metricWriter(MBeanExporter exporter){
返回 新的 JmxMetricWriter(导出器);
}
每个度量标准都作为单个MBean导出。它的格式ObjectNames
由一个ObjectNamingStrategy
可以注入的格式给出JmxMetricWriter
(默认情况下会拆分度量标准名称,并以一种应该在JVisualVM或JConsole中很好地构建度量标准组的方式标记前两个句点分隔的部分)。
53.8汇总来自多个来源的指标
有一个AggregateMetricReader
,你可以用它来整合来自不同物理源指标。同一逻辑度量的源只需要使用以句点分隔的前缀发布它们,并且读取器将聚合(通过截断度量标准名称并删除前缀)。计数器总和,其他一切(即仪表)采用最新的价值。
This is very useful if multiple application instances are feeding to a central (e.g. Redis) repository and you want to display the results. Particularly recommended in conjunction with a MetricReaderPublicMetrics
for hooking up to the results to the “/metrics” endpoint.
Example:
@Autowired
private MetricExportProperties export; @Bean
public PublicMetrics metricsAggregate() {
return new MetricReaderPublicMetrics(aggregatesMetricReader());
} private MetricReader globalMetricsForAggregation() {
return new RedisMetricRepository(this.connectionFactory,
this.export.getRedis().getAggregatePrefix(), this.export.getRedis().getKey());
} private MetricReader aggregatesMetricReader() {
AggregateMetricReader repository = new AggregateMetricReader(
globalMetricsForAggregation());
return repository;
}
The example above uses |
The |
53.9 Dropwizard Metrics
A default MetricRegistry
Spring bean will be created when you declare a dependency to the io.dropwizard.metrics:metrics-core
library; you can also register you own @Bean
instance if you need customizations. Users of the Dropwizard ‘Metrics’ library will find that Spring Boot metrics are automatically published to com.codahale.metrics.MetricRegistry
. Metrics from the MetricRegistry
are also automatically exposed via the /metrics
endpoint
When Dropwizard metrics are in use, the default CounterService
and GaugeService
are replaced with a DropwizardMetricServices
, which is a wrapper around the MetricRegistry
(so you can @Autowired
one of those services and use it as normal). You can also create “special” Dropwizard metrics by prefixing your metric names with the appropriate type (i.e. timer.*
, histogram.*
for gauges, and meter.*
for counters).
53.10 Message channel integration
If a MessageChannel
bean called metricsChannel
exists, then a MetricWriter
will be created that writes metrics to that channel. Each message sent to the channel will contain a Delta
or Metric
payload and have a metricName
header. The writer is automatically hooked up to an exporter (as for all writers), so all metric values will appear on the channel, and additional analysis or actions can be taken by subscribers (it’s up to you to provide the channel and any subscribers you need).
54. Auditing
Spring Boot Actuator has a flexible audit framework that will publish events once Spring Security is in play (‘authentication success’, ‘failure’ and ‘access denied’ exceptions by default). This can be very useful for reporting, and also to implement a lock-out policy based on authentication failures. To customize published security events you can provide your own implementations of AbstractAuthenticationAuditListener
and AbstractAuthorizationAuditListener
.
You can also choose to use the audit services for your own business events. To do that you can either inject the existing AuditEventRepository
into your own components and use that directly, or you can simply publish AuditApplicationEvent
via the Spring ApplicationEventPublisher
(using ApplicationEventPublisherAware
).
55. Tracing
Tracing is automatically enabled for all HTTP requests. You can view the trace
endpoint and obtain basic information about the last 100 requests:
[{
"timestamp": 1394343677415,
"info": {
"method": "GET",
"path": "/trace",
"headers": {
"request": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection": "keep-alive",
"Accept-Encoding": "gzip, deflate",
"User-Agent": "Mozilla/5.0 Gecko/Firefox",
"Accept-Language": "en-US,en;q=0.5",
"Cookie": "_ga=GA1.1.827067509.1390890128; ..."
"Authorization": "Basic ...",
"Host": "localhost:8080"
},
"response": {
"Strict-Transport-Security": "max-age=31536000 ; includeSubDomains",
"X-Application-Context": "application:8080",
"Content-Type": "application/json;charset=UTF-8",
"status": "200"
}
}
}
},{
"timestamp": 1394343684465,
...
}]
The following are included in the trace by default:
Name | Description |
---|---|
Request Headers |
Headers from the request. |
Response Headers |
Headers from the response. |
Cookies |
|
Errors |
The error attributes (if any). |
Time Taken |
The time taken to service the request in milliseconds. |
55.1 Custom tracing
If you need to trace additional events you can inject a TraceRepository
into your Spring beans. The add
method accepts a single Map
structure that will be converted to JSON and logged.
By default an InMemoryTraceRepository
will be used that stores the last 100 events. You can define your own instance of the InMemoryTraceRepository
bean if you need to expand the capacity. You can also create your own alternative TraceRepository
implementation if needed.
56. Process monitoring
In Spring Boot Actuator you can find a couple of classes to create files that are useful for process monitoring:
-
ApplicationPidFileWriter
creates a file containing the application PID (by default in the application directory with the file nameapplication.pid
). -
EmbeddedServerPortFileWriter
creates a file (or files) containing the ports of the embedded server (by default in the application directory with the file nameapplication.port
).
These writers are not activated by default, but you can enable them in one of the ways described below.
56.1 Extend configuration
In META-INF/spring.factories
file you can activate the listener(s) that writes a PID file. Example:
org.springframework.context.ApplicationListener=\
org.springframework.boot.system.ApplicationPidFileWriter,\
org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter
56.2 Programmatically
You can also activate a listener by invoking the SpringApplication.addListeners(…)
method and passing the appropriate Writer
object. This method also allows you to customize the file name and path via the Writer
constructor.
57. Cloud Foundry support
Spring Boot’s actuator module includes additional support that is activated when you deploy to a compatible Cloud Foundry instance. The /cloudfoundryapplication
path provides an alternative secured route to all NamedMvcEndpoint
beans.
The extended support allows Cloud Foundry management UIs (such as the web application that you can use to view deployed applications) to be augmented with Spring Boot actuator information. For example, an application status page may include full health information instead of the typical “running” or “stopped” status.
The |
57.1 Disabling extended Cloud Foundry actuator support
If you want to fully disable the /cloudfoundryapplication
endpoints you can add the following to your application.properties
file:
application.properties.
management.cloudfoundry.enabled=false
57.2 Cloud Foundry self signed certificates
By default, the security verification for /cloudfoundryapplication
endpoints makes SSL calls to various Cloud Foundry services. If your Cloud Foundry UAA or Cloud Controller services use self-signed certificates you will need to set the following property:
application.properties.
management.cloudfoundry.skip-ssl-validation=true
57.3 Custom security configuration
如果您定义自定义安全配置,并且希望扩展Cloud Foundry执行器支持,则应确保/cloudfoundryapplication/**
路径是开放的。如果没有直接开放路线,您的Cloud Foundry应用程序管理器将无法获取端点数据。
对于Spring Security,您通常会mvcMatchers("/cloudfoundryapplication/**").permitAll()
在配置中包含类似 的内容:
@Override
protected void configure(HttpSecurity http)抛出 Exception {
HTTP
.authorizeRequests()
.mvcMatchers(“/ cloudfoundryapplication / **”)
.permitAll()
.mvcMatchers(“/ mypath”)
.hasAnyRole(“SUPERUSER”)
.anyRequest()
.authenticated()和()
.httpBasic();
}
58.接下来要读什么
如果您想探索本章中讨论的一些概念,您可以查看执行器示例应用程序。您还可能想了解Graphite等图形工具。
否则,您可以继续阅读有关“部署选项”的信息,或者继续阅读有关Spring Boot 构建工具插件的一些深入信息 。
第六部分。部署Spring Boot应用程序
Spring Boot的灵活打包选项在部署应用程序时提供了大量选择。您可以轻松地将Spring Boot应用程序部署到各种云平台,容器映像(如Docker)或虚拟/真实计算机。
本节介绍一些更常见的部署方案。
59.部署到云端
Spring Boot的可执行jar是现成的,适用于大多数流行的云PaaS(平台即服务)提供商。这些供应商往往要求您“带上自己的容器”; 他们管理应用程序进程(而不是特定于Java应用程序),因此他们需要一些中间层来使您的应用程序 适应云计算正在运行的进程。
两个流行的云提供商Heroku和Cloud Foundry采用“buildpack”方法。buildpack将您部署的代码包装在启动应用程序所需的任何内容中:它可能是JDK和调用java
,可能是嵌入式Web服务器,也可能是完整的应用程序服务器。buildpack是可插拔的,但理想情况下,您应该能够尽可能少地进行自定义。这减少了不受您控制的功能的占用空间。它最大限度地减少了开发和生产环境之间的差异。
理想情况下,您的应用程序(如Spring Boot可执行jar)具有在其中运行打包所需的所有内容。
在本节中,我们将了解如何使我们在“入门”部分中开发并在云中运行的 简单应用程序。
59.1 Cloud Foundry
如果未指定其他buildpack,Cloud Foundry将提供默认的构建包。Cloud Foundry Java buildpack 对Spring应用程序(包括Spring Boot)提供了出色的支持。您可以部署独立的可执行jar应用程序以及传统的.war
打包应用程序。
Once you’ve built your application (using, for example, mvn clean package
) and installed the cf
command line tool, simply deploy your application using the cf push
command as follows, substituting the path to your compiled .jar
. Be sure to have logged in with your cf
command line client before pushing an application.
$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar
See the cf push
documentation for more options. If there is a Cloud Foundry manifest.yml
file present in the same directory, it will be consulted.
Here we are substituting |
At this point cf
will start uploading your application:
正在上传acloudyspringtime ... 确定
准备启动acloudyspringtime ... 确定
----->下载的应用程序包(8.9M)
-----> Java Buildpack版本:v3.12(离线)| https://github.com/cloudfoundry/java-buildpack.git#6f25b7e
----->从https://java-buildpack.cloudfoundry.org/openjdk/trusty/x86_64/openjdk-1.8.0_121.tar.gz下载Open Jdk JRE 1.8.0_121(在缓存中找到)
将Open Jdk JRE扩展为.java-buildpack / open_jdk_jre(1.6s)
----->从https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz下载Open JDK,如内存计算器2.0.2_RELEASE(在高速缓存)
内存设置:-Xss349K -Xmx681574K -XX:MaxMetaspaceSize = 104857K -Xms681574K -XX:MetaspaceSize = 104857K
----->从https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar下载容器证书信任存储1.0.0_RELEASE(找到在缓存中)
将证书添加到.java-buildpack / container_certificate_trust_store / truststore.jks(0.6s)
----->从https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar下载Spring自动重配置1.10.0_RELEASE(在缓存中找到)
检查应用'acloudyspringtime'的状态...
运行1个实例中的0个(1个开始)
...
运行1个实例中的0个(1个开始)
...
运行1个实例中的0个(1个开始)
...
运行1个实例中的1个(运行1个) 应用程序启动
恭喜!该应用程序现已上线!
然后很容易验证已部署应用程序的状态:
$ cf apps
获取应用程序...
好 名称请求状态实例内存磁盘URL
...
acloudyspringtime开始1/1 512M 1G acloudyspringtime.cfapps.io
...
一旦Cloud Foundry确认您的应用程序已部署,您应该能够在给定的URI处命中应用程序,在本例中 http://acloudyspringtime.cfapps.io/
。
59.1.1绑定到服务
默认情况下,有关正在运行的应用程序的元数据以及服务连接信息将作为环境变量公开给应用程序(例如:) $VCAP_SERVICES
。这种架构决策是由于Cloud Foundry的多语言(任何语言和平台都可以作为buildpack支持)的性质; 进程范围的环境变量是语言无关的。
环境变量并不总能用于最简单的API,因此Spring Boot会自动提取它们并将数据展平为可通过Spring Environment
抽象访问的属性:
@Component
类 MyBean实现 EnvironmentAware { private String instanceId; @覆盖
公共 空隙 setEnvironment(环境环境){
此 .instanceId = environment.getProperty( “vcap.application.instance_id”);
} // ... }
所有Cloud Foundry属性都以vcap
。为前缀。您可以使用vcap属性来访问应用程序信息(例如应用程序的公共URL)和服务信息(例如数据库凭据)。有关CloudFoundryVcapEnvironmentPostProcessor
完整的详细信息,请参阅Javadoc。
在春季云连接器项目是任务,如配置数据源更适合。Spring Boot包括自动配置支持和 |
59.2 Heroku
Heroku是另一个流行的PaaS平台。要自定义Heroku构建,请提供a Procfile
,它提供部署应用程序所需的咒语。Heroku为port
要使用的Java应用程序分配一个,然后确保路由到外部URI工作。
您必须将应用程序配置为侦听正确的端口。这是Procfile
我们的入门REST应用程序:
web:java -Dserver.port = $ PORT -jar target / demo-0.0.1-SNAPSHOT.jar
Spring Boot使-D
参数可用作可从Spring Environment
实例访问的属性 。所述server.port
配置属性被馈送到嵌入的Tomcat,码头或暗流实例,它然后使用它时,它启动。该$PORT
环境变量由Heroku的PaaS的分配给我们。
这应该是你需要的一切。Heroku部署最常见的工作流程是 git push
代码生产。
$ git push heroku master 初始化存储库,完成。
计数对象:95,完成。
Delta压缩使用多达8个线程。
Compressing objects: 100% (78/78), done.
Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, done.
Total 95 (delta 31), reused 0 (delta 0) -----> Java app detected
-----> Installing OpenJDK 1.8... done
-----> Installing Maven 3.3.1... done
-----> Installing settings.xml... done
-----> Executing: mvn -B -DskipTests=true clean install [INFO] Scanning for projects...
Downloading: http://repo.spring.io/...
Downloaded: http://repo.spring.io/... (818 B at 1.8 KB/sec)
....
Downloaded: http://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec)
[INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/...
[INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 59.358s
[INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014
[INFO] Final Memory: 20M/493M
[INFO] ------------------------------------------------------------------------ -----> Discovering process types
Procfile declares types -> web -----> Compressing... done, 70.4MB
-----> Launching... done, v6
http://agile-sierra-1405.herokuapp.com/ deployed to Heroku To git@heroku.com:agile-sierra-1405.git
* [new branch] master -> master
Your application should now be up and running on Heroku.
59.3 OpenShift
OpenShift is the RedHat public (and enterprise) PaaS solution. Like Heroku, it works by running scripts triggered by git commits, so you can script the launching of a Spring Boot application in pretty much any way you like as long as the Java runtime is available (which is a standard feature you can ask for at OpenShift). To do this you can use the DIY Cartridge and hooks in your repository under .openshift/action_hooks
:
The basic model is to:
- Ensure Java and your build tool are installed remotely, e.g. using a
pre_build
hook (Java and Maven are installed by default, Gradle is not) -
Use a
build
hook to build your jar (using Maven or Gradle), e.g.#!/bin/bash
cd $OPENSHIFT_REPO_DIR
mvn package -s .openshift/settings.xml -DskipTests=true -
Add a
start
hook that callsjava -jar …
#!/bin/bash
cd $OPENSHIFT_REPO_DIR
nohup java -jar target/*.jar --server.port=${OPENSHIFT_DIY_PORT} --server.address=${OPENSHIFT_DIY_IP} & -
Use a
stop
hook (since the start is supposed to return cleanly), e.g.#!/bin/bash
source $OPENSHIFT_CARTRIDGE_SDK_BASH
PID=$(ps -ef | grep java.*\.jar | grep -v grep | awk '{ print $2 }')
if [ -z "$PID" ]
then
client_result "Application is already stopped"
else
kill $PID
fi -
Embed service bindings from environment variables provided by the platform in your
application.properties
, e.g.spring.datasource.url: jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_APP_NAME}
spring.datasource.username: ${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password: ${OPENSHIFT_MYSQL_DB_PASSWORD}
在他们的网站上有一个关于在OpenShift中运行Gradle的博客,它将帮助您开始使用gradle构建来运行应用程序。
59.4亚马逊网络服务(AWS)
Amazon Web Services提供了多种方法来安装基于Spring Boot的应用程序,可以是传统的Web应用程序(war),也可以是带有嵌入式Web服务器的可执行jar文件。选项包括:
- AWS Elastic Beanstalk
- AWS Code Deploy
- AWS OPS Works
- AWS Cloud Formation
- AWS容器注册表
每个都有不同的功能和定价模型,这里我们将只描述最简单的选项:AWS Elastic Beanstalk。
59.4.1 AWS Elastic Beanstalk
正如官方Elastic Beanstalk Java指南中所述,部署Java应用程序有两个主要选项; 您可以使用“Tomcat平台”或“Java SE平台”。
使用Tomcat平台
此选项适用于生成war文件的Spring Boot项目。没有任何特殊配置,只需按照官方指南。
使用Java SE平台
此选项适用于生成jar文件和运行嵌入式Web容器的Spring Boot项目。Elastic Beanstalk环境在端口80上运行nginx实例以代理在端口5000上运行的实际应用程序。要配置它,请将以下内容添加到 application.properties
:
server.port = 5000
最佳做法
上传二进制文件而不是源代码
默认情况下,Elastic Beanstalk会上传源并在AWS中对其进行编译。要上传二进制文件,请将以下内容添加到您的.elasticbeanstalk/config.yml
文件中:
部署:
artifact:target / demo-0.0.1-SNAPSHOT.jar
通过设置环境类型来降低成本
默认情况下,Elastic Beanstalk环境是负载平衡的。负载均衡器具有成本视角,为避免这种情况,请将环境类型设置为“单实例”,如 Amazon文档中所述。也可以使用CLI使用以下命令创建单实例环境:
eb创建-s
59.4.2摘要
这是访问AWS的最简单方法之一,但还有更多内容需要涉及,例如:如何将Elastic Beanstalk集成到任何CI / CD工具中,使用Elastic Beanstalk maven插件而不是CLI等。博客 更详细地介绍了这些主题。
59.5 Boxfuse和亚马逊网络服务
Boxfuse works by turning your Spring Boot executable jar or war into a minimal VM image that can be deployed unchanged either on VirtualBox or on AWS. Boxfuse comes with deep integration for Spring Boot and will use the information from your Spring Boot configuration file to automatically configure ports and health check URLs. Boxfuse leverages this information both for the images it produces as well as for all the resources it provisions (instances, security groups, elastic load balancers, etc).
Once you have created a Boxfuse account, connected it to your AWS account, and installed the latest version of the Boxfuse Client, you can deploy your Spring Boot application to AWS as follows (ensure the application has been built by Maven or Gradle first using, for example, mvn clean package
):
$ boxfuse run myapp-1.0.jar -env=prod
See the boxfuse run
documentation for more options. If there is a boxfuse.com/docs/commandline/#configuration [boxfuse.conf
] file present in the current directory, it will be consulted.
By default Boxfuse will activate a Spring profile named |
At this point boxfuse
will create an image for your application, upload it, and then configure and start the necessary resources on AWS:
Fusing Image for myapp-1.0.jar ...
Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0
Creating axelfontaine/myapp ...
Pushing axelfontaine/myapp:1.0 ...
Verifying axelfontaine/myapp:1.0 ...
Creating Elastic IP ...
Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ...
Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ...
AMI created in 00:23.557s -> ami-d23f38cf
Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ...
Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ...
Instance launched in 00:30.306s -> i-92ef9f53
Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at http://52.28.235.61/ ...
Payload started in 00:29.266s -> http://52.28.235.61/
Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ...
Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ...
Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at http://myapp-axelfontaine.boxfuse.io/
Your application should now be up and running on AWS.
There’s a blog on deploying Spring Boot apps on EC2 as well as documentation for the Boxfuse Spring Boot integration on their website that will get you started with a Maven build to run the app.
59.6 Google Cloud
Google Cloud has several options that could be used to launch Spring Boot applications. The easiest to get started with is probably App Engine, but you could also find ways to run Spring Boot in a container with Container Engine, or on a virtual machine using Compute Engine.
要在App Engine中运行,您可以首先在UI中创建项目,该项目为您和HTTP路由设置唯一标识符。将Java应用程序添加到项目中并将其留空,然后使用Google Cloud SDK将Spring Boot应用程序从命令行或CI构建推送到该插槽。
App Engine需要您创建一个app.yaml
文件来描述您的应用所需的资源。通常你把src/min/appengine
它放进去,它看起来像这样:
服务:默认 runtime:java
env:flex runtime_config:
jdk:openjdk8 处理程序:
- url:/。*
脚本:此字段是必需的,但是被忽略 manual_scaling:
instances:1 health_check:
enable_health_check:False env_variables:
ENCRYPT_KEY:your_encryption_key_here
您可以通过简单地将项目ID添加到构建配置来使用Maven插件部署应用程序:
<plugin>
<groupId> com.google.cloud.tools </ groupId>
<artifactId> appengine-maven-plugin </ artifactId>
<version> 1.3.0 </ version>
<configuration>
<project> myproject </ project>
</ configuration>
</ plugin>
然后部署mvn appengine:deploy
(如果您需要首先进行身份验证,则构建将失败)。
Google App Engine Classic与Servlet 2.5 API绑定在一起,因此您无需在不进行某些修改的情况下在其中部署Spring应用程序。请参阅本指南的 Servlet 2.5部分。 |
60.安装Spring Boot应用程序
除了使用java -jar
它运行Spring Boot应用程序之外,还可以为Unix系统创建完全可执行的应用程序。完全可执行的jar可以像任何其他可执行二进制文件一样执行,也可以使用init.d
或注册systemd
。这使得在常见的生产环境中安装和管理Spring Boot应用程序变得非常容易。
完全可执行的jar通过在文件的前面嵌入额外的脚本来工作。目前,某些工具不接受此格式,因此您可能无法始终使用此技术。例如, |
要使用Maven创建“完全可执行”jar,请使用以下插件配置:
<plugin>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-maven-plugin </ artifactId>
<configuration>
<executable> true </ executable>
</ configuration>
</ plugin>
使用Gradle,等效配置为:
springBoot {
executable = true
}
然后,您可以通过键入./my-application.jar
( my-application
您的工件的名称)来运行您的应用程序。包含jar的目录将用作应用程序的工作目录。
60.1支持的操作系统
默认脚本支持大多数Linux发行版,并在CentOS和Ubuntu上进行测试。其他平台,如OS X和FreeBSD,将需要使用自定义 embeddedLaunchScript
。
60.2 Unix/Linux services
Spring Boot application can be easily started as Unix/Linux services using either init.d
or systemd
.
60.2.1 Installation as an init.d service (System V)
If you’ve configured Spring Boot’s Maven or Gradle plugin to generate a fully executable jar, and you’re not using a custom embeddedLaunchScript
, then your application can be used as an init.d
service. Simply symlink the jar to init.d
to support the standard start
, stop
, restart
and status
commands.
The script supports the following features:
- Starts the services as the user that owns the jar file
- Tracks application’s PID using
/var/run/<appname>/<appname>.pid
- Writes console logs to
/var/log/<appname>.log
Assuming that you have a Spring Boot application installed in /var/myapp
, to install a Spring Boot application as an init.d
service simply create a symlink:
$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp
Once installed, you can start and stop the service in the usual way. For example, on a Debian based system:
$ service myapp start
If your application fails to start, check the log file written to |
You can also flag the application to start automatically using your standard operating system tools. For example, on Debian:
$ update-rc.d myapp defaults <priority>
Securing an init.d service
The following is a set of guidelines on how to secure a Spring Boot application that’s being run as an init.d service. It is not intended to be an exhaustive list of everything that should be done to harden an application and the environment in which it runs. |
When executed as root, as is the case when root is being used to start an init.d service, the default executable script will run the application as the user which owns the jar file. You should never run a Spring Boot application as root
so your application’s jar file should never be owned by root. Instead, create a specific user to run your application and use chown
to make it the owner of the jar file. For example:
$ chown bootapp:bootapp your-app.jar
In this case, the default executable script will run the application as the bootapp
user.
为了减少应用程序用户帐户遭到入侵的可能性,您应该考虑阻止它使用登录shell。 |
您还应该采取措施来防止修改应用程序的jar文件。首先,配置其权限,使其无法写入,只能由其所有者读取或执行:
$ chmod 500 your-app.jar
其次,如果您的应用程序或运行它的帐户受到损害,您还应该采取措施限制损害。如果攻击者确实获得了访问权限,他们可以使jar文件可写并更改其内容。防止这种情况的一种方法是使用chattr
以下方法使其不可变:
$ sudo chattr + i your-app.jar
这将阻止任何用户(包括root)修改jar。
如果root用于控制应用程序的服务,并且您 使用.conf
文件来自定义其启动,.conf
则root用户将读取和评估该文件。它应该得到相应的保护。使用,chmod
以便文件只能由所有者读取并用于 chown
使root拥有者:
$ chmod 400 your-app.conf
$ sudo chown root:root your-app.conf
60.2.2作为systemd服务安装
Systemd是System V init系统的后继者,现在许多现代Linux发行版都在使用它。虽然您可以继续使用init.d
脚本systemd
,但也可以使用systemd
“服务”脚本启动Spring Boot应用程序。
假设您安装了Spring Boot应用程序/var/myapp
,要将Spring Boot应用程序安装为systemd
服务,请创建一个myapp.service
使用以下示例命名的脚本并将其放入/etc/systemd/system
目录中:
[单元]
描述的myapp =
之后= syslog.target [服务]
用户的myapp =
ExecStart =的/ var / MyApp的/ myapp.jar
SuccessExitStatus = 143 [安装]
WantedBy = multi-user.target
记住要改变 |
请注意,该 |
Note that unlike when running as an init.d
service, user that runs the application, PID file and console log file are managed by systemd
itself and therefore must be configured using appropriate fields in ‘service’ script. Consult the service unit configuration man page for more details.
To flag the application to start automatically on system boot use the following command:
$ systemctl enable myapp.service
Refer to man systemctl
for more details.
60.2.3 Customizing the startup script
The default embedded startup script written by the Maven or Gradle plugin can be customized in a number of ways. For most people, using the default script along with a few customizations is usually enough. If you find you can’t customize something that you need to, you can always use the embeddedLaunchScript
option to write your own file entirely.
在编写脚本时自定义脚本
在将脚本写入jar文件时自定义启动脚本的元素通常是有意义的。例如,init.d脚本可以提供“描述”,并且由于您事先知道(并且它不会更改),因此您可以在生成jar时提供它。
要自定义书面元素,请使用 embeddedLaunchScriptProperties
option of the Spring Boot Maven or Gradle plugins.
默认脚本支持以下属性替换:
名称 | 描述 |
---|---|
|
脚本模式。默认为 |
|
在 |
|
在 |
|
在 |
|
在 |
|
在 |
|
在 |
|
在 |
|
在 |
|
的默认值 |
|
的默认值 |
|
的默认值 |
|
的默认值 |
|
中的pid文件名的默认值 |
|
如果该 |
|
的默认值 |
运行时自定义脚本
对于在编写jar 之后需要自定义的脚本项,您可以使用环境变量或 配置文件。
默认脚本支持以下环境属性:
变量 | 描述 |
---|---|
|
操作的“模式”。默认值取决于jar的构建方式,但通常是 |
|
如果该 |
|
pid文件夹的根名称( |
|
要放入日志文件的文件夹的名称( |
|
要读取.conf文件的文件夹的名称(默认情况下与jar文件相同)。 |
|
|
|
应用程序的名称。如果从符号链接运行jar,则脚本会猜测应用程序名称,但如果它不是符号链接,或者您希望显式设置应用程序名称,则此操作非常有用。 |
|
传递给程序的参数(Spring Boot应用程序)。 |
|
默认情况下 |
|
启动时传递给JVM的选项。 |
|
jar文件的显式位置,以防脚本用于启动实际上未嵌入的jar。 |
|
如果不为空将 |
|
在强制关闭之前停止应用程序时等待的时间( |
的 |
除了JARFILE
和之外APP_NAME
,可以使用.conf
文件配置上述设置。该文件应该在jar文件旁边,并且具有相同的名称,但后缀为.conf
而不是.jar
。例如,名为jar的jar /var/myapp/myapp.jar
将使用名为的配置文件/var/myapp/myapp.conf
。
myapp.conf。
JAVA_OPTS = -Xmx1024M
LOG_FOLDER = /自定义/日志/文件夹
|
要了解有关正确保护此文件的信息,请参阅 保护init.d服务的准则。
61.接下来要读什么
查看Cloud Foundry, Heroku,OpenShift和 Boxfuse网站,了解有关PaaS可提供的各种功能的更多信息。这些只是四个最受欢迎的Java PaaS提供商,因为Spring Boot非常适合基于云的部署,您也可以*地考虑其他提供商。
接下来的部分将介绍Spring Boot CLI ; 或者你可以跳过阅读有关 构建工具插件的内容。
第七部分。Spring Boot CLI
Spring Boot CLI是一个命令行工具,如果您想使用Spring快速开发,可以使用它。它允许您运行Groovy脚本,这意味着您有一个熟悉的类似Java的语法,没有太多的样板代码。您还可以引导新项目或为其编写自己的命令。
62. Installing the CLI
The Spring Boot CLI can be installed manually; using SDKMAN! (the SDK Manager) or using Homebrew or MacPorts if you are an OSX user. See Section 10.2, “Installing the Spring Boot CLI” in the “Getting started” section for comprehensive installation instructions.
63. Using the CLI
Once you have installed the CLI you can run it by typing spring
. If you run spring
without any arguments, a simple help screen is displayed:
$ spring
usage: spring [--help] [--version]
<command> [<args>] Available commands are: run [options] <files> [--] [args]
Run a spring groovy script ... more command help is shown here
You can use help
to get more details about any of the supported commands. For example:
$ spring help run
spring run - Run a spring groovy script usage: spring run [options] <files> [--] [args] Option Description
------ -----------
--autoconfigure [Boolean] Add autoconfigure compiler
transformations (default: true)
--classpath, -cp Additional classpath entries
-e, --edit Open the file with the default system
editor
--no-guess-dependencies Do not attempt to guess dependencies
--no-guess-imports Do not attempt to guess imports
-q, - quiet安静的日志记录
-v, - verbose详细记录依赖项
解析度
--watch观察指定文件的更改
该version
命令提供了一种快速方法来检查您正在使用的Spring Boot版本。
$ spring版本
Spring CLI v2.0.0.M3
63.1使用CLI运行应用程序
您可以使用该run
命令编译和运行Groovy源代码。Spring Boot CLI是完全独立的,因此您不需要任何外部Groovy安装。
这是一个用Groovy编写的“hello world”Web应用程序示例:
hello.groovy。
@RestController
类 WebApplication { @RequestMapping( “/”)
String home(){
“你好,世界!”
} }
要编译并运行应用程序类型:
$ spring run hello.groovy
要将命令行参数传递给应用程序,您需要使用a --
将它们与“spring”命令参数分开,例如
$ spring run hello.groovy - --server.port = 9000
要设置JVM命令行参数,可以使用JAVA_OPTS
环境变量,例如
$ JAVA_OPTS = -Xmx1024m spring run hello.groovy
63.1.1扣除“抓取”依赖关系
标准Groovy包含一个@Grab
注释,允许您声明对第三方库的依赖性。这种有用的技术允许Groovy以与Maven或Gradle相同的方式下载jar,但不要求你使用构建工具。
Spring Boot进一步扩展了这种技术,并将尝试根据您的代码推断出“抓取”哪些库。例如,由于WebApplication
上面的代码使用 @RestController
注释,因此将抓取“Tomcat”和“Spring MVC”。
以下项目用作“抓取提示”:
项目 | 抓斗 |
---|---|
|
JDBC应用程序。 |
|
JMS应用程序。 |
|
缓存抽象。 |
|
JUnit的。 |
|
RabbitMQ的。 |
|
项目反应堆。 |
扩展 |
Spock测试。 |
|
春批。 |
|
Spring集成。 |
|
Spring Mobile。 |
|
Spring MVC + Embedded Tomcat。 |
|
春季安全。 |
|
春季交易管理。 |
请参阅 |
63.1.2扣除“抓取”坐标
例如,Spring Boot @Grab
允许您指定不带组或版本的依赖项,从而扩展了Groovy的标准支持@Grab('freemarker')
。这将参考Spring Boot的默认依赖关系元数据来推断工件的组和版本。请注意,默认元数据与您正在使用的CLI版本相关联 - 它只会在您移动到新版本的CLI时更改,从而使您可以控制依赖项版本何时更改。可以在附录中找到显示默认元数据中包含的依赖关系及其版本的表。
63.1.3默认导入语句
为了帮助减小Groovy代码的大小,import
自动包含多个语句。请注意上面的示例如何引用@Component
, @RestController
而@RequestMapping
无需使用完全限定的名称或import
语句。
许多Spring注释都可以在不使用 |
63.1.4自动主方法
与等效的Java应用程序不同,您不需要public static void main(String[] args)
在Groovy
脚本中包含 方法。A SpringApplication
是自动创建的,编译后的代码充当 source
。
63.1.5自定义依赖关系管理
默认情况下,CLI使用在spring-boot-dependencies
解析@Grab
依赖项时声明的依赖关系管理。可以使用@DependencyManagementBom
注释配置将覆盖默认依赖关系管理的其他依赖关系管理。注释的值应指定groupId:artifactId:version
一个或多个Maven BOM 的坐标()。
例如,以下声明:
@DependencyManagementBom(“com.example.custom-bom:1.0.0”)
将custom-bom-1.0.0.pom
在Maven存储库中获取 com/example/custom-versions/1.0.0/
。
当指定多个BOM时,它们将按照它们声明的顺序应用。例如:
@DependencyManagementBom([ “com.example.custom-bom:1.0.0”,
“com.example.another-bom:1.0.0” ])
表示依赖项管理another-bom
将覆盖依赖项管理custom-bom
。
但是,您可以@DependencyManagementBom
在任何可以使用的地方使用@Grab
,以确保依赖关系管理的一致排序,您只能@DependencyManagementBom
在应用程序中使用 一次。一个有用的依赖管理源(即Spring Boot的依赖管理的超集)是 Spring IO平台,例如@DependencyManagementBom('io.spring.platform:platform-bom:1.1.2.RELEASE')
。
63.2具有多个源文件的应用程序
您可以对所有接受文件输入的命令使用“shell globbing”。这使您可以轻松地使用单个目录中的多个文件,例如
$ spring run * .groovy
63.3打包您的应用程序
You can use the jar
command to package your application into a self-contained executable jar file. For example:
$ spring jar my-app.jar *.groovy
The resulting jar will contain the classes produced by compiling the application and all of the application’s dependencies so that it can then be run using java -jar
. The jar file will also contain entries from the application’s classpath. You can add explicit paths to the jar using --include
and --exclude
(both are comma-separated, and both accept prefixes to the values “+” and “-” to signify that they should be removed from the defaults). The default includes are
public/**, resources/**, static/**, templates/**, META-INF/**, *
and the default excludes are
.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy
See the output of spring help jar
for more information.
63.4 Initialize a new project
The init
command allows you to create a new project using start.spring.io without leaving the shell. For example:
$ spring init --dependencies=web,data-jpa my-project
Using service at https://start.spring.io
Project extracted to '/Users/developer/example/my-project'
This creates a my-project
directory with a Maven-based project using spring-boot-starter-web
and spring-boot-starter-data-jpa
. You can list the capabilities of the service using the --list
flag
$ spring init --list
=======================================
Capabilities of https://start.spring.io
======================================= Available dependencies:
-----------------------
actuator - Actuator: Production ready features to help you monitor and manage your application
...
web - Web: Support for full-stack web development, including Tomcat and spring-webmvc
websocket - Websocket: Support for WebSocket development
ws - WS: Support for Spring Web Services Available project types:
------------------------
gradle-build - Gradle Config [format:build, build:gradle]
gradle-project - Gradle Project [format:project, build:gradle]
maven-build - Maven POM [format:build, build:maven]
maven-project - Maven Project [format:project, build:maven] (default) ...
The init
command supports many options, check the help
output for more details. For instance, the following command creates a gradle project using Java 8 and war
packaging:
$ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip
Using service at https://start.spring.io
Content saved to 'sample-app.zip'
63.5 Using the embedded shell
Spring Boot includes command-line completion scripts for BASH and zsh shells. If you don’t use either of these shells (perhaps you are a Windows user) then you can use the shell
command to launch an integrated shell.
$ spring shell
Spring Boot (v2.0.0.M3)
Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit.
From inside the embedded shell you can run other commands directly:
$ version
Spring CLI v2.0.0.M3
The embedded shell supports ANSI color output as well as tab
completion. If you need to run a native command you can use the !
prefix. Hitting ctrl-c
will exit the embedded shell.
63.6 Adding extensions to the CLI
You can add extensions to the CLI using the install
command. The command takes one or more sets of artifact coordinates in the format group:artifact:version
. For example:
$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE
In addition to installing the artifacts identified by the coordinates you supply, all of the artifacts' dependencies will also be installed.
To uninstall a dependency use the uninstall
command. As with the install
command, it takes one or more sets of artifact coordinates in the format group:artifact:version
. For example:
$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE
It will uninstall the artifacts identified by the coordinates you supply and their dependencies.
To uninstall all additional dependencies you can use the --all
option. For example:
$ spring uninstall --all
64.使用Groovy bean DSL开发应用程序
Spring Framework 4.0本身支持beans{}
“DSL”(从Grails借用 ),您可以使用相同的格式在Groovy应用程序脚本中嵌入bean定义。这有时是包含中间件声明等外部功能的好方法。例如:
@Configuration
类 Application实现 CommandLineRunner { @Autowired
SharedService服务 @Override
void run(String ... args){
println service.message
} } import my.company.SharedService 豆子 {
service(SharedService){
message = “Hello World”
}
}
您可以将类声明与beans{}
同一文件混合,只要它们保持在顶层,或者如果您愿意,可以将bean DSL放在单独的文件中。
65.使用settings.xml配置CLI
Spring Boot CLI使用Aether,Maven的依赖性解析引擎来解决依赖关系。CLI使用找到的Maven配置~/.m2/settings.xml
来配置Aether。CLI支持以下配置设置:
- 离线
- 镜子
- 服务器
- 代理
-
简介
- 激活
- 库
- 活动档案
有关详细信息,请参阅Maven的设置文档。
66.接下来要读什么
GitHub存储库中提供了一些示例groovy脚本,您可以使用它们来尝试Spring Boot CLI。整个源代码中还有广泛的Javadoc 。
如果您发现自己达到了CLI工具的限制,您可能希望将应用程序转换为完整的Gradle或Maven构建的“groovy项目”。下一节将介绍可与Gradle或Maven一起使用的Spring Boot的 Build工具插件。
第八部分。构建工具插件
Spring Boot为Maven和Gradle提供构建工具插件。这些插件提供了各种功能,包括可执行jar的包装。本节提供有关这两个插件的更多详细信息,以及在需要扩展不受支持的构建系统时的一些帮助。如果您刚刚开始,可能需要先阅读第III部分“使用Spring Boot”部分中的“ 第13章,构建系统 ” 。
67. Spring Boot Maven插件
在春季启动Maven插件提供了Maven的春季启动支持,让你打包可执行的JAR或战争档案和运行“就地”的应用程序。要使用它,您必须使用Maven 3.2(或更好)。
有关完整的插件文档,请参阅Spring Boot Maven插件站点。 |
67.1包括插件
要使用Spring Boot Maven插件,只需在plugins
您的部分中包含相应的XMLpom.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>
<! - ... - >
<build>
<plugins>
<plugin>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-maven-插件</ artifactId>
<version> 2.0.0。M3 </ version>
<executions>
<execution>
<goals>
<goal> repackage </ goal>
</ goals>
</ execution>
</ executions>
</ plugin>
</ plugins>
</ build>
</ project>
此配置将重新打包package
在Maven生命周期阶段构建的jar或war 。以下示例显示了目录中重新打包的jar以及原始jar target
:
$ mvn包
$ ls target / * .jar
target / myproject-1.0.0.jar target / myproject-1.0.0.jar.original
如果您不包含上述<execution/>
配置,则可以单独运行插件(但仅在使用包目标时)。例如:
$ mvn package spring-boot:repackage
$ ls target / * .jar
target / myproject-1.0.0.jar target / myproject-1.0.0.jar.original
If you are using a milestone or snapshot release you will also need to add appropriate pluginRepository
elements:
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
67.2 Packaging executable jar and war files
Once spring-boot-maven-plugin
has been included in your pom.xml
it will automatically attempt to rewrite archives to make them executable using the spring-boot:repackage
goal. You should configure your project to build a jar or war (as appropriate) using the usual packaging
element:
<?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">
<!-- ... -->
<packaging>jar</packaging>
<!-- ... -->
</project>
Your existing archive will be enhanced by Spring Boot during the package
phase. The main class that you want to launch can either be specified using a configuration option, or by adding a Main-Class
attribute to the manifest in the usual way. If you don’t specify a main class the plugin will search for a class with apublic static void main(String[] args)
method.
To build and run a project artifact, you can type the following:
$ mvn package
$ java -jar target/mymodule-0.0.1-SNAPSHOT.jar
To build a war file that is both executable and deployable into an external container you need to mark the embedded container dependencies as “provided”, e.g:
<?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">
<!-- ... -->
<packaging>war</packaging>
<!-- ... -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- ... -->
</dependencies>
</project>
See the “Section 86.1, “Create a deployable war file”” section for more details on how to create a deployable war file. |
Advanced configuration options and examples are available in the plugin info page.
68. Spring Boot Gradle plugin
The Spring Boot Gradle Plugin provides Spring Boot support in Gradle, allowing you to package executable jar or war archives, run Spring Boot applications and use the dependency management provided by spring-boot-dependencies
. It requires Gradle 3.4 or later. Please refer to the plugin’s documentation to learn more:
69. Spring Boot AntLib module
The Spring Boot AntLib module provides basic Spring Boot support for Apache Ant. You can use the module to create executable jars. To use the module you need to declare an additional spring-boot
namespace in your build.xml
:
<project xmlns:ivy="antlib:org.apache.ivy.ant"
xmlns:spring-boot="antlib:org.springframework.boot.ant"
name="myapp" default="build">
...
</project>
You’ll need to remember to start Ant using the -lib
option, for example:
$ ant -lib <folder containing spring-boot-antlib-2.0.0.M3.jar>
The “Using Spring Boot” section includes a more complete example of using Apache Ant with |
69.1 Spring Boot Ant tasks
Once the spring-boot-antlib
namespace has been declared, the following additional tasks are available.
69.1.1 spring-boot:exejar
The exejar
task can be used to creates a Spring Boot executable jar. The following attributes are supported by the task:
Attribute | Description | Required |
---|---|---|
|
The destination jar file to create |
Yes |
|
The root directory of Java class files |
Yes |
|
The main application class to run |
No (default is first class found declaring a |
The following nested elements can be used with the task:
69.1.2例子
指定start-class。
<spring-boot:exejar destfile = “target / my-application.jar”
classes = “target / classes” start-class = “com.foo.MyApplication” >
<resources>
<fileset dir = “src / main / resources” />
</ resources>
<lib>
<fileset dir = “lib” />
</ lib>
</ spring-boot:exejar>
检测初级。
<exejar destfile = “target / my-application.jar” classes = “target / classes” >
<lib>
<fileset dir = “lib” />
</ lib>
</ exejar>
69.2 spring-boot:findmainclass
该findmainclass
任务在内部exejar
用于查找声明a的类 main
。如果需要,您还可以直接在构建中使用此任务。支持以下属性
属性 | 描述 | 需要 |
---|---|---|
|
Java类文件的根目录 |
是(除非 |
|
可用于短路 |
没有 |
|
应该使用结果设置的Ant属性 |
否(如果未指定,将记录结果) |
69.2.1例子
查找并记录。
<findmainclass classesroot = “target / classes” />
查找并设置。
<findmainclass classesroot = “target / classes” property = “main-class” />
覆盖并设置。
<findmainclass mainclass = “com.foo.MainClass” property = “main-class” />
70.支持其他构建系统
如果您想使用Maven,Gradle或Ant以外的构建工具,您可能需要开发自己的插件。可执行jar需要遵循特定的格式,某些条目需要以未压缩的形式编写(有关详细信息,请参阅附录中的 可执行jar格式部分)。
Spring Boot Maven和Gradle插件都可以spring-boot-loader-tools
用来实际生成jar。如果需要,您也可以自己直接使用此库。
70.1重新打包存档
重新打包现有存档,使其成为自包含的可执行存档使用org.springframework.boot.loader.tools.Repackager
。该Repackager
班采取的是指现有的罐子或战争归档单个构造函数的参数。使用两种可用repackage()
方法之一替换原始文件或写入新目标。在重新打包程序运行之前,还可以配置各种设置。
70.2嵌套库
重新打包存档时,可以使用该org.springframework.boot.loader.tools.Libraries
接口包含对依赖项文件的引用 。我们不提供任何具体的实现,Libraries
因为它们通常是特定于系统的。
如果您的存档已包含可以使用的库Libraries.NONE
。
70.3寻找主要班级
如果不使用Repackager.setMainClass()
指定主类,则重新打包程序将使用ASM读取类文件并尝试使用public static void main(String[] args)
方法查找合适的类。如果找到多个候选项,则抛出异常。
70.4重新包装实施示例
以下是典型的重新包装示例:
Repackager repackager = new Repackager(sourceJarFile);
repackager.setBackupSource(假);
repackager.repackage(new Libraries(){
@
Override public void doWithLibraries(LibraryCallback callback)throws IOException {
//构建系统特定的实现,每个依赖的
回调// callback.library(new Library(nestedFile,LibraryScope.COMPILE));
}
});
71.接下来要读什么
如果您对构建工具插件的工作方式感兴趣,可以查看spring-boot-tools
GitHub 上的模块。附录中介绍了可执行jar格式的更多技术细节。
如果您有与构建相关的特定问题,可以查看“操作方法 ”指南。
第九部分。'如何'指南
This section provides answers to some common ‘how do I do that…’ type of questions that often arise when using Spring Boot. This is by no means an exhaustive list, but it does cover quite a lot.
If you are having a specific problem that we don’t cover here, you might want to check out *.com to see if someone has already provided an answer; this is also a great place to ask new questions (please use the spring-boot
tag).
We’re also more than happy to extend this section; If you want to add a ‘how-to’ you can send us a pull request.
72. Spring Boot application
72.1 Create your own FailureAnalyzer
FailureAnalyzer
is a great way to intercept an exception on startup and turn it into a human-readable message, wrapped into a FailureAnalysis
. Spring Boot provides such analyzer for application context related exceptions, JSR-303 validations and more. It is actually very easy to create your own.
AbstractFailureAnalyzer
is a convenient extension of FailureAnalyzer
that checks the presence of a specified exception type in the exception to handle. You can extend from that so that your implementation gets a chance to handle the exception only when it is actually present. If for whatever reason you can’t handle the exception, return null
to give another implementation a chance to handle the exception.
FailureAnalyzer
implementations are to be registered in a META-INF/spring.factories
: the following registers ProjectConstraintViolationFailureAnalyzer
:
org.springframework.boot.diagnostics.FailureAnalyzer=\
com.example.ProjectConstraintViolationFailureAnalyzer
72.2 Troubleshoot auto-configuration
The Spring Boot auto-configuration tries its best to ‘do the right thing’, but sometimes things fail and it can be hard to tell why.
There is a really useful ConditionEvaluationReport
available in any Spring Boot ApplicationContext
. You will see it if you enable DEBUG
logging output. If you use the spring-boot-actuator
there is also an autoconfig
endpoint that renders the report in JSON. Use that to debug the application and see what features have been added (and which not) by Spring Boot at runtime.
Many more questions can be answered by looking at the source code and the Javadoc. Some rules of thumb:
- Look for classes called
*AutoConfiguration
and read their sources, in particular the@Conditional*
annotations to find out what features they enable and when. Add--debug
to the command line or a System property-Ddebug
to get a log on the console of all the auto-configuration decisions that were made in your app. In a running Actuator app look at theautoconfig
endpoint (‘/autoconfig’ or the JMX equivalent) for the same information. - Look for classes that are
@ConfigurationProperties
(e.g.ServerProperties
) and read from there the available external configuration options. The@ConfigurationProperties
has aname
attribute which acts as a prefix to external properties, thusServerProperties
hasprefix="server"
and its configuration properties areserver.port
,server.address
etc. In a running Actuator app look at theconfigprops
endpoint. - Look for uses of the
bind
method on theBinder
to pull configuration values explicitly out of theEnvironment
in a relaxed manner. It is often is used with a prefix. - Look for
@Value
annotations that bind directly to theEnvironment
. - Look for
@ConditionalOnExpression
annotations that switch features on and off in response to SpEL expressions, normally evaluated with placeholders resolved from theEnvironment
.
72.3 Customize the Environment or ApplicationContext before it starts
A SpringApplication
has ApplicationListeners
and ApplicationContextInitializers
that are used to apply customizations to the context or environment. Spring Boot loads a number of such customizations for use internally from META-INF/spring.factories
. There is more than one way to register additional ones:
- Programmatically per application by calling the
addListeners
andaddInitializers
methods onSpringApplication
before you run it. - Declaratively per application by setting
context.initializer.classes
orcontext.listener.classes
. - Declaratively for all applications by adding a
META-INF/spring.factories
and packaging a jar file that the applications all use as a library.
The SpringApplication
sends some special ApplicationEvents
to the listeners (even some before the context is created), and then registers the listeners for events published by the ApplicationContext
as well. See Section 23.5, “Application events and listeners” in the ‘Spring Boot features’ section for a complete list.
It is also possible to customize the Environment
before the application context is refreshed using EnvironmentPostProcessor
. Each implementation should be registered in META-INF/spring.factories
:
org.springframework.boot.env.EnvironmentPostProcessor = com.example.YourEnvironmentPostProcessor
该实现可以加载任意文件并将其添加到Environment
。例如,此示例从类路径加载YAML配置文件:
公共 类 EnvironmentPostProcessorExample 实现 EnvironmentPostProcessor { private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication应用程序){
资源路径= 新的 ClassPathResource(“com / example / myapp / config.yml”);
PropertySource <?> propertySource = loadYaml(path);
。environment.getPropertySources()addlast仅(propertySource);
} private PropertySource <?> loadYaml(资源路径){
if(!path.exists()){
throw new IllegalArgumentException(“Resource” + path + “不存在”);
}
try {
return this .loader.load(“custom-resource”,path,null);
}
catch(IOException ex){
throw new IllegalStateException(
“无法从” + path,ex 加载yaml配置);
}
} }
在 |
虽然使用 |
72.4构建ApplicationContext层次结构(添加父或根上下文)
您可以使用ApplicationBuilder
该类创建父/子ApplicationContext
层次结构。有关详细信息,请参见 “Spring Boot功能”部分中的第23.4节“Fluent构建器API”。
72.5创建非Web应用程序
并非所有Spring应用程序都必须是Web应用程序(或Web服务)。如果要在main
方法中执行某些代码,还要引导Spring应用程序来设置要使用的基础结构,那么使用SpringApplication
Spring Boot 的功能很容易。A 根据是否认为需要Web应用程序来SpringApplication
更改其ApplicationContext
类。您可以做的第一件事就是将servlet API依赖项从类路径中删除。如果你不能这样做(例如你从相同的代码库运行2个应用程序),那么你可以显式调用 setWebEnvironment(false)
你的SpringApplication
实例,或者设置 applicationContextClass
属性(通过Java API或外部属性)。您希望作为业务逻辑运行的应用程序代码可以实现为CommandLineRunner
并作为@Bean
定义放入上下文中。
73.属性和配置
73.1在构建时自动扩展属性
您可以使用现有的构建配置自动扩展它们,而不是对项目的构建配置中指定的某些属性进行硬编码。这在Maven和Gradle都是可行的。
73.1.1使用Maven自动扩展属性
您可以使用资源过滤从Maven项目自动扩展属性。如果你使用,spring-boot-starter-parent
你可以通过@..@
占位符参考你的Maven'项目属性' ,例如
app.encoding =@project.build.sourceEncoding @
app.java.version =@java.version @
The |
If you don’t use the starter parent, in your pom.xml
you need (inside the <build/>
element):
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
and (inside <plugins/>
):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
The |
73.1.2 Automatic property expansion using Gradle
You can automatically expand properties from the Gradle project by configuring the Java plugin’s processResources
task to do so:
processResources {
expand(project.properties)
}
You can then refer to your Gradle project’s properties via placeholders, e.g.
app.name=${name}
app.description=${description}
Gradle’s |
73.2 Externalize the configuration of SpringApplication
A SpringApplication
has bean properties (mainly setters) so you can use its Java API as you create the application to modify its behavior. Or you can externalize the configuration using properties in spring.main.*
. E.g. in application.properties
you might have.
spring.main.web-environment=false
spring.main.banner-mode=off
and then the Spring Boot banner will not be printed on startup, and the application will not be a web application.
The example above also demonstrates how flexible binding allows the use of underscores ( |
Properties defined in external configuration overrides the values specified via the Java API with the notable exception of the sources used to create the ApplicationContext
. Let’s consider this application
new SpringApplicationBuilder()
.bannerMode(Banner.Mode.OFF)
.sources(demo.MyApp.class)
.run(args);
used with the following configuration:
spring.main.sources=com.acme.Config,com.acme.ExtraConfig
spring.main.banner-mode=console
The actual application will now show the banner (as overridden by configuration) and use three sources for the ApplicationContext
(in that order): demo.MyApp
, com.acme.Config
, com.acme.ExtraConfig
.
73.3 Change the location of external properties of an application
By default properties from different sources are added to the Spring Environment
in a defined order (see Chapter 24, Externalized Configuration in the ‘Spring Boot features’ section for the exact order).
A nice way to augment and modify this is to add @PropertySource
annotations to your application sources. Classes passed to the SpringApplication
static convenience methods, and those added using setSources()
are inspected to see if they have @PropertySources
, and if they do, those properties are added to the Environment
early enough to be used in all phases of the ApplicationContext
lifecycle. Properties added in this way have lower priority than any added using the default locations (e.g. application.properties
), system properties, environment variables or the command line.
You can also provide System properties (or environment variables) to change the behavior:
-
spring.config.name
(SPRING_CONFIG_NAME
), defaults toapplication
as the root of the file name. -
spring.config.location
(SPRING_CONFIG_LOCATION
) is the file to load (e.g. a classpath resource or a URL). A separateEnvironment
property source is set up for this document and it can be overridden by system properties, environment variables or the command line.
No matter what you set in the environment, Spring Boot will always load application.properties
as described above. If YAML is used then files with the ‘.yml’ extension are also added to the list by default.
Spring Boot logs the configuration files that are loaded at DEBUG
level and the candidates it has not found at TRACE
level.
See ConfigFileApplicationListener
for more detail.
73.4 Use ‘short’ command line arguments
Some people like to use (for example) --port=9000
instead of --server.port=9000
to set configuration properties on the command line. You can easily enable this by using placeholders in application.properties
, e.g.
server.port=${port:8080}
If you are inheriting from the |
在这种特定情况下,端口绑定将在Heroku和Cloud Foundry等PaaS环境中工作,因为在这两个平台中, |
73.5将YAML用于外部属性
YAML是JSON的超集,因此是一种非常方便的语法,用于以分层格式存储外部属性。例如
spring:
application:
name:
cruncher datasource:
driverClassName:com.mysql.jdbc.Driver
url:jdbc:mysql:// localhost / test
server:
port:9000
创建一个名为的文件application.yml
并将其粘贴到类路径的根目录中,并添加snakeyaml
到依赖项(Maven坐标org.yaml:snakeyaml
,如果使用的话,已包含在内spring-boot-starter
)。YAML文件被解析为Java Map<String,Object>
(如JSON对象),Spring Boot将地图展平,使其深度为1级,并且具有句点分隔键,就像人们习惯使用 Properties
Java中的文件一样。
上面的示例YAML对应于application.properties
文件
spring.application.name =
cruncher spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql:// localhost / test
server.port = 9000
有关YAML的更多信息,请参见“Spring Boot功能”部分中的第24.6节“使用YAML而不是属性”。
73.6设置活动的弹簧配置文件
Spring Environment
有一个API,但通常你会设置一个System属性(spring.profiles.active
)或一个OS环境变量(SPRING_PROFILES_ACTIVE
)。例如,使用-D
参数启动应用程序(记得将它放在主类或jar存档之前):
$ java -jar -Dspring.profiles.active = production demo-0.0.1-SNAPSHOT.jar
在Spring Boot中,您还可以设置活动配置文件application.properties
,例如
spring.profiles.active =生产
以这种方式设置的值将由System属性或环境变量设置替换,但不会由SpringApplicationBuilder.profiles()
方法替换。因此,后一个Java API可用于扩充配置文件而不更改默认值。
有关详细信息,请参见“Spring Boot功能”一节中的第25章“ 配置文件 ”。
73.7根据环境更改配置
YAML文件实际上是由---
行分隔的文档序列,每个文档分别解析为展平的地图。
如果YAML文档包含spring.profiles
密钥,则配置文件值(以逗号分隔的配置文件列表)将被送入Spring Environment.acceptsProfiles()
,如果这些配置文件中的任何配置文件处于活动状态,则该文档将包含在最终合并中(否则不会)。
例:
服务器:
端口:9000
--- spring:
profiles:开发
服务器:
端口:9001 --- spring:
profiles:production
server:
port:0
在此示例中,默认端口为9000,但如果Spring配置文件'development'处于活动状态,则端口为9001,如果'production'处于活动状态,则为0。
YAML文档按它们遇到的顺序合并(因此以后的值会覆盖之前的值)。
要使用属性文件执行相同操作,可以使用它application-${profile}.properties
来指定特定于配置文件的值。
73.8发现外部属性的内置选项
Spring Boot binds external properties from application.properties
(or .yml
) (and other places) into an application at runtime. There is not (and technically cannot be) an exhaustive list of all supported properties in a single location because contributions can come from additional jar files on your classpath.
A running application with the Actuator features has a configprops
endpoint that shows all the bound and bindable properties available through @ConfigurationProperties
.
The appendix includes an application.properties
example with a list of the most common properties supported by Spring Boot. The definitive list comes from searching the source code for @ConfigurationProperties
and @Value
annotations, as well as the occasional use of Binder
.
74. Embedded Web servers
74.1 Use another Web server
The Spring Boot starters bring a default embedded container for you:
-
spring-boot-starter-web
brings Tomcat withspring-boot-starter-tomcat
, butspring-boot-starter-jetty
andspring-boot-starter-undertow
can be used instead. -
spring-boot-starter-webflux
brings Reactor Netty withspring-boot-starter-reactor-netty
, butspring-boot-starter-tomcat
,spring-boot-starter-jetty
andspring-boot-starter-undertow
can be used instead.
Many starters only support Spring MVC, so they transitively bring |
If you choose to use a different HTTP server, you need to exclude those dependencies and include the one you chose instead. Spring Boot provides separate starters for HTTP servers to help make this process as easy as possible.
Example in Maven, for Spring MVC:
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-web </ artifactId>
<exclusions>
<! - 排除Tomcat依赖关系 - >
<exclusion>
<groupId> org .springframework.boot </ groupId>
<artifactId> spring-boot-starter-tomcat </ artifactId>
</ exclusion>
</ exclusions>
</ dependency>
<! - 改用Jetty - >
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-jetty </ artifactId>
</ dependency>
Gradle中的示例,适用于Spring WebFlux:
配置{
//排除Reactor Netty
compile.exclude模块:'spring-boot-starter-reactor-netty'
} 依赖{
编译'org.springframework.boot:spring-boot-starter-webflux'
//使用Undertow
编译'org.springframework.boot:spring-boot-starter-undertow'
// ...
}
|
74.2配置Jetty
一般来说,你可以遵循的建议 第73.8,“探索外部性内置选项”有关 @ConfigurationProperties
(ServerProperties
主要是一个在这里),还看ServletWebServerFactoryCustomizer
。Jetty API非常丰富,因此一旦您有权访问,JettyServletWebServerFactory
您可以通过多种方式对其进行修改。或核选项是添加自己的JettyServletWebServerFactory
。
74.3向应用程序添加Servlet,过滤器或监听器
有两种方法来添加Servlet
,Filter
,ServletContextListener
以及由Servlet规范到您的应用程序支持的其他听众。您可以为它们提供Spring bean,也可以启用Servlet组件的扫描。
74.3.1使用Spring bean添加Servlet,Filter或Listener
要添加Servlet
,Filter
或servlet *Listener
提供@Bean
了它的定义。当您想要注入配置或依赖项时,这非常有用。但是,您必须非常小心,它们不会导致太多其他bean的初始化,因为它们必须在应用程序生命周期的早期安装在容器中(例如,让它们依赖于您DataSource
或JPA 并不是一个好主意)组态)。你可以通过在第一次使用而不是在初始化时懒洋洋地初始化它们来解决这样的限制。
在和的情况下Filters
,Servlets
您还可以通过添加FilterRegistrationBean
或ServletRegistrationBean
替换或替换底层组件来添加映射和init参数。
If no If you are migrating a filter that has no @Bean |
Disable registration of a Servlet or Filter
As described above any Servlet
or Filter
beans will be registered with the servlet container automatically. To disable registration of a particular Filter
or Servlet
bean create a registration bean for it and mark it as disabled. For example:
@Bean
public FilterRegistrationBean registration(MyFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
74.3.2 Add Servlets, Filters, and Listeners using classpath scanning
@WebServlet
, @WebFilter
, and @WebListener
annotated classes can be automatically registered with an embedded servlet container by annotating a @Configuration
class with @ServletComponentScan
and specifying the package(s) containing the components that you want to register. By default, @ServletComponentScan
will scan from the package of the annotated class.
74.4 Change the HTTP port
In a standalone application the main HTTP port defaults to 8080
, but can be set with server.port
(e.g. in application.properties
or as a System property). Thanks to relaxed binding of Environment
values you can also use SERVER_PORT
(e.g. as an OS environment variable).
To switch off the HTTP endpoints completely, but still create a WebApplicationContext
, use server.port=-1
(this is sometimes useful for testing).
For more details look at Section 27.4.4, “Customizing embedded servlet containers” in the ‘Spring Boot features’ section, or the ServerProperties
source code.
74.5 Use a random unassigned HTTP port
To scan for a free port (using OS natives to prevent *es) use server.port=0
.
74.6 Discover the HTTP port at runtime
You can access the port the server is running on from log output or from the ServletWebServerApplicationContext
via its EmbeddedWebServer
. The best way to get that and be sure that it has initialized is to add a @Bean
of type ApplicationListener<ServletWebServerInitializedEvent>
and pull the container out of the event when it is published.
Tests that use @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
can also inject the actual port into a field using the @LocalServerPort
annotation. For example:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class MyWebIntegrationTests { @Autowired
ServletWebServerApplicationContext server; @LocalServerPort
int port; // ... }
|
74.7 Configure SSL
SSL can be configured declaratively by setting the various server.ssl.*
properties, typically in application.properties
or application.yml
. For example:
server.port=8443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=secret
server.ssl.key-password=another-secret
See Ssl
for details of all of the supported properties.
Using configuration like the example above means the application will no longer support plain HTTP connector at port 8080. Spring Boot doesn’t support the configuration of both an HTTP connector and an HTTPS connector via application.properties
. If you want to have both then you’ll need to configure one of them programmatically. It’s recommended to use application.properties
to configure HTTPS as the HTTP connector is the easier of the two to configure programmatically. See the spring-boot-sample-tomcat-multi-connectors
sample project for an example.
74.8 Configure Access Logging
Access logs can be configured for Tomcat, Undertow and Jetty via their respective namespaces.
For instance, the following logs access on Tomcat with a custom pattern.
server.tomcat.basedir=my-tomcat
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms)
The default location for logs is a |
Access logging for undertow can be configured in a similar fashion
server.undertow.accesslog.enabled=true
server.undertow.accesslog.pattern=%t %a "%r" %s (%D ms)
Logs are stored in a logs
directory relative to the working directory of the application. This can be customized via server.undertow.accesslog.directory
.
Finally, access logging for jetty can also be configured that way:
server.jetty.accesslog.enabled=true
server.jetty.accesslog.filename=/var/log/jetty-access.log
By default, logs will be redirected to System.err
. For more details, please refer to the documentation.
74.9 Use behind a front-end proxy server
您的应用程序可能需要发送302
重定向或使用绝对链接呈现内容。在代理后面运行时,调用者需要指向代理的链接,而不是托管应用程序的计算机的物理地址。通常,这种情况通过与代理的合同来处理,代理将添加标题以告知后端如何构建自身链接。
如果代理添加了常规X-Forwarded-For
和X-Forwarded-Proto
标题(大多数是开箱即用的),绝对链接应该正确呈现,只要 在您的server.use-forward-headers
设置true
中application.properties
。
如果您的应用程序在Cloud Foundry或Heroku中运行,则 |
74.9.1自定义Tomcat的代理配置
如果您使用的是Tomcat,则还可以配置用于携带“转发”信息的标头名称:
server.tomcat.remote-IP头= X-您的远程-IP头
server.tomcat.protocol头= X-您的协议报头
Tomcat还配置了一个默认的正则表达式,该表达式匹配要信任的内部代理。默认情况下,IP地址中10/8
,192.168/16
, 169.254/16
和127/8
是值得信赖的。您可以通过添加条目来自定义阀门的配置application.properties
,例如
server.tomcat.internal的代理= 192 \\。168 \\。\\ d {1,3} \\。\\ d {1,3}
只有在使用属性文件进行配置时才需要双反斜杠。如果您使用YAML,则单个反斜杠就足够了,并且该值等于上面显示的值 |
您可以通过将其设置 |
您可以RemoteIpValve
通过关闭自动关闭(即设置server.use-forward-headers=false
)并在TomcatServletWebServerFactory
bean中添加新的阀门实例来完全控制Tomcat的配置。
74.10配置Tomcat
一般来说,你可以从以下建议 第73.8,“探索外部性内置选项”有关 @ConfigurationProperties
(ServerProperties
主要是一个在这里),还要看看ServletWebServerFactoryCustomizer
各种针对Tomcat *Customizers
,您可以在其中的一个补充。Tomcat API非常丰富,因此一旦您有权访问,TomcatServletWebServerFactory
您可以通过多种方式对其进行修改。或核选项是添加自己的TomcatServletWebServerFactory
。
74.11使用Tomcat启用多个连接器
Add a org.apache.catalina.connector.Connector
to the TomcatServletWebServerFactory
which can allow multiple connectors, e.g. HTTP and HTTPS connector:
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat;
} private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = new ClassPathResource("keystore").getFile();
File truststore = new ClassPathResource("keystore").getFile();
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
return connector;
}
catch (IOException ex) {
throw new IllegalStateException("can't access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
74.12 Use Tomcat’s LegacyCookieProcessor
The embedded Tomcat used by Spring Boot does not support "Version 0" of the Cookie format out of the box, and you may see the following error:
java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value
If at all possible, you should consider updating your code to only store values compliant with later Cookie specifications. If, however, you’re unable to change the way that cookies are written, you can instead configure Tomcat to use a LegacyCookieProcessor
. To switch to the LegacyCookieProcessor
use anServletWebServerFactoryCustomizer
bean that adds a TomcatContextCustomizer
:
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
return (serverFactory) -> serverFactory.addContextCustomizers(
(context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
}
74.13 Configure Undertow
Generally you can follow the advice from Section 73.8, “Discover built-in options for external properties” about @ConfigurationProperties
(ServerProperties
and ServerProperties.Undertow
are the main ones here), but also look at ServletWebServerFactoryCustomizer
. Once you have access to theUndertowServletWebServerFactory
you can use an UndertowBuilderCustomizer
to modify Undertow’s configuration to meet your needs. Or the nuclear option is to add your own UndertowServletWebServerFactory
.
74.14 Enable Multiple Listeners with Undertow
Add an UndertowBuilderCustomizer
to the UndertowServletWebServerFactory
and add a listener to the Builder
:
@Bean
public UndertowServletWebServerFactory servletWebServerFactory() {
UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { @Override
public void customize(Builder builder) {
builder.addHttpListener(8080, "0.0.0.0");
} });
return factory;
}
74.15 Create WebSocket endpoints using @ServerEndpoint
If you want to use @ServerEndpoint
in a Spring Boot application that used an embedded container, you must declare a single ServerEndpointExporter
@Bean
:
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
This bean will register any @ServerEndpoint
annotated beans with the underlying WebSocket container. When deployed to a standalone servlet container this role is performed by a servlet container initializer and the ServerEndpointExporter
bean is not required.
74.16 Enable HTTP response compression
HTTP response compression is supported by Jetty, Tomcat, and Undertow. It can be enabled via application.properties
:
server.compression.enabled=true
By default, responses must be at least 2048 bytes in length for compression to be performed. This can be configured using the server.compression.min-response-size
property.
By default, responses will only be compressed if their content type is one of the following:
text/html
text/xml
text/plain
text/css
This can be configured using the server.compression.mime-types
property.
75. Spring MVC
75.1 Write a JSON REST service
Any Spring @RestController
in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath. For example:
@RestController
public class MyController { @RequestMapping("/thing")
public MyThing thing() {
return new MyThing();
} }
As long as MyThing
can be serialized by Jackson2 (e.g. a normal POJO or Groovy object) then localhost:8080/thing
will serve a JSON representation of it by default. Sometimes in a browser you might see XML responses because browsers tend to send accept headers that prefer XML.
75.2 Write an XML REST service
If you have the Jackson XML extension (jackson-dataformat-xml
) on the classpath, it will be used to render XML responses and the very same example as we used for JSON would work. To use it, add the following dependency to your project:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
You may also want to add a dependency on Woodstox. It’s faster than the default StAX implementation provided by the JDK and also adds pretty print support and improved namespace handling:
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
</dependency>
If Jackson’s XML extension is not available, JAXB (provided by default in the JDK) will be used, with the additional requirement to have MyThing
annotated as@XmlRootElement
:
@XmlRootElement
public class MyThing {
private String name;
// .. getters and setters
}
To get the server to render XML instead of JSON you might have to send an Accept: text/xml
header (or use a browser).
75.3 Customize the Jackson ObjectMapper
Spring MVC (client and server side) uses HttpMessageConverters
to negotiate content conversion in an HTTP exchange. If Jackson is on the classpath you already get the default converter(s) provided by Jackson2ObjectMapperBuilder
, an instance of which is auto-configured for you.
The ObjectMapper
(or XmlMapper
for Jackson XML converter) instance created by default has the following customized properties:
-
MapperFeature.DEFAULT_VIEW_INCLUSION
is disabled -
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
is disabled
Spring Boot has also some features to make it easier to customize this behavior.
You can configure the ObjectMapper
and XmlMapper
instances using the environment. Jackson provides an extensive suite of simple on/off features that can be used to configure various aspects of its processing. These features are described in six enums in Jackson which map onto properties in the environment:
Jackson enum | Environment property |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
For example, to enable pretty print, set spring.jackson.serialization.indent_output=true
. Note that, thanks to the use of relaxed binding, the case of indent_output
doesn’t have to match the case of the corresponding enum constant which is INDENT_OUTPUT
.
This environment-based configuration is applied to the auto-configured Jackson2ObjectMapperBuilder
bean, and will apply to any mappers created using the builder, including the auto-configured ObjectMapper
bean.
The context’s Jackson2ObjectMapperBuilder
can be customized by one or more Jackson2ObjectMapperBuilderCustomizer
beans. Such customizer beans can be ordered and Boot’s own customizer has an order of 0, allowing additional customization to be applied both before and after Boot’s customization.
Any beans of type com.fasterxml.jackson.databind.Module
will be automatically registered with the auto-configured Jackson2ObjectMapperBuilder
and applied to any ObjectMapper
instances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application.
If you want to replace the default ObjectMapper
completely, either define a @Bean
of that type and mark it as @Primary
, or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder
@Bean
. Note that in either case this will disable all auto-configuration of the ObjectMapper
.
If you provide any @Beans
of type MappingJackson2HttpMessageConverter
then they will replace the default value in the MVC configuration. Also, a convenience bean is provided of type HttpMessageConverters
(always available if you use the default MVC configuration) which has some useful methods to access the default and user-enhanced message converters.
See also the Section 75.4, “Customize the @ResponseBody rendering” section and the WebMvcAutoConfiguration
source code for more details.
75.4 Customize the @ResponseBody rendering
Spring uses HttpMessageConverters
to render @ResponseBody
(or responses from @RestController
). You can contribute additional converters by simply adding beans of that type in a Spring Boot context. If a bean you add is of a type that would have been included by default anyway (like MappingJackson2HttpMessageConverter
for JSON conversions) then it will replace the default value. A convenience bean is provided of type HttpMessageConverters
(always available if you use the default MVC configuration) which has some useful methods to access the default and user-enhanced message converters (useful, for example if you want to manually inject them into a custom RestTemplate
).
As in normal MVC usage, any WebMvcConfigurer
beans that you provide can also contribute converters by overriding the configureMessageConverters
method, but unlike with normal MVC, you can supply only additional converters that you need (because Spring Boot uses the same mechanism to contribute its defaults). Finally, if you opt-out of the Spring Boot default MVC configuration by providing your own @EnableWebMvc
configuration, then you can take control completely and do everything manually using getMessageConverters
from WebMvcConfigurationSupport
.
See the WebMvcAutoConfiguration
source code for more details.
75.5 Handling Multipart File Uploads
Spring Boot embraces the Servlet 3 javax.servlet.http.Part
API to support uploading files. By default Spring Boot configures Spring MVC with a maximum file of 1MB per file and a maximum of 10MB of file data in a single request. You may override these values, as well as the location to which intermediate data is stored (e.g., to the /tmp
directory) and the threshold past which data is flushed to disk by using the properties exposed in the MultipartProperties
class. If you want to specify that files be unlimited, for example, set the spring.servlet.multipart.max-file-size
property to -1
.
The multipart support is helpful when you want to receive multipart encoded file data as a @RequestParam
-annotated parameter of type MultipartFile
in a Spring MVC controller handler method.
See the MultipartAutoConfiguration
source for more details.
75.6关闭Spring MVC DispatcherServlet
Spring Boot希望从应用程序的根目录中提供所有内容/
。如果您希望将自己的servlet映射到该URL,则可以执行此操作,但当然您可能会丢失其他一些Boot MVC功能。要添加自己的servlet并将其映射到根资源,只需声明一个@Bean
类型Servlet
并为其指定特殊的bean名称 dispatcherServlet
(如果要将其关闭而不替