赞
踩
Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch, Andy Wilkinson, Marcel Overdijk, Christian Dupuis, Sébastien Deleuze, Michael Simons, VedranPavić, Jay Bryant, Madhura Bhave
2.1.0.BUILD-SNAPSHOT
版权(2012-2018年)
本文件的副本可供你自己使用及分发给他人,但你无须就该等副本收取任何费用,而每一份副本均须载有本版权公告,不论是以印刷形式或以电子方式分发。
目录
11.3.1@RestController和@Requestmap注释
11.3.2@EnableAutoConfiguration注释
23.8使用ApplicationRunner或CommandLineRunner
24.7.5@ConfigurationProperties验证
24.7.6@ConfigurationProperties与@Value
27.1.9 ConfigurableWebBindingInitiators
27.2.2带有HttpMessageReader和HttpMessageWriters的HTTP编解码器
27.4.3 ServletWebServerApplicationContext
44.3.24使用Spock测试SpringBoot应用程序
44.4.1 ConfigFileApplicationContextInitiizer
52.8.4自动配置的ReactiveHealthIndicator
72.2 spring-boot:findmainclass
75.3在环境或ApplicationContext启动之前定制它
75.4构建ApplicationContext层次结构(添加父上下文或根上下文)
77.10.1使用SpringBean添加servlet、过滤器或侦听器
77.10.2使用Classpath扫描添加servlet、过滤器和侦听器
77.14使用Tomcat的LegacyCookieProcessor
77.16使用@ServerEndpoint创建WebSocketEndpoint
78.6关闭SpringMVC DispatcherServlet
88.2更改UserDetailsService并添加用户帐户
90.8远程调试从Maven启动的SpringBoot应用程序
90.9在不使用Ant的情况下从Ant构建可执行存档spring-boot-antlib
本节简要概述SpringBoot参考文档。它用作文档其余部分的地图。
SpringBoot参考指南如下所示
最新的副本可在docs.spring.io/spring-boot/docs/current/reference.
本文件的副本可供你自己使用及分发给他人,但你无须就该等副本收取任何费用,而每一份副本均须载有本版权公告,不论是以印刷形式或以电子方式分发。
如果你对SpringBoot有问题,我们愿意帮忙。
spring-boot
.![]() |
所有SpringBoot都是开源的,包括文档。如果你发现文档有问题,或者你想改进它们,请介入. |
如果您要开始使用SpringBoot或“Spring”,请从以下主题:
准备好真正开始使用SpringBoot了吗?我们保护了你:
需要更多关于SpringBoot核心功能的详细信息吗?以下内容是给您的:
当您准备将SpringBoot应用程序推向生产时,我们有一些技巧你可能会喜欢:
最后,我们为更高级的用户提供了一些主题:
如果您要开始使用SpringBoot或一般的“Spring”,请从阅读本节开始。它回答了基本的“什么?”“怎么做”还有“为什么”问题。它包括对SpringBoot的介绍,以及安装说明。然后,我们将引导您构建您的第一个SpringBoot应用程序,同时讨论一些核心原则。
SpringBoot使得创建独立的、生产级的基于Spring的应用程序变得很容易,您可以运行这些应用程序。我们对Spring平台和第三方库有一个独断专行的看法,这样您就可以最小的小题大做开始了。大多数SpringBoot应用程序只需要很少的Spring配置。
可以使用SpringBoot创建可以通过以下方式启动的Java应用程序java -jar
或者更传统的战争部署。我们还提供了一个运行“Spring脚本”的命令行工具。
我们的主要目标是:
SpringBoot2.1.0 BUILD-快照要求Java 8或9和Spring Framework 5.1.0.RELEASE或者更高。
为下列构建工具提供了显式构建支持:
构建工具 | 版本 |
---|---|
马文 | 3.3+ |
梯度 | 4.4+ |
SpringBoot支持以下嵌入式servlet容器:
名字,姓名 | Servlet版本 |
---|---|
Tomcat 9.0 | 4.0 |
Jetty 9.4 | 3.1 |
Undertow 2.0 | 4.0 |
您还可以将SpringBoot应用程序部署到任何与Servlet3.1+兼容的容器中。
SpringBoot可以与“经典”Java开发工具一起使用,也可以作为命令行工具安装。不管怎样,你需要Java SDK v1.8或者更高。在开始之前,应该使用以下命令检查当前的Java安装:
$ java -version
如果您是Java开发新手,或者您想尝试SpringBoot,您可能需要尝试弹簧启动CLI(命令行接口)。否则,继续阅读“经典”安装说明。
您可以与任何标准Java库相同的方式使用SpringBoot。为此,请包括适当的spring-boot-*.jar
你的类路径上的文件。SpringBoot不需要任何特殊的工具集成,所以您可以使用任何IDE或文本编辑器。此外,SpringBoot应用程序没有什么特别之处,因此您可以像其他Java程序一样运行和调试SpringBoot应用程序。
虽然你能复制SpringBootJars,我们通常建议您使用支持依赖管理(如Maven或Gradle)的构建工具。
SpringBoot与ApacheMaven 3.3或更高版本兼容。如果您还没有安装Maven,可以按照maven.apache.org.
![]() |
在许多操作系统上,Maven可以安装包管理器。如果您使用OSX自制,请尝试 |
Spring引导依赖项使用org.springframework.boot
groupId
。通常,Maven POM文件从spring-boot-starter-parent
项目并将依赖项声明为一个或多个。“起步者”。SpringBoot还提供了一个可选的Maven插件若要创建可执行的JAR,请执行以下操作。
下面的清单显示了一个典型的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>
-
- <!-- Inherit defaults from Spring Boot -->
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.0.BUILD-SNAPSHOT</version>
- </parent>
-
- <!-- Add typical dependencies for a web application -->
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- </dependencies>
-
- <!-- Package as an executable jar -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- <!-- Add Spring repositories -->
- <!-- (you don't need this if you are using a .RELEASE version) -->
- <repositories>
- <repository>
- <id>spring-snapshots</id>
- <url>https://repo.spring.io/snapshot</url>
- <snapshots><enabled>true</enabled></snapshots>
- </repository>
- <repository>
- <id>spring-milestones</id>
- <url>https://repo.spring.io/milestone</url>
- </repository>
- </repositories>
- <pluginRepositories>
- <pluginRepository>
- <id>spring-snapshots</id>
- <url>https://repo.spring.io/snapshot</url>
- </pluginRepository>
- <pluginRepository>
- <id>spring-milestones</id>
- <url>https://repo.spring.io/milestone</url>
- </pluginRepository>
- </pluginRepositories>
- </project>

![]() |
这,这个,那,那个 |
SpringBoot与Gradle 4.4及更高版本兼容。如果您还没有安装Gradle,可以按照gradle.org.
属性可以声明Spring启动依赖项。org.springframework.boot
group
。通常,项目将依赖项声明为一个或多个。“起步者”。Spring Boot提供了一个有用的Gradle插件它可以用来简化依赖声明和创建可执行的JAR。
梯度包装
当您需要构建一个项目时,Gradle包装提供了一种很好的“获取”Gradle的方法。这是一个很小的脚本和库,您可以将其与代码一起用于引导构建过程。看见docs.gradle.org/4.2.1/userguide/gradle_wrapper.html关于细节。
下面的示例显示了一个典型的build.gradle
档案:
buildscript { repositories { jcenter() maven { url 'https://repo.spring.io/snapshot' } maven { url 'https://repo.spring.io/milestone' } } dependencies { classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.1.0.BUILD-SNAPSHOT' } } apply plugin: 'java' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' jar { baseName = 'myproject' version = '0.0.1-SNAPSHOT' } repositories { jcenter() maven { url "https://repo.spring.io/snapshot" } maven { url "https://repo.spring.io/milestone" } } dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("org.springframework.boot:spring-boot-starter-test") }
SpringBootCLI(命令行接口)是一个命令行工具,您可以使用它快速地使用Spring进行原型。它让你跑Groovy脚本,这意味着您有一个熟悉的类似Java的语法,而没有那么多样板代码。
您不需要使用CLI来使用SpringBoot,但这绝对是获得Spring应用程序的最快方法。
您可以从Spring软件存储库下载SpringCLI发行版:
刀刃快照分布也是可用的。
下载后,按照INSTALL.txt解压档案的说明。总之,有一个spring
脚本(spring.bat
)中的bin/
目录中的.zip
档案。或者,您可以使用java -jar
带着.jar
文件(脚本帮助您确保正确设置了类路径)。
SDKMAN!(SoftwareDevelopmentKitManager)可用于管理各种二进制SDK的多个版本,包括Groovy和SpringBootCLI。去找SDKMAN!从…sdkman.io并使用以下命令安装SpringBoot:
- $ sdk install springboot
- $ spring --version
- Spring Boot v2.1.0.BUILD-SNAPSHOT
如果您为CLI开发特性并希望轻松访问您构建的版本,请使用以下命令:
- $ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.1.0.BUILD-SNAPSHOT-bin/spring-2.1.0.BUILD-SNAPSHOT/
- $ sdk default springboot dev
- $ spring --version
- Spring CLI v2.1.0.BUILD-SNAPSHOT
的本地实例spring
称为dev
举个例子。它指向您的目标构建位置,所以每次您重建SpringBoot时,spring
是最新的。
通过运行以下命令可以看到它:
- $ sdk ls springboot
-
- ================================================================================
- Available Springboot Versions
- ================================================================================
- > + dev
- * 2.1.0.BUILD-SNAPSHOT
-
- ================================================================================
- + - local version
- * - installed
- > - currently in use
- ================================================================================
如果你在mac上使用自制,可以使用以下命令安装SpringBootCLI:
- $ brew tap pivotal/tap
- $ brew install springboot
自制安装spring
到/usr/local/bin
.
![]() |
如果您没有看到公式,您的BREW安装可能是过时的。在这种情况下,运行 |
如果你在mac上使用麦克波特,可以使用以下命令安装SpringBootCLI:
$ sudo port install spring-boot-cli
SpringBootCLI包括为巴什和兹什贝壳。你可以的。source
脚本(也称为spring
)在任何shell中,或将其放在个人或系统范围内的bash完成初始化中。在debian系统上,系统范围内的脚本位于/shell-completion/bash
当一个新的shell启动时,该目录中的所有脚本都会被执行。例如,如果通过使用SDKMAN安装了脚本,则手动运行脚本!,使用以下命令:
- $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring
- $ spring <HIT TAB HERE>
- grab help jar run test version
![]() |
如果使用HOMEBREW或MacPorts安装SpringBootCLI,命令行完成脚本将自动注册到shell中。 |
如果您在Windows上并使用铲子,可以使用以下命令安装SpringBootCLI:
- > scoop bucket add extras
- > scoop install springboot
铲斗安装spring
到~/scoop/apps/springboot/current/bin
.
![]() |
如果您没有看到应用程序清单,您安装的独家新闻可能是过时的。在这种情况下,运行 |
您可以使用下面的web应用程序来测试您的安装。首先,创建一个名为app.groovy
,如下:
- @RestController
- class ThisWillActuallyRun {
-
- @RequestMapping("/")
- String home() {
- "Hello World!"
- }
-
- }
然后从shell运行它,如下所示:
$ spring run app.groovy
![]() |
随着依赖项的下载,应用程序的第一次运行是缓慢的。随后的运行要快得多。 |
打开localhost:8080
在你最喜欢的网页浏览器里。您应该看到以下输出:
Hello World!
如果您正在从SpringBoot的早期版本进行升级,请检查项目wiki的“迁移指南”这提供了详细的升级说明。也检查“发布说明”关于每个版本的“新的和值得注意的”特性的列表。
升级到新的特性发行版时,一些属性可能已被重命名或删除。SpringBoot提供了一种在启动时分析应用程序环境和打印诊断信息的方法,但也为您提供了在运行时临时迁移属性的方法。若要启用该功能,请向项目中添加以下依赖项:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-properties-migrator</artifactId>
- <scope>runtime</scope>
- </dependency>
![]() |
晚添加到环境中的属性,例如当使用 |
![]() |
完成迁移后,请确保从项目的依赖项中删除此模块。 |
若要升级现有的CLI安装,请使用适当的包管理器命令(例如,brew upgrade
)或者,如果手动安装了CLI,请按照标准指令,请记住更新PATH
环境变量以删除任何旧的引用。
本节描述如何开发一个简单的“HelloWorld!”Web应用程序,它突出了SpringBoot的一些关键特性。我们使用Maven构建这个项目,因为大多数IDE都支持它。
![]() |
这,这个,那,那个spring.io网站包含许多“入门”导轨使用Spring Boot。如果你需要解决一个具体的问题,首先检查那里。 您可以通过以下步骤转到start.spring.io并从依赖项搜索器中选择“Web”启动器。这样做会生成一个新的项目结构,这样您就可以立即开始编码。检查SpringInitializr文档更多细节。 |
在开始之前,打开一个终端并运行以下命令,以确保安装了有效版本的Java和Maven:
- $ java -version
- java version "1.8.0_102"
- Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
- Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
- $ mvn -v
- Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00)
- Maven home: /usr/local/Cellar/maven/3.3.9/libexec
- Java version: 1.8.0_102, vendor: Oracle Corporation
![]() |
此示例需要在自己的文件夹中创建。后续说明假设您已经创建了一个合适的文件夹,并且它是您的当前目录。 |
我们需要从创建一个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.1.0.BUILD-SNAPSHOT</version>
- </parent>
-
- <!-- Additional lines to be added here... -->
-
- <!-- (you don't need this if you are using a .RELEASE version) -->
- <repositories>
- <repository>
- <id>spring-snapshots</id>
- <url>https://repo.spring.io/snapshot</url>
- <snapshots><enabled>true</enabled></snapshots>
- </repository>
- <repository>
- <id>spring-milestones</id>
- <url>https://repo.spring.io/milestone</url>
- </repository>
- </repositories>
- <pluginRepositories>
- <pluginRepository>
- <id>spring-snapshots</id>
- <url>https://repo.spring.io/snapshot</url>
- </pluginRepository>
- <pluginRepository>
- <id>spring-milestones</id>
- <url>https://repo.spring.io/milestone</url>
- </pluginRepository>
- </pluginRepositories>
- </project>

上面的清单应该为您提供一个工作构建。您可以通过运行mvn package
(现在,您可以忽略“jar将为空-没有标记为包含的内容!”警告)。
![]() |
此时,您可以将项目导入IDE(大多数现代Java IDE都包括对Maven的内置支持)。为了简单起见,我们继续为这个示例使用纯文本编辑器。 |
SpringBoot提供了许多“启动器”,允许您在类路径中添加罐子。我们的示例应用程序已经使用了spring-boot-starter-parent
在.。parent
POM的章节。这,这个,那,那个spring-boot-starter-parent
是一个特殊的启动程序,它提供了有用的Maven默认值。它还提供了一个dependency-management
节,以便您可以省略version
标记用于“祝福”依赖项。
其他“启动程序”提供了您在开发特定类型应用程序时可能需要的依赖项。因为我们正在开发一个web应用程序,所以我们添加了一个spring-boot-starter-web
依赖。在此之前,我们可以通过运行以下命令查看我们目前拥有的内容:
- $ mvn dependency:tree
-
- [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服务器和SpringBoot本身。
要完成我们的应用程序,我们需要创建一个Java文件。默认情况下,Maven从src/main/java
,所以您需要创建该文件夹结构,然后添加一个名为src/main/java/Example.java
若要包含以下代码,请执行以下操作:
import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.web.bind.annotation.*; @RestController @EnableAutoConfiguration public class Example { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(Example.class, args); } }
虽然这里没有太多的代码,但是正在发生很多事情。在接下来的几节中,我们将逐步了解重要的部分。
我们的第一个注释Example
类是@RestController
。这被称为刻板印象注释它为阅读代码的人和Spring提供了提示,说明类扮演了特定的角色。在这种情况下,我们的类是一个web。@Controller
,所以Spring在处理传入的Web请求时会考虑它。
这,这个,那,那个@RequestMapping
注释提供“路由”信息。它告诉Spring,任何带有/
路径应映射到home
方法。这,这个,那,那个@RestController
注释告诉Spring将结果字符串直接呈现给调用者。
![]() |
这,这个,那,那个 |
第二个类级注释是@EnableAutoConfiguration
。这个注释告诉SpringBoot根据您添加的JAR依赖项“猜测”如何配置Spring。自spring-boot-starter-web
加上Tomcat和SpringMVC,自动配置假设您正在开发一个Web应用程序,并相应地设置Spring。
启动器和自动配置
自动配置被设计为与“启动器”很好地工作,但这两个概念并不是直接联系在一起的。您可以在启动程序之外自由选择JAR依赖项。SpringBoot仍然尽力自动配置您的应用程序。
应用程序的最后一部分是main
方法。这只是应用程序入口点遵循Java约定的一个标准方法。我们的主要方法委托给SpringBootSpringApplication
通过调用run
.SpringApplication
引导我们的应用程序,启动Spring,然后启动自动配置的Tomcat Web服务器。我们需要通过Example.class
作为对run
告知方法SpringApplication
这是主要的Spring组件。这,这个,那,那个args
数组也被传递到公开任何命令行参数。
此时,您的应用程序应该可以工作。因为你用了spring-boot-starter-parent
波姆,你有个有用的run
可以用来启动应用程序的目标。类型mvn spring-boot:run
从根项目目录中启动应用程序。您应该看到类似于以下内容的输出:
- $ mvn spring-boot:run
-
- . ____ _ __ _ _
- /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
- ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
- \\/ ___)| |_)| | | | | || (_| | ) ) ) )
- ' |____| .__|_| |_|_| |_\__, | / / / /
- =========|_|==============|___/=/_/_/_/
- :: Spring Boot :: (v2.1.0.BUILD-SNAPSHOT)
- ....... . . .
- ....... . . . (log output here)
- ....... . . .
- ........ Started Example in 2.222 seconds (JVM running for 6.514)
如果您打开web浏览器到localhost:8080
,您将看到以下输出:
Hello World!
若要优雅地退出应用程序,请按ctrl-c
.
我们通过创建一个可以在生产中运行的完全独立的可执行JAR文件来完成我们的示例。可执行的JAR(有时称为“FAT JAR”)是包含编译类以及代码运行所需的所有JAR依赖项的档案。
可执行JAR和Java
Java没有提供加载嵌套JAR文件的标准方法(JAR文件本身包含在JAR中)。如果您希望分发一个独立的应用程序,这可能会有问题。
为了解决这个问题,许多开发人员使用“uber”JAR。一个uberjar将所有应用程序依赖项中的所有类打包到一个归档文件中。这种方法的问题是很难看出应用程序中有哪些库。如果在多个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 package
-
- [INFO] Scanning for projects...
- [INFO]
- [INFO] ------------------------------------------------------------------------
- [INFO] Building myproject 0.0.1-SNAPSHOT
- [INFO] ------------------------------------------------------------------------
- [INFO] .... ..
- [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
- [INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
- [INFO]
- [INFO] --- spring-boot-maven-plugin:2.1.0.BUILD-SNAPSHOT:repackage (default) @ myproject ---
- [INFO] ------------------------------------------------------------------------
- [INFO] BUILD SUCCESS
- [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在SpringBoot重新打包之前创建的原始JAR文件。
若要运行该应用程序,请使用java -jar
命令如下:
- $ java -jar target/myproject-0.0.1-SNAPSHOT.jar
-
- . ____ _ __ _ _
- /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
- ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
- \\/ ___)| |_)| | | | | || (_| | ) ) ) )
- ' |____| .__|_| |_|_| |_\__, | / / / /
- =========|_|==============|___/=/_/_/_/
- :: Spring Boot :: (v2.1.0.BUILD-SNAPSHOT)
- ....... . . .
- ....... . . . (log output here)
- ....... . . .
- ........ Started Example in 2.536 seconds (JVM running for 2.864)
如前所述,要退出应用程序,请按ctrl-c
.
希望本节提供了一些SpringBoot基础知识,并帮助您编写自己的应用程序。如果您是面向任务的开发人员,您可能需要跳到spring.io看看其中的一些开始解决具体问题的指南“我如何用Spring实现这一点?”问题。我们也有SpringBoot特有的“如何“参考文件。
这,这个,那,那个弹簧启动库也有一个一堆样本你可以跑了。示例独立于代码的其余部分(也就是说,您不需要构建其余的代码来运行或使用示例)。
否则,下一个逻辑步骤是读取第三部分,“使用Spring Boot”。如果你真的不耐烦的话,你也可以跳到前面去读。弹簧启动功能.
本节将详细介绍如何使用SpringBoot。它涵盖了一些主题,如构建系统、自动配置以及如何运行应用程序。我们还介绍了一些SpringBoot最佳实践。虽然SpringBoot没有什么特别之处(它只是您可以使用的另一个库),但是下面有一些建议可以使您的开发过程更容易一些。
如果您是从SpringBoot开始的,您可能应该阅读开始在潜入这一段之前,导游。
强烈建议您选择支持依赖性管理这可以使用发布到“Maven Central”存储库的工件。我们建议您选择Maven或Gradle。让SpringBoot与其他构建系统(例如Ant)一起工作是可能的,但它们并不是特别受支持的。
SpringBoot的每个版本都提供了它支持的依赖项的管理列表。实际上,您不需要在构建配置中为这些依赖项中的任何一个提供版本,因为SpringBoot为您管理这些依赖关系。升级SpringBoot本身时,这些依赖项也会以一致的方式升级。
![]() |
如果需要,仍然可以指定版本并覆盖SpringBoot的建议。 |
管理列表包含了您可以在SpringBoot中使用的所有Spring模块,以及一个完善的第三方库列表。该列表可作为标准提供。物料清单(spring-boot-dependencies
)两者都可以使用的马文和梯度.
![]() |
SpringBoot的每个版本都与Spring框架的一个基本版本相关联。我们高度建议您不要指定其版本。 |
Maven用户可以从spring-boot-starter-parent
项目以获得合理的默认值。父项目提供以下特性:
repackage
目标带着repackage
行刑证明。application.properties
和application.yml
包括特定于配置文件的文件(例如,application-dev.properties
和application-dev.yml
)注意,因为application.properties
和application.yml
文件接受Spring样式占位符(${…}
),则将Maven筛选更改为使用@..@
占位符。(您可以通过设置名为resource.delimiter
.)
将项目配置为从spring-boot-starter-parent
,设置parent
详情如下:
- <!-- Inherit defaults from Spring Boot -->
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.0.BUILD-SNAPSHOT</version>
- </parent>
![]() |
您应该只需在此依赖项上指定SpringBoot版本号。如果您导入其他启动程序,则可以安全地省略版本号。 |
使用该设置,还可以通过重写自己项目中的属性来覆盖各个依赖项。例如,要升级到另一个Spring数据发布培训,您可以将以下内容添加到您的pom.xml
:
- <properties>
- <spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
- </properties>
![]() |
检查 |
不是每个人都喜欢从spring-boot-starter-parent
波姆。您可能需要使用自己的企业标准父级,或者您可能更愿意显式声明所有Maven配置。
如果您不想使用spring-boot-starter-parent
,仍然可以保留依赖关系管理(但不是插件管理)的好处,方法是使用scope=import
依赖性如下:
- <dependencyManagement>
- <dependencies>
- <dependency>
- <!-- Import dependency management from Spring Boot -->
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- <version>2.1.0.BUILD-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
如前所述,前面的示例设置不允许您使用属性覆盖单个依赖项。要达到同样的结果,您需要在dependencyManagement
你的项目以前这,这个,那,那个spring-boot-dependencies
入场。例如,要升级到另一个Spring数据发布培训,可以向您的pom.xml
:
- <dependencyManagement>
- <dependencies>
- <!-- Override Spring Data release train provided by Spring Boot -->
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-releasetrain</artifactId>
- <version>Fowler-SR2</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- <version>2.1.0.BUILD-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>

![]() |
在前面的示例中,我们指定了BOM,但是任何依赖类型都可以相同的方式被重写。 |
弹簧启动包括一个Maven插件它可以将项目打包为可执行的JAR。将插件添加到您的<plugins>
如果您想使用它,如下面的示例所示:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
![]() |
如果您使用SpringBootStart父pom,则只需要添加插件。除非您想要更改父级中定义的设置,否则不需要配置它。 |
要了解如何在Gradle中使用SpringBoot,请参阅SpringBoot的Gradle插件的文档:
可以使用ApacheAnt+Ivy构建SpringBoot项目。这,这个,那,那个spring-boot-antlib
“AntLib”模块还可以帮助Ant创建可执行的JAR。
要声明依赖项,典型的ivy.xml
文件如下所示:
- <ivy-module version="2.0">
- <info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
- <configurations>
- <conf name="compile" description="everything needed to compile this module" />
- <conf name="runtime" extends="compile" description="everything needed to run this module" />
- </configurations>
- <dependencies>
- <dependency 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="2.1.0.BUILD-SNAPSHOT" />
-
- <target name="resolve" description="--> retrieve dependencies with ivy">
- <ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
- </target>
-
- <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>

![]() |
如果您不想使用 |
Starters是一组方便的依赖描述符,可以包含在应用程序中。您可以为您需要的所有Spring和相关技术提供一站式服务,而无需搜索示例代码和复制粘贴大量的依赖描述符。例如,如果您想开始使用Spring和JPA进行数据库访问,请将spring-boot-starter-data-jpa
项目中的依赖项。
启动程序包含许多依赖项,您需要这些依赖项才能使项目快速启动和运行,并且具有一致的、受支持的托管传递依赖关系集。
名字里有什么
全官初学者遵循类似的命名模式;spring-boot-starter-*
,在哪里*
是一种特殊类型的应用程序。当您需要找到启动器时,此命名结构旨在帮助您。许多IDE中的Maven集成允许您按名称搜索依赖项。例如,安装了适当的Eclipse或STS插件后,可以按ctrl-space
在POM编辑器中键入“Spring-boot-starter”以获得完整的列表。
如“创建自己的初学者“第三部分,第三人不应以spring-boot
,因为它是为官方的SpringBoot文物保留的。相反,第三方启动程序通常以项目名称开始。例如,一个第三方启动项目称为thirdpartyproject
通常被命名为thirdpartyproject-spring-boot-starter
.
下面的应用程序启动程序由SpringBoot在org.springframework.boot
小组:
表13.1.弹簧启动应用程序启动器
名字,姓名 | 描述 | 波姆 |
---|---|---|
| 核心启动程序,包括自动配置支持、日志记录和YAML。 | |
| 使用ApacheActiveMQ启动JMS消息传递 | |
| 使用SpringAMQP和兔子MQ的启动器 | |
| 使用SpringAOP和AspectJ进行面向方面的编程 | |
| 使用ApacheArtemis启动JMS消息传递 | |
| 弹簧批次起动器 | |
| 开始使用Spring框架的缓存支持 | |
| 使用SpringCloud连接器的初学者,它简化了云平台(如CloudFoundry和Heroku)中的服务连接 | |
| 开始使用Cassandra分布式数据库和Spring数据Cassandra | |
| 使用Cassandra分布式数据库和Spring数据的启动器-Cassandra反应性 | |
| 开始使用Couchbase面向文档的数据库和Spring数据库 | |
| 开始使用面向Couchbase文档的数据库和SpringDataCouchbase反应性 | |
| 使用弹性搜索和分析引擎及Spring数据弹性搜索的启动器 | |
| 使用Spring数据JDBC的启动程序 | |
| Spring数据JPA与Hibernate的启动 | |
| 开始使用Spring数据LDAP | |
| 开始使用MongoDB面向文档的数据库和Spring数据MongoDB | |
| MongoDB面向文档数据库和Spring数据的启动 | |
| Neo4j图形数据库和Spring数据Neo4j的启动 | |
| 启动使用Redis键值数据存储与Spring数据Redis和生菜客户端 | |
| 启动使用Redis键值数据存储与SpringDataRedisReactiveand生菜客户端 | |
| 开始使用Spring数据REST在REST上公开Spring数据存储库 | |
| Apache Solr搜索平台与Spring数据Solr的启动 | |
| 使用FreeMarker视图构建MVC Web应用程序的入门 | |
| 使用Groovy模板视图构建MVC Web应用程序的入门 | |
| 用SpringMVC和SpringHATEOA构建基于超媒体的RESTfulweb应用程序 | |
| 使用Spring集成的启动器 | |
| 与HikariCP连接池一起使用JDBC的启动程序 | |
| 使用JAX-RS和泽西岛构建RESTful Web应用程序的初学者。替代物 | |
| 开始使用jOOQ访问SQL数据库。替代物 | |
| 读写入门 | |
| 使用Atomikos启动JTA事务 | |
| 使用Bitronix启动JTA事务 | |
| 启动使用Java邮件和Spring框架的电子邮件发送支持 | |
| 使用胡子视图构建Web应用程序的初学者 | |
| 使用SpringSecurity的OAuth2/OpenID连接客户端特性的启动器 | |
| 使用Quartz调度程序的启动程序 | |
| 使用Spring安全性的启动器 | |
| 使用包括JUnit、Hamcrest和Mockito在内的库测试SpringBoot应用程序的初学者 | |
| 使用Thymeleaf视图构建MVC Web应用程序的入门 | |
| JavaBean验证与Hibernate验证器的启动 | |
| 使用SpringMVC构建Web应用程序,包括RESTful应用程序。使用Tomcat作为默认的嵌入式容器。 | |
| 启动使用SpringWeb服务 | |
| 使用Spring框架的反应性Web支持构建WebFlux应用程序的初学者 | |
| 使用Spring框架的WebSocket支持构建WebSocket应用程序的初学者 |
除了应用程序启动程序之外,还可以使用以下启动程序添加生产准备特征:
表13.2.弹簧启动生产启动器
名字,姓名 | 描述 | 波姆 |
---|---|---|
| 使用SpringBootActuator的初学者,它提供生产准备功能,帮助您监视和管理应用程序 |
最后,SpringBoot还包括以下启动程序,如果要排除或交换特定的技术方面,可以使用这些启动程序:
表13.3.弹簧启动技术启动器
名字,姓名 | 描述 | 波姆 |
---|---|---|
| 开始使用Jetty作为嵌入式servlet容器。替代物 | |
| 开始使用Log4j2进行日志记录。替代物 | |
| 使用Logback开始日志记录。默认日志起动器 | |
| 开始使用反应堆Netty作为嵌入式反应HTTP服务器。 | |
| 开始使用Tomcat作为嵌入式servlet容器。使用的默认servlet容器启动器 | |
| 作为嵌入式servlet容器的启动程序。替代物 |
![]() |
有关其他社区贡献者的列表,请参见自述文件在.。 |
SpringBoot不需要任何特定的代码布局才能工作。然而,有一些最佳实践是有帮助的。
类不包括package
声明,它被认为是在“默认包”中。通常不鼓励使用“默认包”,应该避免使用。它可能会给SpringBoot应用程序带来特殊问题,这些应用程序使用@ComponentScan
, @EntityScan
,或@SpringBootApplication
注释,因为每个JAR中的每个类都会被读取。
![]() |
我们建议您遵循Java推荐的包命名约定,并使用反向域名(例如, |
我们通常建议您将主应用程序类定位在根包中,而不是其他类。这,这个,那,那个@SpringBootApplication
注记通常放在主类中,并且它隐式地定义了特定项的基本“搜索包”。例如,如果您正在编写JPA应用程序,则@SpringBootApplication
带注释的类用于搜索@Entity
物品。使用根包还允许组件扫描只应用于项目。
![]() |
如果你不想用 |
下面的清单显示了一个典型的布局:
com +- example +- myapplication +- Application.java | +- customer | +- Customer.java | +- CustomerController.java | +- CustomerService.java | +- CustomerRepository.java | +- order +- Order.java +- OrderController.java +- OrderService.java +- OrderRepository.java
这,这个,那,那个Application.java
文件将声明main
方法,以及@SpringBootApplication
,如下:
- package com.example.myapplication;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
-
- @SpringBootApplication
- public class Application {
-
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
-
- }
Spring Boot支持基于Java的配置。虽然可以使用SpringApplication
对于xml源,我们通常建议您的主源是一个@Configuration
班级,等级通常定义main
方法是一种很好的候选方法。@Configuration
.
![]() |
许多使用XML配置的Spring配置示例已经在Internet上发布。如果可能,请始终尝试使用等效的基于Java的配置。寻觅 |
你不需要把你所有的@Configuration
变成一个班级。这,这个,那,那个@Import
注释可用于导入其他配置类。或者,您可以使用@ComponentScan
自动获取所有Spring组件,包括@Configuration
上课。
如果您绝对必须使用基于xml的配置,我们建议您仍然从@Configuration
班级,等级然后,您可以使用@ImportResource
注释以加载XML配置文件。
SpringBoot自动配置尝试根据您添加的JAR依赖关系自动配置Spring应用程序。例如,如果HSQLDB
在类路径上,并且没有手动配置任何数据库连接bean,那么SpringBoot自动配置内存中的数据库。
您需要通过添加@EnableAutoConfiguration
或@SpringBootApplication
中的一个注释@Configuration
上课。
![]() |
你只应该加一个 |
自动配置是非侵入性的。在任何时候,您都可以开始定义自己的配置来替换自动配置的特定部分。例如,如果添加自己的DataSource
bean,默认的嵌入式数据库支持将不再支持。
如果您需要了解当前应用的是什么自动配置,以及为什么应用程序,请使用--debug
切换。这样做可以为选定的核心记录器启用调试日志,并将条件报告记录到控制台。
如果发现正在应用不希望应用的特定自动配置类,则可以使用@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
财产。
![]() |
您可以在注释级别和通过使用属性定义排除。 |
您可以使用任何标准的SpringFramework技术来定义bean及其注入的依赖项。为了简单起见,我们经常发现@ComponentScan
(找到您的bean)并使用@Autowired
(进行构造函数注入)工作得很好。
如果按照上面的建议构造代码(将应用程序类定位在根包中),则可以添加@ComponentScan
没有任何争论。所有应用程序组件(@Component
, @Service
, @Repository
, @Controller
自动注册为Springbean。
下面的示例显示@Service
bean,它使用构造函数注入来获得所需的RiskAssessor
豆子:
package com.example.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DatabaseAccountService implements AccountService { private final RiskAssessor riskAssessor; @Autowired public DatabaseAccountService(RiskAssessor riskAssessor) { this.riskAssessor = riskAssessor; } // ... }
如果bean有一个构造函数,则可以省略@Autowired
,如以下示例所示:
- @Service
- public class DatabaseAccountService implements AccountService {
-
- private final RiskAssessor riskAssessor;
-
- public DatabaseAccountService(RiskAssessor riskAssessor) {
- this.riskAssessor = riskAssessor;
- }
-
- // ...
-
- }
![]() |
注意如何使用构造函数注入使 |
许多SpringBoot开发人员喜欢他们的应用程序使用自动配置、组件扫描,并且能够在他们的“应用程序类”上定义额外的配置。单曲@SpringBootApplication
可以使用注释来启用这三个特性,即:
@EnableAutoConfiguration
*启用弹簧启动自动配置机构@ComponentScan
*启用@Component
扫描应用程序所在的包(请参阅最佳做法)@Configuration
允许在上下文中注册额外的bean或导入其他配置类这,这个,那,那个@SpringBootApplication
注释相当于使用@Configuration
, @EnableAutoConfiguration
,和@ComponentScan
使用它们的默认属性,如下面的示例所示:
- package com.example.myapplication;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
-
- @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
- public class Application {
-
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
-
- }
![]() |
|
![]() |
这些特性中没有一个是强制性的,您可以选择用它所启用的任何特性来替换这个单个注释。例如,您可能不希望在应用程序中使用组件扫描: 在这个例子中, |
将应用程序打包为JAR并使用嵌入式HTTP服务器的最大优点之一是可以像运行其他应用程序一样运行应用程序。调试SpringBoot应用程序也很容易。您不需要任何特殊的IDE插件或扩展。
![]() |
本节仅涉及基于JAR的包装。如果选择将应用程序打包为WAR文件,则应参考服务器和IDE文档。 |
您可以从IDE作为一个简单的Java应用程序运行SpringBoot应用程序。但是,您首先需要导入项目。导入步骤因IDE和生成系统而异。大多数IDE可以直接导入Maven项目。例如,Eclipse用户可以选择Import…
→ Existing Maven Projects
从File
菜单。
如果不能直接将项目导入IDE,则可以使用构建插件生成IDE元数据。Maven包括用于月食和理念。Gradle为各种IDE.
![]() |
如果您意外地运行了两个web应用程序,您会看到一个“端口已经在使用”错误。STS用户可以使用 |
如果使用SpringBootMaven或Gradle插件创建可执行JAR,则可以使用java -jar
,如以下示例所示:
$ java -jar target/myapplication-0.0.1-SNAPSHOT.jar
还可以在启用远程调试支持的情况下运行打包应用程序。这样做可以将调试器附加到打包的应用程序,如下面的示例所示:
- $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
- -jar target/myapplication-0.0.1-SNAPSHOT.jar
SpringBootMaven插件包括一个run
可用于快速编译和运行应用程序的目标。应用程序以爆炸性的形式运行,就像它们在您的IDE中所做的那样。下面的示例显示了运行SpringBoot应用程序的典型Maven命令:
$ mvn spring-boot:run
您可能还需要使用MAVEN_OPTS
操作系统环境变量,如以下示例所示:
$ export MAVEN_OPTS=-Xmx1024m
SpringBootGradle插件还包括bootRun
可用于以爆炸性形式运行应用程序的任务。这,这个,那,那个bootRun
当您应用org.springframework.boot
和java
插件,如以下示例所示:
$ gradle bootRun
您可能还需要使用JAVA_OPTS
操作系统环境变量,如以下示例所示:
$ export JAVA_OPTS=-Xmx1024m
由于SpringBoot应用程序只是普通的Java应用程序,因此JVM热交换应该是现成的。JVM热交换在一定程度上受到了它可以替换的字节码的限制。为了更完整的解决方案,贾贝尔可以使用。
这,这个,那,那个spring-boot-devtools
模块还包括对快速应用程序重新启动的支持。见第20章,开发工具本章后面的一节以及热腾腾的“如何-到”关于细节。
SpringBoot包括一组额外的工具,这些工具可以使应用程序开发体验更加愉快。这,这个,那,那个spring-boot-devtools
模块可以包含在任何项目中,以提供额外的开发时特性。要包含DevTools支持,请将模块依赖项添加到您的构建中,如Maven和Gradle的以下清单所示:
梅文。
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <optional>true</optional>
- </dependency>
- </dependencies>
格拉德尔。
- dependencies {
- compile("org.springframework.boot:spring-boot-devtools")
- }
![]() |
在运行完整打包的应用程序时,将自动禁用开发工具。如果您的应用程序是从 |
![]() |
默认情况下,重新打包的档案不包含DevTools。如果您想使用某些远程DevTools功能,则需要禁用 |
SpringBoot支持的几个库使用缓存来提高性能。例如模板引擎缓存已编译模板,以避免重复解析模板文件。此外,SpringMVC可以在提供静态资源时向响应添加HTTP缓存头。
虽然缓存在生产中非常有益,但它在开发过程中可能会适得其反,从而阻止您看到您刚才在应用程序中所做的更改。因此,Springboot-DevTools默认禁用缓存选项。
缓存选项通常由application.properties
档案。例如,Thymeleaf提供spring.thymeleaf.cache
财产。不需要手动设置这些属性,spring-boot-devtools
模块自动应用合理的开发时间配置。
因为您在开发SpringMVC和SpringWebFlux应用程序时需要更多关于Web请求的信息,所以开发人员工具将启用DEBUG
的日志记录。web
伐木组。这将为您提供有关传入请求、正在处理它的处理程序、响应结果等方面的信息。如果希望记录所有请求详细信息(包括潜在敏感信息),可以打开spring.http.log-request-details
配置属性。
![]() |
如果不希望应用属性默认值,则可以设置 |
![]() |
有关DevTools应用的属性的完整列表,请参见DevToolsPropertyDefaultsPostProcessor. |
使用spring-boot-devtools
每当类路径上的文件发生更改时,都会自动重新启动。在IDE中工作时,这可能是一个有用的特性,因为它为代码更改提供了一个非常快速的反馈循环。默认情况下,指向文件夹的类路径上的任何条目都会被监视更改。注意,某些资源,如静态资产和视图模板,不需要重新启动应用程序。.
触发重新启动
在DevTools监视类路径资源时,触发重新启动的唯一方法是更新类路径。导致类路径更新的方式取决于您正在使用的IDE。在Eclipse中,保存修改后的文件将导致类路径被更新并触发重新启动。在IntelliJ IDEA中,构建项目(Build -> Build Project
)具有相同的效果。
![]() |
只要启用了分叉,您也可以使用支持的构建插件(Maven和Gradle)启动应用程序,因为DevTools需要一个独立的应用程序类加载程序才能正常运行。默认情况下,Gradle和Maven在类路径上检测DevTools时会这样做。 |
![]() |
当与LiveReload一起使用时,自动重新启动工作非常好。参见LiveReload部分关于细节。如果使用JRebel,则禁用自动重新启动以支持动态类重新加载。其他DevTools特性(如LiveReload和PropertyOverrids)仍然可以使用。 |
![]() |
DevTools依赖于应用程序上下文的关机钩子来关闭它。如果禁用了关机挂钩( |
![]() |
在决定类路径上的条目是否应该在更改时触发重新启动时,DevTools会自动忽略名为 |
![]() |
DevTools需要自定义 |
重新启动VS Reload
SpringBoot提供的重新启动技术通过使用两个类加载器来工作。不更改的类(例如,来自第三方JAR的类)被加载到底座类加载器。正在积极开发的类被加载到重新启动类加载器。重新启动应用程序时,重新启动类加载器被丢弃,并创建一个新的类加载器。这种方法意味着应用程序重新启动通常比“冷启动”快得多,因为底座类加载器已经可用并已填充。
如果发现重新启动对应用程序来说不够快,或者遇到类加载问题,则可以考虑重新加载技术,例如贾贝尔来自ZeroTurn的。这些工作是通过在加载类时重写类来完成的,以使它们更易于重新加载。
默认情况下,每次应用程序重新启动时,都会记录一个显示条件评估增量的报告。报告显示了在进行更改时对应用程序的自动配置所做的更改,例如添加或删除bean以及设置配置属性。
若要禁用报表的日志记录,请设置以下属性:
spring.devtools.restart.log-condition-evaluation-delta=false
某些资源在更改时不一定需要触发重新启动。例如,Thymeleaf模板可以就地编辑.默认情况下,更改/META-INF/maven
, /META-INF/resources
, /resources
, /static
, /public
,或/templates
不会触发重新启动,但会触发活重装。如果要自定义这些排除,可以使用spring.devtools.restart.exclude
财产。例如,仅排除/static
和/public
您将设置以下属性:
spring.devtools.restart.exclude=static/**,public/**
![]() |
如果你想保留这些默认值加其他排除,请使用 |
您可能希望在对不位于类路径上的文件进行更改时重新启动或重新加载应用程序。若要这样做,请使用spring.devtools.restart.additional-paths
属性配置其他路径以监视更改。您可以使用spring.devtools.restart.exclude
财产前文描述若要控制附加路径下的更改是否触发完全重新启动或活重装.
如果不想使用重新启动功能,可以使用spring.devtools.restart.enabled
财产。在大多数情况下,您可以在application.properties
(这样做仍然初始化重新启动类加载器,但它不监视文件更改)。
如果你需要完全地禁用重新启动支持(例如,因为它不适用于特定的库),您需要设置spring.devtools.restart.enabled
System
财产false
在打电话之前SpringApplication.run(…)
,如以下示例所示:
- public static void main(String[] args) {
- System.setProperty("spring.devtools.restart.enabled", "false");
- SpringApplication.run(MyApp.class, args);
- }
如果您使用持续编译更改文件的IDE,则可能希望只在特定时间触发重新启动。为此,您可以使用“触发器文件”,这是一个特殊的文件,当您想要实际触发重新启动检查时,必须修改该文件。更改文件只会触发检查,只有在DevTools检测到必须做什么时才会重新启动。触发器文件可以手动更新,也可以使用IDE插件更新。
若要使用触发器文件,请将spring.devtools.restart.trigger-file
属性设置为触发器文件的路径。
![]() |
你可能想要设置 |
如前面所述,重新启动VS Reload节中,重新启动功能是通过使用两个类加载器实现的。对于大多数应用程序来说,这种方法工作得很好。但是,它有时会导致类加载问题。
默认情况下,IDE中的任何打开项目都带有“重新启动”类加载器和任何常规的类加载器。.jar
使用“基本”类加载器加载文件。如果您在一个多模块项目上工作,而且不是每个模块都导入到您的IDE中,那么您可能需要定制一些东西。为此,您可以创建一个META-INF/spring-devtools.properties
档案。
这,这个,那,那个spring-devtools.properties
文件可以包含以restart.exclude
和restart.include
。这,这个,那,那个include
元素是应该拖放到“重新启动”类加载器中的项,并且exclude
元素是应该向下推到“基本”类加载器中的项。属性的值是应用于类路径的regex模式,如下面的示例所示:
- restart.exclude.companycommonlibs=/mycorp-common-[\\w-]+\.jar
- restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar
![]() |
所有属性键必须是唯一的。只要财产开始于 |
![]() |
全 |
重新启动功能不能很好地处理使用标准反序列化的对象。ObjectInputStream
。如果需要反序列化数据,则可能需要使用Spring的ConfigurableObjectInputStream
结合在一起Thread.currentThread().getContextClassLoader()
.
不幸的是,一些第三方库在不考虑上下文类加载器的情况下反序列化.如果发现这样的问题,则需要向原始作者请求修复。
这,这个,那,那个spring-boot-devtools
模块包括嵌入式LiveReload服务器,该服务器可用于在资源更改时触发浏览器刷新。LiveReload浏览器扩展可以免费提供给Chrome、Firefox和Safarilivereload.com.
如果不希望在应用程序运行时启动LiveReload服务器,则可以将spring.devtools.livereload.enabled
财产false
.
![]() |
一次只能运行一个LiveReload服务器。在启动应用程序之前,请确保没有其他LiveReload服务器正在运行。如果您从IDE启动多个应用程序,那么只有第一个应用程序具有LiveReload支持。 |
可以通过添加名为.spring-boot-devtools.properties
敬你的$HOME
文件夹(请注意文件名以“.”开头)。添加到此文件的任何属性都应用于全使用DevTools的机器上的SpringBoot应用程序。例如,要将重新启动配置为始终使用触发文件,您将添加以下属性:
~/.Spring-boot-devtools.properties。
spring.devtools.reload.trigger-file=.reloadtrigger
SpringBootDeveloper工具并不局限于本地开发。在远程运行应用程序时,还可以使用几个特性。远程支持是可选的。要启用它,您需要确保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
属性设置。必须手动启动客户端组件。
远程客户端应用程序设计为在IDE中运行。你得跑org.springframework.boot.devtools.RemoteSpringApplication
具有与所连接的远程项目相同的类路径。应用程序唯一需要的参数是它所连接的远程URL。
例如,如果您正在使用Eclipse或STS,并且您有一个名为my-app
您已经部署到CloudFoundry,您将执行以下操作:
Run Configurations…
从Run
菜单。Java Application
“发射配置”。my-app
项目。org.springframework.boot.devtools.RemoteSpringApplication
作为主修班。https://myapp.cfapps.io
到Program arguments
(或者不管您的远程URL是什么)。正在运行的远程客户端可能类似于以下清单:
- . ____ _ __ _ _
- /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \
- ( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \
- \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) )
- ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / /
- =========|_|==============|___/===================================/_/_/_/
- :: Spring Boot Remote :: 2.1.0.BUILD-SNAPSHOT
-
- 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)
![]() |
由于远程客户端使用的类路径与实际应用程序相同,因此可以直接读取应用程序属性。这就是为什么 |
![]() |
使用总是明智的。 |
![]() |
如果需要使用代理访问远程应用程序,请配置 |
远程客户端监视应用程序类路径的更改,方式与局部重启。任何更新的资源都被推送到远程应用程序中,并且(如有需要)触发重新启动。如果您在使用本地没有的云服务的特性上进行迭代,这可能会很有帮助。通常,远程更新和重新启动要比完整的重建和部署周期快得多。
![]() |
只有在远程客户端运行时才监视文件。如果在启动远程客户端之前更改文件,则不会将其推送到远程服务器。 |
可执行的JAR可用于生产部署。由于它们是独立的,所以它们也非常适合基于云的部署。
要获得额外的“生产准备”功能,如健康、审核和度量REST或jmx端点,请考虑添加spring-boot-actuator
。看见第五部分,“SpringBoot执行器:可生产的特性”关于细节。
现在您应该了解如何使用SpringBoot和应该遵循的一些最佳实践。现在您可以继续了解弹簧启动功能或者你可以跳过前面读到“生产准备“春靴的各个方面。
本节讨论SpringBoot的细节。在这里,您可以了解您可能希望使用和自定义的关键特性。如果您还没有这样做,您可能需要阅读“第二部分,“开始”“和”第三部分,“使用Spring Boot”“章节,让你有一个良好的基础。
这,这个,那,那个SpringApplication
类提供了一种方便的方法来引导从main()
方法。在许多情况下,您可以委托给静态SpringApplication.run
方法,如以下示例所示:
- public static void main(String[] args) {
- SpringApplication.run(MySpringConfiguration.class, args);
- }
当应用程序启动时,您应该会看到类似于以下输出的内容:
- . ____ _ __ _ _
- /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
- ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
- \\/ ___)| |_)| | | | | || (_| | ) ) ) )
- ' |____| .__|_| |_|_| |_\__, | / / / /
- =========|_|==============|___/=/_/_/_/
- :: Spring Boot :: v2.1.0.BUILD-SNAPSHOT
-
- 2013-07-31 00:08:16.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)
- 2013-07-31 00:08:16.166 INFO 56603 --- [ main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
- 2014-03-04 13:09:54.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080
- 2014-03-04 13:09:56.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658)
默认情况下,INFO
将显示日志消息,包括一些相关的启动细节,例如启动应用程序的用户。如果您需要日志级别而不是INFO
,您可以设置它,如第26.4节,“日志水平”,
如果您的应用程序无法启动,请注册FailureAnalyzers
有机会提供一条专门的错误消息和解决问题的具体操作。例如,如果您在端口上启动web应用程序8080
而且该端口已经在使用中,您应该会看到类似于以下消息的内容:
- ***************************
- APPLICATION FAILED TO START
- ***************************
-
- Description:
-
- Embedded servlet container failed to start. Port 8080 was already in use.
-
- Action:
-
- Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
![]() |
Spring Boot提供了许多 |
如果没有故障分析器能够处理异常,则仍然可以显示完整的条件报告,以更好地了解错误所在。要做到这一点,你需要启用debug
财产或使能DEBUG
测井为org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
.
例如,如果您正在运行您的应用程序,则使用java -jar
,您可以启用debug
财产如下:
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
在启动时打印的横幅可以通过添加banner.txt
文件到类路径中,或者通过设置spring.banner.location
属性设置为这样一个文件的位置。如果文件具有utf-8以外的编码,则可以设置spring.banner.charset
。除了文本文件之外,还可以添加banner.gif
, banner.jpg
,或banner.png
图像文件到类路径或设置spring.banner.image.location
财产。图像被转换成ASCII艺术表示法,并打印在任何文字横幅之上。
在你的banner.txt
文件中,可以使用下列任何占位符:
表23.1.横幅变量
变量 | 描述 |
---|---|
| 应用程序的版本号,如 |
| 应用程序的版本号,如 |
| 您正在使用的SpringBoot版本。例如 |
| 您所使用的SpringBoot版本,格式化为显示(用括号包围,前缀为 |
| 哪里 |
| 您的应用程序的标题,如 |
![]() |
这,这个,那,那个 |
您还可以使用spring.main.banner-mode
属性以确定是否必须在其上打印横幅。System.out
(console
),发送到配置的记录器(log
),或根本不生产(off
).
打印的横幅以下列名称注册为单例bean:springBootBanner
.
![]() |
YAML地图 |
如果SpringApplication
默认值并不适合您的口味,您可以创建一个本地实例并对其进行自定义。例如,要关闭横幅,可以编写:
- public static void main(String[] args) {
- SpringApplication app = new SpringApplication(MySpringConfiguration.class);
- app.setBannerMode(Banner.Mode.OFF);
- app.run(args);
- }
![]() |
传递给 |
还可以配置SpringApplication
通过使用application.properties
档案。看见第24章,外化配置关于细节。
有关配置选项的完整列表,请参见SpringApplication
Javadoc.
如果您需要构建一个ApplicationContext
层次结构(具有父/子关系的多个上下文),或者如果您更喜欢使用“流利”构建器API,则可以使用SpringApplicationBuilder
.
这,这个,那,那个SpringApplicationBuilder
让您将多个方法调用链接在一起,并包括parent
和child
允许您创建层次结构的方法,如以下示例所示:
- new SpringApplicationBuilder()
- .sources(Parent.class)
- .child(Application.class)
- .bannerMode(Banner.Mode.OFF)
- .run(args);
![]() |
创建 |
除了常见的Spring框架事件之外,例如ContextRefreshedEvent
..SpringApplication
发送其他应用程序事件。
![]() |
某些事件实际上是在 如果希望这些侦听器自动注册,而不管应用程序的创建方式如何,则可以添加 |
在应用程序运行时,应用程序事件按以下顺序发送:
ApplicationStartingEvent
在运行开始时发送,但在任何处理之前发送,但侦听器和初始化器的注册除外。ApplicationEnvironmentPreparedEvent
当Environment
在上下文中使用是已知的,但在创建上下文之前。ApplicationPreparedEvent
在启动刷新之前发送,但在加载bean定义之后发送。ApplicationStartedEvent
在刷新上下文之后,但在调用任何应用程序和命令行运行程序之前发送。ApplicationReadyEvent
在调用任何应用程序和命令行运行程序之后发送。它表示应用程序已准备好为请求提供服务。ApplicationFailedEvent
如果启动时出现异常,则发送。![]() |
您通常不需要使用应用程序事件,但是知道它们的存在是很方便的。在内部,SpringBoot使用事件来处理各种任务。 |
应用程序事件是通过使用SpringFramework的事件发布机制发送的。此机制的一部分确保在子上下文中发布给侦听器的事件也会在任何祖先上下文中发布给侦听器。因此,如果应用程序使用的层次结构为SpringApplication
实例,侦听器可能接收同一类型应用程序事件的多个实例。
若要允许侦听器区分针对其上下文的事件和针对后代上下文的事件,则应请求注入其应用程序上下文,然后将注入的上下文与事件的上下文进行比较。可以通过实现ApplicationContextAware
或者,如果侦听器是bean,则使用@Autowired
.
A SpringApplication
尝试创建正确类型的ApplicationContext
代表你。用于确定WebApplicationType
相当简单:
AnnotationConfigServletWebServerApplicationContext
使用AnnotationConfigReactiveWebServerApplicationContext
使用AnnotationConfigApplicationContext
使用这意味着如果您使用SpringMVC和新的WebClient
从同一个应用程序中的SpringWebFlux开始,默认情况下将使用SpringMVC。您可以通过调用setWebApplicationType(WebApplicationType)
.
也可以完全控制ApplicationContext
类型,该类型通过调用setApplicationContextClass(…)
.
![]() |
打电话给 |
如果需要访问传递给SpringApplication.run(…)
,你可以注射org.springframework.boot.ApplicationArguments
豆子这,这个,那,那个ApplicationArguments
接口提供对两个原始数据的访问。String[]
论点和分析option
和non-option
参数,如以下示例所示:
- 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还注册了一个 |
如果您需要在SpringApplication
已经启动,您可以实现ApplicationRunner
或CommandLineRunner
接口。两个接口都以相同的方式工作,并提供了一个run
方法,该方法在前面被调用。SpringApplication.run(…)
完成。
这,这个,那,那个CommandLineRunner
接口以简单字符串数组的形式提供对应用程序参数的访问,而ApplicationRunner
使用ApplicationArguments
接口。下面的示例显示CommandLineRunner
带着run
方法:
- import org.springframework.boot.*;
- import org.springframework.stereotype.*;
-
- @Component
- public class MyBean implements CommandLineRunner {
-
- public void run(String... args) {
- // Do something...
- }
-
- }
如果几个CommandLineRunner
或ApplicationRunner
bean被定义为必须按特定顺序调用,您可以另外实现org.springframework.core.Ordered
接口或使用org.springframework.core.annotation.Order
注释
各SpringApplication
向JVM注册一个关闭挂钩,以确保ApplicationContext
在出口处优雅地关闭。所有标准的Spring生命周期回调(如DisposableBean
接口或@PreDestroy
(注释)可以使用。
此外,bean还可以实现org.springframework.boot.ExitCodeGenerator
接口时,如果希望返回特定的退出代码,则为SpringApplication.exit()
叫做。然后,可以将此退出代码传递给System.exit()
若要将其作为状态代码返回,请参见以下示例:
- @SpringBootApplication
- public class ExitCodeApplication {
-
- @Bean
- public ExitCodeGenerator exitCodeGenerator() {
- return () -> 42;
- }
-
- public static void main(String[] args) {
- System.exit(SpringApplication
- .exit(SpringApplication.run(ExitCodeApplication.class, args)));
- }
-
- }
此外,ExitCodeGenerator
接口可以通过异常实现。当遇到这样的异常时,SpringBoot返回实现的退出代码getExitCode()
方法。
通过指定spring.application.admin.enabled
财产。这暴露了SpringApplicationAdminMXBean
在站台上MBeanServer
。您可以使用此特性远程管理SpringBoot应用程序。此特性对于任何服务包装器实现也可能有用。
![]() |
如果您想知道应用程序在哪个HTTP端口上运行,请使用 |
![]() | 谨慎 |
---|---|
启用此特性时要小心,因为MBean公开了关闭应用程序的方法。 |
SpringBoot允许您将配置外部化,以便在不同的环境中使用相同的应用程序代码。您可以使用属性文件、YAML文件、环境变量和命令行参数来外部化配置.属性可以将属性值直接注入bean中。@Value
注释,通过Spring的Environment
抽象,或被绑定到结构化对象贯通@ConfigurationProperties
.
Spring Boot使用了一个非常特殊的PropertySource
旨在允许合理地凌驾于价值观之上的秩序。属性按以下顺序考虑:
~/.spring-boot-devtools.properties
当DevTools处于活动状态时)。@TestPropertySource
测试的注释。properties
属性在您的测试中。可在@SpringBootTest
而用于测试应用程序的特定部分的测试注释.SPRING_APPLICATION_JSON
(嵌入到环境变量或系统属性中的内联JSON)。ServletConfig
init参数ServletContext
init参数java:comp/env
.System.getProperties()
).RandomValuePropertySource
中只具有属性的random.*
.application-{profile}.properties
和YAML变体)。application-{profile}.properties
和YAML变体)。application.properties
和YAML变体)。application.properties
和YAML变体)。@PropertySource
的注释@Configuration
上课。SpringApplication.setDefaultProperties
).为了提供一个具体的示例,假设您开发了一个@Component
使用name
属性,如以下示例所示:
- import org.springframework.stereotype.*;
- import org.springframework.beans.factory.annotation.*;
-
- @Component
- public class MyBean {
-
- @Value("${name}")
- private String name;
-
- // ...
-
- }
在应用程序类路径(例如,在JAR中)上,可以使用application.properties
文件,该文件提供了name
。在新环境中运行时,application.properties
文件可以在您的JAR之外提供,该JAR覆盖name
。对于一次性测试,可以使用特定的命令行开关启动(例如,java -jar app.jar --name="Spring"
).
![]() |
这,这个,那,那个 在前面的示例中,您的结果是 还可以使用命令行参数提供JSON,如下例所示: 您还可以将JSON作为JNDI变量提供,如下所示: |
这,这个,那,那个RandomValuePropertySource
对于注入随机值(例如,向秘密或测试用例)很有用。它可以生成整数、长、uid或字符串,如以下示例所示:
- 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
最大值(独占)。
默认情况下,SpringApplication
转换任何命令行选项参数(即以--
,如--server.port=9000
)property
并将它们添加到春天Environment
。如前所述,命令行属性总是优先于其他属性源。
如果不希望将命令行属性添加到Environment
,您可以通过以下方式禁用它们SpringApplication.setAddCommandLineProperties(false)
.
SpringApplication
从application.properties
文件位于以下位置,并将它们添加到Spring中Environment
:
/config
当前目录的子目录/config
包装列表按优先级排序(在列表中较高的位置中定义的属性覆盖在较低位置中定义的属性)。
![]() |
你也可以使用YAML(‘.yml’)文件作为“.properties”的替代物。 |
如果你不喜欢application.properties
作为配置文件名,可以通过指定spring.config.name
环境属性属性还可以引用显式位置。spring.config.location
环境属性(它是以逗号分隔的目录位置或文件路径列表)。下面的示例演示如何指定不同的文件名:
$ 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
作为-is使用,不支持特定于配置文件的变体,并且被任何特定于配置文件的属性覆盖.
配置位置按反向顺序搜索。默认情况下,配置的位置为classpath:/,classpath:/config/,file:./,file:./config/
。得到的搜索顺序如下:
file:./config/
file:./
classpath:/config/
classpath:/
当通过以下方式配置自定义配置位置时spring.config.location
,它们替换默认位置。例如,如果spring.config.location
配置为classpath:/custom-config/,file:./custom-config/
,搜索顺序如下:
file:./custom-config/
classpath:custom-config/
或者,当通过以下方法配置自定义配置位置时spring.config.additional-location
,除默认位置外,还将使用它们。在默认位置之前搜索其他位置。例如,如果classpath:/custom-config/,file:./custom-config/
配置后,搜索顺序如下:
file:./custom-config/
classpath:custom-config/
file:./config/
file:./
classpath:/config/
classpath:/
此搜索顺序允许您在一个配置文件中指定默认值,然后在另一个配置文件中选择性地覆盖这些值。中为应用程序提供默认值。application.properties
(或您选择的其他任何基本名称)spring.config.name
)在默认位置之一。然后,可以在运行时使用位于其中一个自定义位置的不同文件重写这些默认值。
![]() |
如果使用环境变量而不是系统属性,大多数操作系统都不允许以周期分隔的键名,但可以使用下划线(例如, |
![]() |
如果应用程序在容器中运行,则JNDI属性(在 |
除了……之外application.properties
还可以使用下列命名约定定义特定于配置文件的属性:application-{profile}.properties
。这,这个,那,那个Environment
具有一组默认配置文件(默认情况下,[default]
),如果未设置活动配置文件,则使用。换句话说,如果没有显式激活配置文件,则application-default.properties
都装好了。
特定于配置文件的属性是从与标准位置相同的位置加载的。application.properties
,使用特定于配置文件的文件总是覆盖非特定的文件,无论配置文件特定的文件是否位于打包的JAR内部或外部。
如果指定了多个配置文件,则应用最后一次获胜策略。例如,由spring.profiles.active
属性的配置后添加SpringApplication
API,因此优先。
![]() |
如果您在 |
中的值application.properties
通过现有的Environment
当它们被使用时,您可以引用以前定义的值(例如,从系统属性)。
- app.name=MyApp
- app.description=${app.name} is a Spring Boot application
![]() |
您还可以使用此技术创建现有SpringBoot属性的“短”变体。见第76.4节,“使用‘短’命令行参数”如何了解细节。 |
YAML是JSON的超集,因此是指定分层配置数据的方便格式。这,这个,那,那个SpringApplication
类自动支持YAML作为属性的替代方法,只要您有蛇YAML你的类路径上的图书馆。
![]() |
如果使用“starters”,SnakeYAML将自动由 |
SpringFramework提供了两个方便的类,可用于加载YAML文档。这,这个,那,那个YamlPropertiesFactoryBean
负载YAML ASProperties
而YamlMapFactoryBean
将YAML加载为Map
.
例如,考虑以下YAML文档:
- environments:
- dev:
- url: http://dev.example.com
- name: Developer Setup
- prod:
- url: http://another.example.com
- name: My Cool App
前面的示例将转换为以下属性:
- environments.dev.url=http://dev.example.com
- environments.dev.name=Developer Setup
- environments.prod.url=http://another.example.com
- environments.prod.name=My Cool App
YAML列表表示为[index]
脱扣器。例如,考虑以下YAML:
- my:
- servers:
- - dev.example.com
- - another.example.com
前面的示例将转换为以下属性:
- my.servers[0]=dev.example.com
- my.servers[1]=another.example.com
通过使用SpringBoot的Binder
实用程序(这是@ConfigurationProperties
,则需要在类型为java.util.List
(或Set
),或者需要提供一个setter,或者用一个可变值初始化它。例如,下面的示例绑定到前面显示的属性:
- @ConfigurationProperties(prefix="my")
- public class Config {
-
- private List<String> servers = new ArrayList<String>();
-
- public List<String> getServers() {
- return this.servers;
- }
- }
这,这个,那,那个YamlPropertySourceLoader
类可用于将YAML公开为PropertySource
春天Environment
。这样做可以让您使用@Value
带有占位符语法的注释以访问YAML属性。
可以在单个文件中指定多个特定于配置文件的YAML文档。spring.profiles
键指示何时应用文档,如以下示例所示:
- server:
- address: 192.168.1.100
- ---
- spring:
- profiles: development
- server:
- address: 127.0.0.1
- ---
- spring:
- profiles: production & eu-central
- server:
- address: 192.168.1.120
在前面的示例中,如果development
配置文件处于活动状态,则server.address
财产127.0.0.1
。类似地,如果production
和 eu-central
配置文件处于活动状态,server.address
财产192.168.1.120
。如果development
, production
和eu-central
配置文件是不启用,则属性的值为192.168.1.100
.
![]() |
|
如果在应用程序上下文启动时没有显式活动,默认配置文件将被激活。因此,在下面的YAML中,我们为spring.security.user.password
那是可得的只在“默认”配置文件中:
- server:
- port: 8000
- ---
- spring:
- profiles: default
- security:
- user:
- password: weak
然而,在下面的示例中,密码总是被设置,因为它没有附加到任何配置文件,并且在所有其他配置文件中都必须在必要时显式地重置它:
- server:
- port: 8000
- spring:
- security:
- user:
- password: weak
使用spring.profiles
元素可以通过使用!
性格。如果为单个文档指定了否定的和非否定的配置文件,则至少必须有一个非否定的配置文件匹配,并且任何否定的配置文件都不能匹配。
属性无法加载YAML文件。@PropertySource
注释因此,在需要以这种方式加载值的情况下,需要使用属性文件。
使用@Value("${property}")
注入配置属性的注释有时会很麻烦,特别是如果您正在处理多个属性,或者您的数据本质上是分层的。SpringBoot提供了一种使用属性的替代方法,该方法允许强类型bean控制和验证应用程序的配置,如下面的示例所示:
- package 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("acme")
- public class AcmeProperties {
-
- 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) { ... }
-
- public Security getSecurity() { ... }
-
- public static class Security {
-
- private String username;
-
- private String password;
-
- 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定义了以下属性:
acme.enabled
,值为false
默认情况下。acme.remote-address
,具有可以被胁迫的类型。String
.acme.security.username
具有嵌套的“Security”对象,该对象的名称由属性的名称决定。特别是,返回类型根本不被使用,而且可能是SecurityProperties
.acme.security.password
.acme.security.roles
的集合String
.![]() |
getter和setter通常是强制性的,因为绑定是通过标准的JavaBeans属性描述符进行的,就像SpringMVC中的那样。在下列情况下,可省略一位策划人:
有些人使用ProjectLombok自动添加getter和setter。确保Lombok不会为这种类型生成任何特定的构造函数,因为容器会自动使用它来实例化对象。 最后,只考虑标准JavaBean属性,不支持在静态属性上绑定。 |
您还需要列出要在@EnableConfigurationProperties
注释,如以下示例所示:
- @Configuration
- @EnableConfigurationProperties(AcmeProperties.class)
- public class MyConfiguration {
- }
![]() |
当 上面示例中的bean名称是 |
即使前面的配置为AcmeProperties
,我们建议@ConfigurationProperties
只处理环境,特别是不从上下文注入其他bean。话虽如此,@EnableConfigurationProperties
注释是也自动应用于您的项目,以便任何现有带注释的bean@ConfigurationProperties
配置为Environment
。你可以走捷径MyConfiguration
确保AcmeProperties
已经是一个bean,如下面的示例所示:
- @Component
- @ConfigurationProperties(prefix="acme")
- public class AcmeProperties {
-
- // ... see the preceding example
-
- }
这种类型的配置特别适用于SpringApplication
外部YAML配置,如以下示例所示:
- # application.yml
-
- acme:
- remote-address: 192.168.1.1
- security:
- username: admin
- roles:
- - USER
- - ADMIN
-
- # additional configuration as required
与之合作@ConfigurationProperties
bean,您可以与任何其他bean相同的方式注入它们,如下面的示例所示:
@Service public class MyService { private final AcmeProperties properties; @Autowired public MyService(AcmeProperties properties) { this.properties = properties; } //... @PostConstruct public void openConnection() { Server server = new Server(this.properties.getRemoteAddress()); // ... } }
![]() |
使用 |
以及使用@ConfigurationProperties
若要对类进行注释,还可以将其用于公共类。@Bean
方法。当您想要将属性绑定到超出您控制范围的第三方组件时,这样做特别有用。
配置bean的步骤。Environment
属性,添加@ConfigurationProperties
到它的bean注册,如下面的示例所示:
- @ConfigurationProperties(prefix = "another")
- @Bean
- public AnotherComponent anotherComponent() {
- ...
- }
属性定义的任何属性。another
前缀映射到AnotherComponent
bean的方式类似于前面的AcmeProperties
举个例子。
SpringBoot使用一些宽松的规则进行绑定Environment
属性@ConfigurationProperties
类之间不需要完全匹配。Environment
属性名称和bean属性名称。有用的常见示例包括破折号分隔的环境属性(例如,context-path
绑定到contextPath
)和大写环境属性(例如,PORT
绑定到port
).
例如,请考虑以下几点@ConfigurationProperties
班级:
- @ConfigurationProperties(prefix="acme.my-project.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格式存储,例如 |
当绑定到Map
属性,如果key
包含除小写字母-数字字符或-
,您需要使用括号表示法,以便保留原始值。如果密钥未被[]
,任何不是alpha-数字或-
都被移走了。例如,考虑将下列属性绑定到Map
:
- acme:
- map:
- "[/key1]": value1
- "[/key2]": value2
- /key3: value3
上面的属性将绑定到Map
带着/key1
, /key2
和key3
就像地图上的钥匙。
当在多个地方配置列表时,可以通过替换整个列表来重写。
例如,假设MyPojo
对象name
和description
属性null
默认情况下。下面的示例公开MyPojo
对象AcmeProperties
:
- @ConfigurationProperties("acme")
- public class AcmeProperties {
-
- private final List<MyPojo> list = new ArrayList<>();
-
- public List<MyPojo> getList() {
- return this.list;
- }
-
- }
考虑以下配置:
- acme:
- list:
- - name: my name
- description: my description
- ---
- spring:
- profiles: dev
- acme:
- list:
- - name: my another name
如果dev
侧写不活跃,AcmeProperties.list
包含一个MyPojo
条目,如先前定义的。如果dev
但是,已启用配置文件。list
仍然只包含一个条目(名称为my another name
以及对.的描述null
)这种配置不加一秒钟MyPojo
实例添加到列表中,并且它不合并项。
当List
在多个配置文件中指定,则使用优先级最高的配置文件(仅使用该配置文件)。考虑以下示例:
- acme:
- list:
- - name: my name
- description: my description
- - name: another name
- description: another description
- ---
- spring:
- profiles: dev
- acme:
- list:
- - name: my another name
在前面的示例中,如果dev
侧写很活跃,AcmeProperties.list
含一 MyPojo
条目(名称为my another name
以及对.的描述null
)对于YAML,逗号分隔的列表和YAML列表都可以用于完全覆盖列表的内容。
为Map
属性,则可以绑定从多个源提取的属性值。但是,对于多个源中的相同属性,则使用具有最高优先级的属性。下面的示例公开Map<String, MyPojo>
从…AcmeProperties
:
- @ConfigurationProperties("acme")
- public class AcmeProperties {
-
- private final Map<String, MyPojo> map = new HashMap<>();
-
- public Map<String, MyPojo> getMap() {
- return this.map;
- }
-
- }
考虑以下配置:
- acme:
- map:
- key1:
- name: my name 1
- description: my description 1
- ---
- spring:
- profiles: dev
- acme:
- map:
- key1:
- name: dev name 1
- key2:
- name: dev name 2
- description: dev description 2
如果dev
侧写不活跃,AcmeProperties.map
包含一个带键的条目key1
(名称为my name 1
以及对.的描述my description 1
)如果dev
但是,已启用配置文件,map
包含两个带键的条目。key1
(名称为dev name 1
以及对.的描述my description 1
)和key2
(名称为dev name 2
以及对.的描述dev description 2
).
![]() |
前面的合并规则适用于来自所有属性源的属性,而不仅仅是YAML文件。 |
当外部应用程序属性绑定到@ConfigurationProperties
豆子如果需要自定义类型转换,则可以提供ConversionService
bean(有一个名为conversionService
)或自定义属性编辑器(通过CustomEditorConfigurer
(豆子)或习惯Converters
(将bean定义注释为@ConfigurationPropertiesBinding
).
![]() |
由于此bean是在应用程序生命周期早期被请求的,请确保限制您 |
转换持续时间
SpringBoot为表示持续时间提供了专门的支持。如果您暴露了java.time.Duration
属性时,应用程序属性中的下列格式可用:
long
表示(使用毫秒作为默认单位,除非@DurationUnit
已指定)java.util.Duration
10s
表示10秒)考虑以下示例:
@ConfigurationProperties("app.system") public class AppSystemProperties { @DurationUnit(ChronoUnit.SECONDS) private Duration sessionTimeout = Duration.ofSeconds(30); private Duration readTimeout = Duration.ofMillis(1000); public Duration getSessionTimeout() { return this.sessionTimeout; } public void setSessionTimeout(Duration sessionTimeout) { this.sessionTimeout = sessionTimeout; } public Duration getReadTimeout() { return this.readTimeout; } public void setReadTimeout(Duration readTimeout) { this.readTimeout = readTimeout; } }
若要指定30秒的会话超时,30
, PT30S
和30s
都是等价物。可以下列任何形式指定500 ms的读取超时:500
, PT0.5S
和500ms
.
您还可以使用任何受支持的单元。它们是:
ns
纳秒us
微秒ms
毫秒s
几秒钟m
几分钟h
几个小时d
好几天默认单位为毫秒,可以使用@DurationUnit
如上面的示例所示。
![]() |
如果您正在从简单地使用 |
转换数据大小
Spring Framework有一个DataSize
值类型,允许以字节表示大小。如果您暴露了DataSize
属性时,应用程序属性中的下列格式可用:
long
表示(使用字节作为默认单位,除非@DataSizeUnit
已指定)10MB
表示10兆字节)考虑以下示例:
@ConfigurationProperties("app.io") public class AppIoProperties { @DataSizeUnit(DataUnit.MEGABYTES) private DataSize bufferSize = DataSize.ofMegabytes(2); private DataSize sizeThreshold = DataSize.ofBytes(512); public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public DataSize getSizeThreshold() { return this.sizeThreshold; } public void setSizeThreshold(DataSize sizeThreshold) { this.sizeThreshold = sizeThreshold; } }
若要指定10兆字节的缓冲区大小,10
和10MB
都是等价物。大小阈值为256字节,可指定为256
或256B
.
您还可以使用任何受支持的单元。它们是:
B
表示字节KB
千字节MB
兆字节GB
千兆字节TB
为兆字节默认单位是字节,可以使用@DataSizeUnit
如上面的示例所示。
![]() |
如果您正在从简单地使用 |
Spring Boot试图验证@ConfigurationProperties
类,只要它们被Spring注释@Validated
注释您可以使用jsr-303。javax.validation
直接对配置类进行约束注释。为此,请确保类路径上有符合JSR-303的实现,然后将约束注释添加到字段中,如下面的示例所示:
- @ConfigurationProperties(prefix="acme")
- @Validated
- public class AcmeProperties {
-
- @NotNull
- private InetAddress remoteAddress;
-
- // ... getters and setters
-
- }
![]() |
还可以通过注释 |
虽然嵌套属性在绑定时也将得到验证,但最好的做法是将关联字段注释为@Valid
。这确保即使没有找到嵌套属性也会触发验证。下面的示例构建在前面的AcmeProperties
例子:
@ConfigurationProperties(prefix="acme") @Validated public class AcmeProperties { @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 } }
还可以添加自定义SpringValidator
通过创建一个名为configurationPropertiesValidator
。这,这个,那,那个@Bean
方法应声明static
。配置属性验证器是在应用程序生命周期的早期创建的,并声明@Bean
方法可以创建bean,而不必实例化@Configuration
班级,等级这样做可以避免任何可能因早期实例化而引起的问题。有一个属性验证样本这说明了如何设置。
![]() |
这,这个,那,那个 |
这,这个,那,那个@Value
注释是一个核心容器特性,它不提供与类型安全配置属性相同的特性。下表总结了@ConfigurationProperties
和@Value
:
如果您为您自己的组件定义了一组配置键,我们建议您将它们分组到带注释的POJO中。@ConfigurationProperties
。你也应该知道,因为@Value
不支持轻松绑定,如果需要使用环境变量提供值,则不是很好的选择。
最后,当您可以编写一个SpEL
表达在@Value
,这些表达式不是从应用程序属性文件.
SpringProfiles提供了一种隔离应用程序配置部分并使其仅在特定环境中可用的方法。任何@Component
或@Configuration
可以用@Profile
若要限制加载时间,请参见以下示例:
- @Configuration
- @Profile("production")
- public class ProductionConfiguration {
-
- // ...
-
- }
您可以使用spring.profiles.active
Environment
属性指定哪些配置文件是活动的。您可以使用本章前面描述的任何方式指定该属性。例如,您可以将它包含在您的application.properties
,如以下示例所示:
spring.profiles.active=dev,hsqldb
还可以使用以下开关在命令行中指定它:--spring.profiles.active=dev,hsqldb
.
这,这个,那,那个spring.profiles.active
属性遵循与其他属性相同的排序规则:PropertySource
赢了。这意味着您可以在application.properties
然后取代通过使用命令行开关。
有时,具有特定于配置文件的属性是有用的加而不是替换它们。这,这个,那,那个spring.profiles.include
属性可用于无条件地添加活动配置文件。这,这个,那,那个SpringApplication
入口点还具有一个JavaAPI,用于设置其他配置文件(即,在由spring.profiles.active
财产)。见setAdditionalProfiles()
方法Spring应用.
例如,当使用开关运行具有下列属性的应用程序时,--spring.profiles.active=prod
,proddb
和prodmq
还启动了配置文件:
- ---
- my.property: fromyamlfile
- ---
- spring.profiles: prod
- spring.profiles.include:
- - proddb
- - prodmq
![]() |
记住 |
可以通过以下方式以编程方式设置活动配置文件:SpringApplication.setAdditionalProfiles(…)
在应用程序运行之前。还可以使用Spring的ConfigurableEnvironment
接口。
特定于配置文件的两种变体application.properties
(或application.yml
)和通过@ConfigurationProperties
被视为文件并加载。见“第24.4节,“配置文件特有的属性”“详细情况。
弹簧启动共用测井对于所有内部日志记录,但保持基础日志实现处于打开状态。提供了默认配置。Java Util测井, Log4J2,和Logback。在每种情况下,记录器都预先配置为使用控制台输出和可选文件输出。
默认情况下,如果使用“starters”,则使用Logback进行日志记录。还包括适当的Logback路由,以确保使用JavaUtil日志记录、CommonLogging、Log4J或SLF4J的依赖库都正确工作。
![]() |
Java有很多日志记录框架可用。如果上面的列表看起来很混乱,不要担心。通常,您不需要更改日志记录依赖项,SpringBoot默认设置也很好。 |
SpringBoot的默认日志输出类似于以下示例:
- 2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52
- 2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
- 2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms
- 2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
- 2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
输出的项目如下:
ERROR
, WARN
, INFO
, DEBUG
,或TRACE
.---
分隔符以区分实际日志消息的开始。![]() |
Logback没有 |
默认日志配置在写入消息时将消息回显到控制台。默认情况下,ERROR
-水平,WARN
-级别,和INFO
-记录级别消息。还可以启用“调试”模式,方法是将应用程序启动为--debug
旗子。
$ java -jar myapp.jar --debug
![]() |
您还可以指定 |
启用调试模式后,将选择核心记录器(嵌入式容器、Hibernate和SpringBoot)以输出更多信息。启用调试模式不将应用程序配置为将所有消息记录为DEBUG
水平。
或者,您可以启用“跟踪”模式,方法是将应用程序启动为--trace
旗(或)trace=true
在你的application.properties
)这样做可以为选择的核心记录器(嵌入式容器、Hibernate模式生成和整个Spring组合)启用跟踪日志记录。
如果您的终端支持ANSI,则使用颜色输出来提高可读性。你可以spring.output.ansi.enabled
转到支撑值以覆盖自动检测。
颜色编码是通过使用%clr
转换词。最简单的形式是,转换器根据日志级别对输出进行着色,如下面的示例所示:
%clr(%5p)
下表描述日志级别到颜色的映射:
水平 | 颜色 |
---|---|
| 红色 |
| 红色 |
| 黄色 |
| 绿色 |
| 绿色 |
| 绿色 |
或者,您可以通过提供颜色或样式作为转换的选项来指定应该使用的颜色或样式。例如,要使文本变黄,请使用以下设置:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
支持下列颜色和样式:
blue
cyan
faint
green
magenta
red
yellow
默认情况下,SpringBoot只记录到控制台,不写入日志文件。如果要在控制台输出之外写入日志文件,则需要设置logging.file
或logging.path
属性(例如,在application.properties
).
下表显示了logging.*
属性可以一起使用:
表26.1.测井特性
logging.file | logging.path | 例 | 描述 |
---|---|---|---|
(无) | (无) | 控制台只记录。 | |
特定文件 | (无) |
| 写入指定的日志文件。名称可以是确切的位置,也可以是相对于当前目录的位置。 |
(无) | 特定目录 |
| 写字 |
日志文件在达到10 MB时旋转,与控制台输出一样,ERROR
-水平,WARN
-级别,和INFO
-默认情况下记录级别消息。大小限制可以使用logging.file.max-size
财产。以前旋转的文件被无限期存档,除非logging.file.max-history
属性已设置。
![]() |
日志系统是在应用程序生命周期的早期初始化的。因此,在通过 |
![]() |
日志属性独立于实际的日志基础结构。因此,特定的配置键(如 |
所有受支持的日志系统都可以在Spring中设置记录器级别Environment
(例如,在application.properties
)通过使用logging.level.<logger-name>=<level>
哪里level
是跟踪、调试、信息、警告、错误、致命或关闭之一。这,这个,那,那个root
可以通过以下方式配置记录器:logging.level.root
.
下面的示例显示了application.properties
:
- logging.level.root=WARN
- logging.level.org.springframework.web=DEBUG
- logging.level.org.hibernate=ERROR
能够将相关的记录器组合在一起,以便能够同时配置它们,这通常是有用的。例如,您可能通常会更改日志记录级别。全Tomcat相关的记录器,但您不能轻松地记住顶级软件包。
为此,SpringBoot允许您在Spring中定义日志组Environment
。例如,通过将“tomcat”组添加到application.properties
:
logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat
定义完后,可以用一行更改组中所有记录器的级别:
logging.level.tomcat=TRACE
SpringBoot包括下列预定义的日志组,可以开箱即用:
名字,姓名 | 伐木工 |
---|---|
万维网 |
|
SQL |
|
可以通过在类路径中包含适当的库来激活各种日志系统,并可以通过在类路径根目录中或在下面的Spring指定的位置提供适当的配置文件来进一步定制这些日志系统。Environment
财产:logging.config
.
可以强制SpringBoot使用特定的日志系统,方法是使用org.springframework.boot.logging.LoggingSystem
系统属性值应该是LoggingSystem
执行。您还可以完全禁用SpringBoot的日志配置,方法是使用none
.
![]() |
因为日志记录是初始化的以前这,这个,那,那个 |
根据日志记录系统的不同,将加载以下文件:
测井系统 | 定制化 |
---|---|
Logback |
|
Log4j2 |
|
JDK(Java Util日志记录) |
|
![]() |
如果可能,我们建议您使用 |
![]() |
JavaUtil日志记录中存在已知的类加载问题,在从“可执行JAR”运行时会导致问题。如果可能的话,我们建议您在从“可执行的JAR”运行时避免使用它。 |
为了帮助定制,其他一些属性将从Spring中传输Environment
到系统属性,如下表所述:
春季环境 | 系统性质 | 评论意见 |
---|---|---|
|
| 记录异常时使用的转换字。 |
|
| 如果已定义,则在默认日志配置中使用。 |
|
| 最大日志文件大小(如果启用LOG_FILE)。(仅支持默认的Logback设置。) |
|
| 要保留的存档日志文件的最大数量(如果启用log_file)。(仅支持默认的Logback设置。) |
|
| 如果已定义,则在默认日志配置中使用。 |
|
| 要在控制台上使用的日志模式(Stdout)。(仅支持默认的Logback设置。) |
|
| 日志日期格式的附录模式。(仅支持默认的Logback设置。) |
|
| 要在文件中使用的日志模式(如果 |
|
| 在呈现日志级别时使用的格式(默认值) |
|
| 当前进程ID(如果可能的话会被发现,如果还没有定义为OS环境变量的话)。 |
所有受支持的日志记录系统在解析其配置文件时都可以参考系统属性。中的默认配置spring-boot.jar
例如:
![]() |
如果要在日志记录属性中使用占位符,则应使用Spring Boot语法而不是底层框架的语法。特别要注意的是,如果您使用Logback,您应该使用 |
![]() |
您可以将mdc和其他临时内容添加到日志行中,只需重写 |
SpringBoot包括一些可以帮助高级配置的Logback扩展。您可以在logback-spring.xml
配置文件
![]() |
因为标准 |
![]() |
这些扩展不能与Logback的组态扫描。如果尝试这样做,对配置文件进行更改将导致一个类似于正在记录的以下内容之一的错误: |
- ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
- ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]]
这,这个,那,那个<springProfile>
标记允许您根据活动的Spring配置文件选择性地包含或排除配置部分。配置文件中的任何位置都支持配置文件节。<configuration>
元素。使用name
属性指定哪个配置文件接受配置。这,这个,那,那个<springProfile>
标记可以包含一个简单的配置文件名称(例如staging
)或配置文件表达式。配置文件表达式允许表示更复杂的配置文件逻辑,例如production & (eu-central | eu-west)
。检查参考指南更多细节。下面的清单显示了三个示例配置文件:
- <springProfile name="staging">
- <!-- configuration to be enabled when the "staging" profile is active -->
- </springProfile>
-
- <springProfile name="dev | staging">
- <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
- </springProfile>
-
- <springProfile name="!production">
- <!-- configuration to be enabled when the "production" profile is not active -->
- </springProfile>
这,这个,那,那个<springProperty>
标记允许您公开Spring中的属性Environment
在Logback中使用。如果您想从application.properties
在您的Logback配置中的文件。标记的工作方式类似于Logback的标准<property>
标签。但是,与其指定直接value
,您可以指定source
(从Environment
)如果您需要将该财产存储在local
范围内,可以使用scope
属性。如果需要回退值(如果属性未在Environment
),您可以使用defaultValue
属性。下面的示例演示如何公开在Logback中使用的属性:
- <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>
![]() |
这,这个,那,那个 |
SpringBoot非常适合Web应用程序的开发。您可以通过使用嵌入式Tomcat、Jetty、Under拖车或Netty创建一个自包含的HTTP服务器。大多数web应用程序使用spring-boot-starter-web
模块快速启动和运行。还可以选择使用spring-boot-starter-webflux
模块。
如果你还没有开发一个SpringBootWeb应用程序,你可以按照“HelloWorld!”实例中的开始部分。
这,这个,那,那个SpringWebMVC框架(通常简称为“SpringMVC”)是一个丰富的“模型视图控制器”Web框架。Springmvc允许您创建特殊的@Controller
或@RestController
用来处理传入的HTTP请求的bean。方法将控制器中的方法映射到HTTP。@RequestMapping
注释。
下面的代码显示了一个典型的@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) {
- // ...
- }
-
- }

SpringMVC是核心Spring框架的一部分,详细信息可在参考文献。还有几个指南介绍了SpringMVCspring.io/guides.
SpringBoot为SpringMVC提供了自动配置,它适用于大多数应用程序。
自动配置在Spring的默认值之上添加了以下特性:
ContentNegotiatingViewResolver
和BeanNameViewResolver
豆子Converter
, GenericConverter
,和Formatter
豆子HttpMessageConverters
(包括在内)在本文档的后面).MessageCodesResolver
(包括在内)在本文档的后面).index.html
支持。Favicon
支助(包括在内)在本文档的后面).ConfigurableWebBindingInitializer
豆(覆盖)在本文档的后面).如果您想保持SpringBootMVC特性,并且希望添加额外的MVC配置(拦截器、格式化程序、视图控制器和其他特性),您可以添加自己的@Configuration
类型类WebMvcConfigurer
但无 @EnableWebMvc
。如果您希望提供RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
,或ExceptionHandlerExceptionResolver
,您可以声明WebMvcRegistrationsAdapter
实例来提供这些组件。
如果您想完全控制SpringMVC,可以添加您自己的@Configuration
带注释@EnableWebMvc
.
SpringMVC使用HttpMessageConverter
接口来转换HTTP请求和响应。明智之举也包括在内。例如,对象可以自动转换为JSON(通过使用Jackson库)或XML(如果可用的话使用Jackson XML扩展,或者在Jackson XML扩展不可用时使用JAXB)。默认情况下,字符串编码为UTF-8
.
如果需要添加或自定义转换器,可以使用SpringBoot的HttpMessageConverters
类,如以下清单所示:
- import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
- import org.springframework.context.annotation.*;
- import org.springframework.http.converter.*;
-
- @Configuration
- public class MyConfiguration {
-
- @Bean
- public HttpMessageConverters customConverters() {
- HttpMessageConverter<?> additional = ...
- HttpMessageConverter<?> another = ...
- return new HttpMessageConverters(additional, another);
- }
-
- }
任何HttpMessageConverter
上下文中存在的bean被添加到转换器列表中。您也可以同样的方式覆盖默认转换器。
如果使用Jackson序列化和反序列化JSON数据,则可能需要编写自己的JsonSerializer
和JsonDeserializer
上课。自定义序列化程序通常是通过模块向Jackson注册,但是SpringBoot提供了另一种选择@JsonComponent
注释,使直接注册Springbean更加容易。
您可以使用@JsonComponent
直接注释JsonSerializer
或JsonDeserializer
实现。还可以在包含序列化器/反序列化器的类中作为内部类使用它,如下面的示例所示:
- 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> {
- // ...
- }
-
- }

全@JsonComponent
豆类ApplicationContext
都会自动注册到杰克逊那里。因为@JsonComponent
元注释@Component
,适用通常的组件扫描规则。
Spring Boot还提供JsonObjectSerializer
和JsonObjectDeserializer
基类,这些基类在序列化对象时为标准Jackson版本提供了有用的替代方案。看见JsonObjectSerializer
和JsonObjectDeserializer
在Javadoc中获得详细信息。
SpringMVC有一种用于生成错误代码的策略,用于从绑定错误中呈现错误消息:MessageCodesResolver
。如果您设置spring.mvc.message-codes-resolver.format
财产PREFIX_ERROR_CODE
或POSTFIX_ERROR_CODE
,Spring Boot为您创建一个DefaultMessageCodesResolver.Format
).
默认情况下,SpringBoot从一个名为/static
(或/public
或/resources
或/META-INF/resources
)在类路径中或从ServletContext
。它使用ResourceHttpRequestHandler
,这样您就可以通过添加自己的WebMvcConfigurer
和凌驾于addResourceHandlers
方法。
在独立的web应用程序中,容器中的默认servlet也被启用,并充当后盾,从ServletContext
如果春天决定不处理它。大多数情况下,这种情况不会发生(除非修改默认的MVC配置),因为Spring总是可以通过DispatcherServlet
.
默认情况下,资源被映射到/**
,但是您可以通过spring.mvc.static-path-pattern
财产。例如,将所有资源重新定位到/resources/**
可实现以下目标:
spring.mvc.static-path-pattern=/resources/**
还可以使用spring.resources.static-locations
属性(将默认值替换为目录位置列表)。根servlet上下文路径,"/"
自动添加为一个位置。
除了前面提到的“标准”静态资源位置之外,还为WebJars内容。中具有路径的任何资源。/webjars/**
如果JAR文件以Webjars格式打包,则从JAR文件中提供服务。
![]() |
不要使用 |
SpringBoot还支持SpringMVC提供的高级资源处理特性,允许用例,例如破坏缓存的静态资源或Webjars的版本无关URL。
若要将版本无关的URL用于Webjars,请添加webjars-locator-core
依赖。然后声明你的Webjar。以jQuery为例,添加"/webjars/jquery/jquery.min.js"
结果"/webjars/jquery/x.y.z/jquery.min.js"
。哪里x.y.z
是Webjar版本。
![]() |
如果使用JBoss,则需要声明 |
要使用缓存破坏,以下配置为所有静态资源配置缓存破坏解决方案,有效地添加内容散列,如<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>
,以URL表示:
- spring.resources.chain.strategy.content.enabled=true
- spring.resources.chain.strategy.content.paths=/**
![]() |
到资源的链接在运行时用模板重写,这要感谢 |
例如,当用JavaScript模块加载器动态加载资源时,重命名文件不是一个选项。这就是为什么其他战略也得到支持并可以结合在一起的原因。“固定”策略在不更改文件名的情况下在URL中添加静态版本字符串,如下面的示例所示:
- 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
使用此配置,JavaScript模块位于"/js/lib/"
使用固定版本控制策略("/v12/js/lib/mymodule.js"
),而其他资源仍然使用内容1(<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>
).
看见ResourceProperties
获得更多支持的选项。
SpringBoot支持静态和模板欢迎页面。它首先寻找一个index.html
文件在配置的静态内容位置中。如果找不到一个,它就会查找一个index
模板。如果找到其中之一,则自动将其用作应用程序的欢迎页。
春靴favicon.ico
在配置的静态内容位置和类路径的根中(按该顺序)。如果存在这样的文件,则自动将其用作应用程序的首选项。
SpringMVC可以通过查看请求路径并将其匹配到应用程序中定义的映射来将传入的HTTP请求映射到处理程序(例如,@GetMapping
控制器方法的注释)。
SpringBoot默认选择禁用后缀模式匹配,这意味着请求类似"GET /projects/spring-boot.json"
将无法与@GetMapping("/projects/spring-boot")
映射。这被认为是SpringMVC应用程序的最佳实践。这个特性过去主要用于HTTP客户机,它没有发送正确的“接受”请求头;我们需要确保向客户端发送正确的ContentType。如今,内容协商变得更加可靠。
还有其他处理HTTP客户端的方法,这些方法不一致地发送适当的“接受”请求标头。不使用后缀匹配,我们可以使用查询参数来确保请求类似"GET /projects/spring-boot?format=json"
将被映射到@GetMapping("/projects/spring-boot")
:
- spring.mvc.contentnegotiation.favor-parameter=true
-
- # We can change the parameter name, which is "format" by default:
- # spring.mvc.contentnegotiation.parameter-name=myparam
-
- # We can also register additional file extensions/media types with:
- spring.mvc.contentnegotiation.media-types.markdown=text/markdown
如果您理解这些警告,并且仍然希望您的应用程序使用后缀模式匹配,则需要进行以下配置:
- spring.mvc.contentnegotiation.favor-path-extension=true
-
- # You can also restrict that feature to known extensions only
- # spring.mvc.pathmatch.use-registered-suffix-pattern=true
-
- # We can also register additional file extensions/media types with:
- # spring.mvc.contentnegotiation.media-types.adoc=text/asciidoc
SpringMVC使用WebBindingInitializer
若要初始化WebDataBinder
特别的请求。如果你自己创造ConfigurableWebBindingInitializer
@Bean
,SpringBoot自动配置SpringMVC来使用它。
除了RESTWeb服务之外,您还可以使用SpringMVC来提供动态HTML内容。SpringMVC支持多种模板技术,包括Thymeleaf、FreeMarker和JSP。此外,许多其他模板引擎包括自己的SpringMVC集成。
SpringBoot包括对下列模板引擎的自动配置支持:
![]() |
如果可能,应该避免JSP。有几个已知限制当将它们与嵌入式servlet容器一起使用时。 |
当您使用默认配置的模板引擎之一时,您的模板将自动从src/main/resources/templates
.
![]() |
根据运行应用程序的方式,IntelliJIDEA对类路径的排序不同。通过IDE的主方法在IDE中运行应用程序,与使用Maven或Gradle或从打包JAR运行应用程序时相比,会产生不同的顺序。这可能导致SpringBoot无法找到类路径上的模板。如果有此问题,可以重新排序IDE中的类路径,以便首先放置模块的类和资源。或者,您可以将模板前缀配置为搜索 |
默认情况下,SpringBoot提供一个/error
映射,以合理的方式处理所有错误,并将其注册为servlet容器中的“全局”错误页。对于机器客户端,它生成一个JSON响应,其中包含错误、HTTP状态和异常消息的详细信息。对于浏览器客户端,有一个“Whitelabel”错误视图,它以HTML格式呈现相同的数据(要自定义它,添加一个View
决心error
)若要完全替换默认行为,可以实现ErrorController
并注册该类型的bean定义或添加类型的bean。ErrorAttributes
使用现有机制但替换内容。
![]() |
这,这个,那,那个 |
还可以定义带注释的类。@ControllerAdvice
自定义JSON文档以返回特定控制器和/或异常类型,如下面的示例所示:
- @ControllerAdvice(basePackageClasses = AcmeController.class)
- public class AcmeControllerAdvice extends ResponseEntityExceptionHandler {
-
- @ExceptionHandler(YourException.class)
- @ResponseBody
- ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
- HttpStatus status = getStatus(request);
- return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
- }
-
- private HttpStatus getStatus(HttpServletRequest request) {
- Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
- if (statusCode == null) {
- return HttpStatus.INTERNAL_SERVER_ERROR;
- }
- return HttpStatus.valueOf(statusCode);
- }
-
- }

在前面的示例中,如果YourException
中定义的控制器引发AcmeController
的JSON表示形式。CustomErrorType
使用POJO代替ErrorAttributes
代表。
自定义错误页
如果要显示给定状态代码的自定义HTML错误页,可以将文件添加到/error
文件夹。错误页可以是静态HTML(即在任何静态资源文件夹下添加),也可以使用模板构建。文件的名称应该是确切的状态代码或序列掩码。
例如,要映射404
对于静态HTML文件,文件夹结构如下:
- src/
- +- main/
- +- java/
- | + <source code>
- +- resources/
- +- public/
- +- error/
- | +- 404.html
- +- <other public assets>
映射所有5xx
使用FreeMarker模板出错,文件夹结构如下所示:
- src/
- +- main/
- +- java/
- | + <source code>
- +- resources/
- +- templates/
- +- error/
- | +- 5xx.ftl
- +- <other templates>
对于更复杂的映射,还可以添加实现ErrorViewResolver
接口,如以下示例所示:
- public class MyErrorViewResolver implements ErrorViewResolver {
-
- @Override
- public ModelAndView resolveErrorView(HttpServletRequest request,
- HttpStatus status, Map<String, Object> model) {
- // Use the request or status to optionally return a ModelAndView
- return ...
- }
-
- }
您还可以使用常规的SpringMVC功能,如@ExceptionHandler
方法和@ControllerAdvice
。这,这个,那,那个ErrorController
然后提取任何未处理的异常。
在SpringMVC之外映射错误页面
对于不使用SpringMVC的应用程序,可以使用ErrorPageRegistrar
接口直接注册ErrorPages
。此抽象直接用于底层嵌入式servlet容器,即使您没有SpringMVC,也可以工作。DispatcherServlet
.
- @Bean
- public ErrorPageRegistrar errorPageRegistrar(){
- return new MyErrorPageRegistrar();
- }
-
- // ...
-
- private static class MyErrorPageRegistrar implements ErrorPageRegistrar {
-
- @Override
- public void registerErrorPages(ErrorPageRegistry registry) {
- registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
- }
-
- }
![]() |
如果您注册了 |
- @Bean
- public FilterRegistrationBean myFilter() {
- FilterRegistrationBean registration = new FilterRegistrationBean();
- registration.setFilter(new MyFilter());
- ...
- registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
- return registration;
- }
注意,默认的FilterRegistrationBean
不包括ERROR
调度员类型。
警告:当部署到servlet容器时,SpringBoot使用其错误页面筛选器将具有错误状态的请求转发到相应的错误页。只有在尚未提交响应的情况下,才能将请求转发到正确的错误页。默认情况下,WebSphereApplicationServer8.0及更高版本在成功完成servlet的服务方法后提交响应。应该通过设置com.ibm.ws.webcontainer.invokeFlushAfterService
到false
.
如果您开发了一个使用超媒体的RESTfulAPI,SpringBoot为SpringHATEOA提供了自动配置,它可以很好地应用于大多数应用程序。自动配置取代了使用@EnableHypermediaSupport
并注册多个bean以方便构建基于超媒体的应用程序,包括LinkDiscoverers
(用于客户端支持)和ObjectMapper
配置为正确地将响应编组到所需的表示形式。这,这个,那,那个ObjectMapper
是通过设置spring.jackson.*
属性,或者,如果存在,则由Jackson2ObjectMapperBuilder
豆子
您可以通过使用@EnableHypermediaSupport
。注意,这样做将禁用ObjectMapper
前面描述的自定义。
跨源资源共享(CORS)是W3C规范由大多数浏览器这允许您以灵活的方式指定哪些类型的跨域请求是被授权的,而不是使用一些不太安全和功能较弱的方法,例如iframe或JSONP。
截至4.2版,SpringMVC支持CORS。使用控制器方法CORS配置带着@CrossOrigin
SpringBoot应用程序中的注释不需要任何特定的配置。全局CORS配置可以通过注册WebMvcConfigurer
带有自定义的beanaddCorsMappings(CorsRegistry)
方法,如以下示例所示:
- @Configuration
- public class MyConfiguration {
-
- @Bean
- public WebMvcConfigurer corsConfigurer() {
- return new WebMvcConfigurer() {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/api/**");
- }
- };
- }
- }
SpringWebFlux是SpringFramework5.0中引入的新的反应性Web框架。与SpringMVC不同,它不需要ServletAPI,完全异步和非阻塞,并实现了反应流规格通过反应堆工程.
SpringWebFlux有两种风格:基于功能的和基于注释的。基于注释的注释非常接近SpringMVC模型,如下面的示例所示:
- @RestController
- @RequestMapping("/users")
- public class MyRestController {
-
- @GetMapping("/{user}")
- public Mono<User> getUser(@PathVariable Long user) {
- // ...
- }
-
- @GetMapping("/{user}/customers")
- public Flux<Customer> getUserCustomers(@PathVariable Long user) {
- // ...
- }
-
- @DeleteMapping("/{user}")
- public Mono<User> deleteUser(@PathVariable Long user) {
- // ...
- }
-
- }

函数变体“WebFlim.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是Spring框架的一部分,详细信息可在其参考文献.
![]() |
你可以定义 |
要开始,添加spring-boot-starter-webflux
模块到您的应用程序。
![]() |
加法 |
SpringBoot为SpringWebFlux提供了自动配置,它适用于大多数应用程序。
自动配置在Spring的默认值之上添加了以下特性:
如果您想保持SpringBootWebFlux特性,并且希望添加其他功能WebFlux配置,您可以添加自己的@Configuration
类型类WebFluxConfigurer
但无 @EnableWebFlux
.
如果您想完全控制SpringWebFlux,可以添加您自己的@Configuration
带注释@EnableWebFlux
.
SpringWebFlux使用HttpMessageReader
和HttpMessageWriter
接口来转换HTTP请求和响应。它们被配置为CodecConfigurer
通过查看类路径中可用的库来实现合理的默认值。
Spring Boot使用CodecCustomizer
实例。例如spring.jackson.*
配置密钥应用于Jackson编解码器。
如果需要添加或自定义编解码器,则可以创建自定义CodecCustomizer
组件,如以下示例所示:
- import org.springframework.boot.web.codec.CodecCustomizer;
-
- @Configuration
- public class MyConfiguration {
-
- @Bean
- public CodecCustomizer myCodecCustomizer() {
- return codecConfigurer -> {
- // ...
- }
- }
-
- }
你也可以利用引导的自定义JSON序列化程序和反序列化器.
默认情况下,SpringBoot从一个名为/static
(或/public
或/resources
或/META-INF/resources
)在类路径中。它使用ResourceWebHandler
从SpringWebFlux开始,这样您就可以通过添加自己的WebFlux来修改这种行为了。WebFluxConfigurer
和凌驾于addResourceHandlers
方法。
默认情况下,资源被映射到/**
,但是您可以通过设置spring.webflux.static-path-pattern
财产。例如,将所有资源重新定位到/resources/**
可实现以下目标:
spring.webflux.static-path-pattern=/resources/**
还可以通过以下方法自定义静态资源位置:spring.resources.static-locations
。这样做将用目录位置列表替换默认值。如果这样做,默认欢迎页检测切换到自定义位置。所以,如果有一个index.html
在启动时的任何位置,它都是应用程序的主页。
除了前面列出的“标准”静态资源位置之外,还为WebJars内容。中具有路径的任何资源。/webjars/**
如果JAR文件以Webjars格式打包,则从JAR文件中提供服务。
![]() |
SpringWebFlux应用程序并不严格依赖ServletAPI,因此它们不能作为WAR文件部署,也不使用 |
除了RESTWeb服务之外,还可以使用SpringWebFlux提供动态HTML内容。SpringWebFlux支持多种模板技术,包括Thymeleaf、FreeMarker和胡子。
SpringBoot包括对下列模板引擎的自动配置支持:
当您使用默认配置的模板引擎之一时,您的模板将自动从src/main/resources/templates
.
Spring Boot提供了一个WebExceptionHandler
以合理的方式处理所有错误。它在处理顺序中的位置就在WebFlux提供的处理程序之前,后者被认为是最后一个。对于机器客户端,它生成一个JSON响应,其中包含错误、HTTP状态和异常消息的详细信息。对于浏览器客户端,有一个“Whitelabel”错误处理程序,它以HTML格式呈现相同的数据。您还可以提供自己的HTML模板来显示错误(请参阅下一节).
自定义此特性的第一步通常涉及使用现有机制,但替换或增强错误内容。为此,可以添加类型为ErrorAttributes
.
若要更改错误处理行为,可以实现ErrorWebExceptionHandler
并注册该类型的bean定义。因为WebExceptionHandler
是相当低级的,SpringBoot也提供了方便。AbstractErrorWebExceptionHandler
为了让您以WebFlux函数的方式处理错误,如下面的示例所示:
- public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
-
- // Define constructor here
-
- @Override
- protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
-
- return RouterFunctions
- .route(aPredicate, aHandler)
- .andRoute(anotherPredicate, anotherHandler);
- }
-
- }
要获得更完整的图片,还可以使用子类。DefaultErrorWebExceptionHandler
直接覆盖特定方法。
自定义错误页
如果要显示给定状态代码的自定义HTML错误页,可以将文件添加到/error
文件夹。错误页可以是静态HTML(即在任何静态资源文件夹下添加),也可以是用模板构建的。文件的名称应该是确切的状态代码或序列掩码。
例如,要映射404
对于静态HTML文件,文件夹结构如下:
- src/
- +- main/
- +- java/
- | + <source code>
- +- resources/
- +- public/
- +- error/
- | +- 404.html
- +- <other public assets>
映射所有5xx
使用胡子模板出错,文件夹结构如下所示:
- src/
- +- main/
- +- java/
- | + <source code>
- +- resources/
- +- templates/
- +- error/
- | +- 5xx.mustache
- +- <other templates>
SpringWebFlux提供了一个WebFilter
接口,可用于过滤HTTP请求-响应交换。WebFilter
应用程序上下文中的bean将自动用于筛选每个交换。
在筛选器的顺序很重要的地方,它们可以实现。Ordered
或用@Order
。SpringBoot自动配置可以为您配置Web过滤器。这样做时,将使用下表中显示的命令:
Web过滤器 | 命令 |
---|---|
|
|
|
|
|
|
如果您更喜欢用于REST端点的JAX-RS编程模型,则可以使用可用的实现之一,而不是SpringMVC。泽西和ApacheCXF工作得很好。CXF要求您注册它的Servlet
或Filter
作为@Bean
在您的应用程序上下文中。泽西有一些原生的Spring支持,所以我们还在SpringBoot中为它提供了自动配置支持,同时还提供了一个启动器。
要开始使用泽西,包括spring-boot-starter-jersey
作为一种依赖,那么你就需要一种依赖。@Bean
类型ResourceConfig
在其中注册所有端点,如以下示例所示:
- @Component
- public class JerseyConfig extends ResourceConfig {
-
- public JerseyConfig() {
- register(Endpoint.class);
- }
-
- }
![]() |
泽西对扫描可执行档案的支持相当有限。例如,它无法扫描在 |
对于更高级的自定义,还可以注册任意数量的实现ResourceConfigCustomizer
.
所有注册的端点应该是@Components
使用HTTP资源注释(@GET
),如以下示例所示:
- @Component
- @Path("/hello")
- public class Endpoint {
-
- @GET
- public String message() {
- return "Hello";
- }
-
- }
因为Endpoint
是春天@Component
,它的生命周期由Spring管理,您可以使用@Autowired
注释注入依赖项并使用@Value
注解注入外部配置。默认情况下,Jerseyservlet被注册并映射到/*
。可以通过添加@ApplicationPath
敬你的ResourceConfig
.
默认情况下,泽西岛被设置为@Bean
类型ServletRegistrationBean
命名jerseyServletRegistration
。默认情况下,servlet是延迟初始化的,但是可以通过设置spring.jersey.servlet.load-on-startup
。您可以使用相同的名称创建自己的bean,从而禁用或重写该bean。还可以通过设置spring.jersey.type=filter
(在这种情况下,@Bean
替换或覆盖是jerseyFilterRegistration
)过滤器有一个@Order
,您可以将其设置为spring.jersey.filter.order
。servlet和过滤器注册都可以通过以下方式给出init参数:spring.jersey.init.*
若要指定属性映射,请执行以下操作。
有一个泽西样本这样你就能看到如何安排好一切。
SpringBoot包括对嵌入式系统的支持猫猫, 码头,和下引服务器。大多数开发人员使用适当的“初学者”来获得完全配置的实例。默认情况下,嵌入式服务器侦听端口上的HTTP请求8080
.
![]() |
如果您选择使用Tomcat onCentOS,请注意,默认情况下,临时目录用于存储已编译的JSP、文件上载等。此目录可由 |
当使用嵌入式servlet容器时,可以注册servlet、过滤器和所有侦听器(如HttpSessionListener
),通过使用Springbean或扫描servlet组件。
将servlet、过滤器和侦听器注册为Springbean
任何Servlet
, Filter
,或Servlet*Listener
实例,即Springbean在嵌入式容器中注册。如果要引用application.properties
在配置过程中。
默认情况下,如果上下文仅包含单个servlet,则将其映射到/
。对于多个Servlet bean,bean名称用作路径前缀。过滤器映射到/*
.
如果基于约定的映射不够灵活,则可以使用ServletRegistrationBean
, FilterRegistrationBean
,和ServletListenerRegistrationBean
类用于完全控制。
SpringBoot提供了许多自动配置,可以定义过滤器bean。下面是几个过滤器的示例及其各自的顺序(低阶值意味着更高的优先级):
Servlet过滤器 | 命令 |
---|---|
|
|
|
|
|
|
|
|
通常是安全的,让过滤豆子无序。
如果需要特定的订单,则应避免配置一个筛选器,该筛选器将在Ordered.HIGHEST_PRECEDENCE
,因为它可能与应用程序的字符编码配置背道而驰。如果servlet筛选器包装了请求,则应该将其配置为小于或等于FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER
.
嵌入式servlet容器不直接执行Servlet3.0+javax.servlet.ServletContainerInitializer
界面或弹簧org.springframework.web.WebApplicationInitializer
接口。这是一个有意的设计决策,旨在降低第三方库在WAR中运行可能破坏SpringBoot应用程序的风险。
如果需要在SpringBoot应用程序中执行servlet上下文初始化,则应该注册一个实现org.springframework.boot.web.servlet.ServletContextInitializer
接口。单曲onStartup
方法提供对ServletContext
并且,如果有必要,可以很容易地用作现有的适配器。WebApplicationInitializer
.
扫描servlet、过滤器和侦听器
使用嵌入式容器时,自动注册带注释的类@WebServlet
, @WebFilter
,和@WebListener
可以通过以下方式启用@ServletComponentScan
.
![]() |
|
在引擎盖下,SpringBoot使用了一种不同类型的ApplicationContext
支持嵌入式servlet容器。这,这个,那,那个ServletWebServerApplicationContext
是一种特殊的WebApplicationContext
通过搜索单个ServletWebServerFactory
豆子通常是TomcatServletWebServerFactory
, JettyServletWebServerFactory
,或UndertowServletWebServerFactory
已经自动配置好了。
![]() |
您通常不需要知道这些实现类。大多数应用程序都是自动配置的,并且 |
可以使用Spring配置常见的servlet容器设置Environment
财产。通常,您将在application.properties
档案。
常见的服务器设置包括:
server.port
),要绑定到的接口地址。server.address
等等。server.servlet.session.persistence
),会话超时(server.servlet.session.timeout
),会话数据的位置(server.servlet.session.store-dir
),以及会话-cookie配置(server.servlet.session.cookie.*
).server.error.path
等等。SpringBoot尽可能多地尝试公开公共设置,但这并不总是可能的。对于这些情况,专用名称空间提供特定于服务器的自定义(请参阅server.tomcat
和server.undertow
)例如访问日志可以使用嵌入式servlet容器的特定功能进行配置。
![]() |
见 |
程序定制
如果需要以编程方式配置嵌入的servlet容器,则可以注册实现WebServerFactoryCustomizer
接口。WebServerFactoryCustomizer
提供对ConfigurableServletWebServerFactory
,其中包括许多定制的setter方法。下面的示例显示了以编程方式设置端口:
- import org.springframework.boot.web.server.WebServerFactoryCustomizer;
- import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
- import org.springframework.stereotype.Component;
-
- @Component
- public class CustomizationBean implements 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"));
- return factory;
- }
为许多配置选项提供了setter。如果您需要做一些更有异国情调的事情,还提供了几个受保护的方法“钩子”。见源代码文档关于细节。
当运行使用嵌入式servlet容器(并打包为可执行存档)的SpringBoot应用程序时,JSP支持有一些限制。
java -jar
,也可以部署到任何标准容器中。在使用可执行JAR时,不支持JPS。error.jsp
页不覆盖默认视图。错误处理. 自定义错误页应该用它代替。有一个JSP样本这样你就能看到如何安排好一切。
如果弹簧安全在类路径上,则Web应用程序在默认情况下是安全的。Spring Boot依赖SpringSecurity的内容协商策略来决定是否使用httpBasic
或formLogin
。若要向web应用程序添加方法级安全性,还可以添加@EnableGlobalMethodSecurity
有你想要的设置。更多信息可在弹簧安全参考指南.
默认UserDetailsService
只有一个用户。用户名是user
,密码是随机的,在应用程序启动时在信息级别打印,如下面的示例所示:
Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
![]() |
如果您微调日志记录配置,请确保 |
您可以通过提供spring.security.user.name
和spring.security.user.password
.
默认情况下,Web应用程序中获得的基本功能如下:
UserDetailsService
(或ReactiveUserDetailsService
在WebFlux应用程序的情况下,bean具有内存存储和生成密码的单个用户(请参见SecurityProperties.User
对于用户的属性)。DefaultAuthenticationEventPublisher
用于发布身份验证事件。你可以提供不同的AuthenticationEventPublisher
为它添加一个豆子。
默认安全配置是在SecurityAutoConfiguration
和UserDetailsServiceAutoConfiguration
. SecurityAutoConfiguration
进口品SpringBootWebSecurityConfiguration
对于网络安全和UserDetailsServiceAutoConfiguration
配置身份验证,这也与非web应用程序相关。若要完全关闭默认web应用程序安全配置,可以添加类型为WebSecurityConfigurerAdapter
(这样做不会禁用UserDetailsService
配置或执行器的安全性)。
也可以关闭UserDetailsService
配置时,可以添加类型为UserDetailsService
, AuthenticationProvider
,或AuthenticationManager
。中有几个安全应用程序。弹簧启动样本让您从通用例开始。
可以通过添加自定义来重写访问规则。WebSecurityConfigurerAdapter
。SpringBoot提供了方便的方法,可以用来覆盖执行器端点和静态资源的访问规则。EndpointRequest
可以用来创建RequestMatcher
,这是基于management.endpoints.web.base-path
财产。PathRequest
可以用来创建RequestMatcher
用于常用地点的资源。
类似于SpringMVC应用程序,可以通过添加spring-boot-starter-security
依赖。默认安全配置是在ReactiveSecurityAutoConfiguration
和UserDetailsServiceAutoConfiguration
. ReactiveSecurityAutoConfiguration
进口品WebFluxSecurityConfiguration
对于网络安全和UserDetailsServiceAutoConfiguration
配置身份验证,这也与非web应用程序相关。若要完全关闭默认web应用程序安全配置,可以添加类型为WebFilterChainProxy
(这样做不会禁用UserDetailsService
配置或执行器的安全性)。
也可以关闭UserDetailsService
配置时,可以添加类型为ReactiveUserDetailsService
或ReactiveAuthenticationManager
.
可以通过添加自定义来配置访问规则。SecurityWebFilterChain
。SpringBoot提供了方便的方法,可以用来覆盖执行器端点和静态资源的访问规则。EndpointRequest
可以用来创建ServerWebExchangeMatcher
,这是基于management.endpoints.web.base-path
财产。
PathRequest
可以用来创建ServerWebExchangeMatcher
用于常用地点的资源。
例如,您可以通过添加以下内容来自定义您的安全配置:
- @Bean
- public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
- return http
- .authorizeExchange()
- .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
- .pathMatchers("/foo", "/bar")
- .authenticated().and()
- .formLogin().and()
- .build();
- }
OAuth2是Spring支持的广泛使用的授权框架。
如果你有spring-security-oauth2-client
在类路径上,您可以利用一些自动配置来轻松地设置OAuth2/OpenIDConnect客户端。此配置使用OAuth2ClientProperties
.
对象下注册多个OAuth2/OpenID连接提供程序。spring.security.oauth2.client.provider
前缀,如以下示例所示:
- spring.security.oauth2.client.provider.my-oauth-provider.authorization-uri=http://my-auth-server/oauth/authorize
- spring.security.oauth2.client.provider.my-oauth-provider.token-uri=http://my-auth-server/oauth/token
- spring.security.oauth2.client.provider.my-oauth-provider.user-info-uri=http://my-auth-server/userinfo
- spring.security.oauth2.client.provider.my-oauth-provider.user-info-authentication-method=header
- spring.security.oauth2.client.provider.my-oauth-provider.jwk-set-uri=http://my-auth-server/token_keys
- spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=name
对于支持OpenID连接提供程序的OpenID连接发现,可以进一步简化配置。提供程序需要配置issuer-uri
它断言的URI是它的颁发者标识符。例如,如果issuer-uri
提供的是“https:/example.com”,然后是OpenID Provider Configuration Request
将被制作成“https://example.com/.well-known/openid-configuration”.预期结果将是OpenID Provider Configuration Response
。下面的示例演示如何使用issuer-uri
:
spring.security.oauth2.client.provider.oidc-provider.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/
OpenID连接登录客户端注册
对象下注册多个开放ID连接客户端。spring.security.oauth2.client.registration.login
前缀,如以下示例所示:
spring.security.oauth2.client.registration.login.my-client-1.client-id=abcd spring.security.oauth2.client.registration.login.my-client-1.client-secret=password spring.security.oauth2.client.registration.login.my-client-1.client-name=Client for user scope spring.security.oauth2.client.registration.login.my-client-1.provider=my-oauth-provider spring.security.oauth2.client.registration.login.my-client-1.scope=user spring.security.oauth2.client.registration.login.my-client-1.redirect-uri=http://localhost:8080/login/oauth2/code/my-client-1 spring.security.oauth2.client.registration.login.my-client-1.client-authentication-method=basic spring.security.oauth2.client.registration.login.my-client-1.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.login.my-client-2.client-id=abcd spring.security.oauth2.client.registration.login.my-client-2.client-secret=password spring.security.oauth2.client.registration.login.my-client-2.client-name=Client for email scope spring.security.oauth2.client.registration.login.my-client-2.provider=my-oauth-provider spring.security.oauth2.client.registration.login.my-client-2.scope=email spring.security.oauth2.client.registration.login.my-client-2.redirect-uri=http://localhost:8080/login/oauth2/code/my-client-2 spring.security.oauth2.client.registration.login.my-client-2.client-authentication-method=basic spring.security.oauth2.client.registration.login.my-client-2.authorization-grant-type=authorization_code
默认情况下,Spring的OAuth2LoginAuthenticationFilter
只处理URL匹配/login/oauth2/code/*
。如果要自定义redirect-uri
要使用不同的模式,您需要提供配置来处理该自定义模式。例如,对于servlet应用程序,可以添加自己的WebSecurityConfigurerAdapter
这类似于以下几点:
- public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .oauth2Login()
- .redirectionEndpoint()
- .baseUri("/custom-callback");
- }
- }
同样的属性也适用于servlet和反应性应用程序。
OAuth2授权代码客户端注册
您可以注册多个OAuth2authorization_code
客户在spring.security.oauth2.client.registration.authorization-code
前缀,如以下示例所示:
spring.security.oauth2.client.registration.authorization-code.my-client-1.client-id=abcd spring.security.oauth2.client.registration.authorization-code.my-client-1.client-secret=password spring.security.oauth2.client.registration.authorization-code.my-client-1.client-name=Client for user scope spring.security.oauth2.client.registration.authorization-code.my-client-1.provider=my-oauth-provider spring.security.oauth2.client.registration.authorization-code.my-client-1.scope=user spring.security.oauth2.client.registration.authorization-code.my-client-1.redirect-uri=http://my-redirect-uri.com spring.security.oauth2.client.registration.authorization-code.my-client-1.client-authentication-method=basic spring.security.oauth2.client.registration.authorization-code.my-client-1.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.authorization-code.my-client-2.client-id=abcd spring.security.oauth2.client.registration.authorization-code.my-client-2.client-secret=password spring.security.oauth2.client.registration.authorization-code.my-client-2.client-name=Client for email scope spring.security.oauth2.client.registration.authorization-code.my-client-2.provider=my-oauth-provider spring.security.oauth2.client.registration.authorization-code.my-client-2.scope=email spring.security.oauth2.client.registration.authorization-code.my-client-2.redirect-uri=http://my-redirect-uri.com spring.security.oauth2.client.registration.authorization-code.my-client-2.client-authentication-method=basic spring.security.oauth2.client.registration.authorization-code.my-client-2.authorization-grant-type=authorization_code
OAuth2通用提供者的客户端注册
对于常见的OAuth2和OpenID提供商,包括Google、Gizub、Facebook和Okta,我们提供了一组提供者默认值(google
, github
, facebook
,和okta
分别)。
如果不需要自定义这些提供程序,则可以将provider
属性为需要推断默认值的属性。此外,如果客户端的ID与默认支持的提供程序匹配,SpringBoot也会推断这一点。
换句话说,以下示例中的两个配置使用Google Provider:
- spring.security.oauth2.client.registration.login.my-client.client-id=abcd
- spring.security.oauth2.client.registration.login.my-client.client-secret=password
- spring.security.oauth2.client.registration.login.my-client.provider=google
-
- spring.security.oauth2.client.registration.login.google.client-id=abcd
- spring.security.oauth2.client.registration.login.google.client-secret=password
如果你有spring-security-oauth2-resource-server
在类路径上,只要指定了JWK集URI或OIDC Issuer URI,Spring Boot就可以设置OAuth2资源服务器,如以下示例所示:
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/oauth2/default/v1/keys
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/
同样的属性也适用于servlet和反应性应用程序。
或者,您可以定义自己的JwtDecoder
用于servlet应用程序的bean或ReactiveJwtDecoder
用于反应性应用。
目前,SpringSecurity不支持实现OAuth2.0授权服务器。但是,此功能可从弹簧安全OAuth项目,它最终将被SpringSecurity完全取代。在此之前,您可以使用spring-security-oauth2-autoconfigure
模块以轻松设置OAuth2.0授权服务器;请参见其文献资料为了得到指示。
为安全起见,除/health
和/info
默认情况下禁用。这,这个,那,那个management.endpoints.web.exposure.include
属性可用于启用执行机构。
如果Spring安全性位于类路径上,并且没有其他WebSecurityConfigurerAdapter,则除/health
和/info
由SpringBoot自动配置保护。如果您定义了一个自定义WebSecurityConfigurerAdapter
,SpringBoot自动配置将退出,您将完全控制执行器访问规则。
![]() |
在设置 |
由于SpringBoot依赖SpringSecurity的默认设置,默认情况下CSRF保护是打开的。这意味着执行器端点需要POST
(关机和记录器端点),PUT
或DELETE
在使用默认安全配置时,将得到一个403禁止的错误。
![]() |
只有在创建非浏览器客户端使用的服务时,我们才建议完全禁用CSRF保护。 |
有关csrf保护的其他信息,请参阅弹簧安全参考指南.
这,这个,那,那个弹簧框架提供对使用sql数据库的广泛支持,可直接使用jdbc访问JdbcTemplate
来完成诸如Hibernate之类的“对象关系映射”技术。弹簧数据提供额外的功能级别:创建Repository
直接从接口实现,并使用约定从您的方法名称生成查询。
爪哇javax.sql.DataSource
接口提供了处理数据库连接的标准方法。传统上,“DataSource”使用URL
以及建立数据库连接的一些凭据。
![]() |
看见“如何到”一节对于更高级的示例,通常要完全控制DataSource的配置。 |
使用内存内嵌入式数据库开发应用程序通常很方便.显然,内存中的数据库不提供持久存储.您需要在应用程序启动时填充数据库,并准备好在应用程序结束时丢弃数据。
![]() |
“如何到”部分包括一节,介绍如何初始化数据库。. |
弹簧引导可以自动配置嵌入式。氢, HSQL,和德比数据库。您不需要提供任何连接URL。只需将构建依赖项包含到要使用的嵌入式数据库。
![]() |
如果您在测试中使用此功能,您可能会注意到,无论您使用多少应用程序上下文,整个测试套件都重用相同的数据库。如果要确保每个上下文都有单独的嵌入式数据库,则应设置 |
例如,典型的POM依赖关系如下:
- <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>
![]() |
你需要依赖 |
![]() |
如果出于任何原因,您确实为嵌入式数据库配置了连接URL,请注意确保禁用了数据库的自动关闭。如果你使用h2,你应该使用 |
还可以使用池自动配置生产数据库连接。DataSource
。Spring Boot使用以下算法来选择特定的实现:
DataSource
是可用的,我们用它。如果您使用spring-boot-starter-jdbc
或spring-boot-starter-data-jpa
“Starters”,您将自动获得一个依赖项HikariCP
.
![]() |
可以完全绕过该算法,并通过设置 |
![]() |
其他连接池始终可以手动配置。如果你定义了你自己的 |
中的外部配置属性控制数据源配置。spring.datasource.*
。例如,您可以在application.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
![]() |
您至少应该通过设置 |
![]() |
您通常不需要指定 |
![]() |
为了汇集 |
看见DataSourceProperties
有关更多受支持的选项。无论实际实现如何,这些都是有效的标准选项。还可以使用它们各自的前缀对特定于实现的设置进行微调(spring.datasource.hikari.*
, spring.datasource.tomcat.*
,和spring.datasource.dbcp2.*
)有关详细信息,请参阅您正在使用的连接池实现的文档。
例如,如果您使用Tomcat连接池,您可以自定义许多其他设置,如以下示例所示:
- # Number of ms to wait before throwing an exception if no connection is available.
- spring.datasource.tomcat.max-wait=10000
-
- # Maximum number of active connections that can be allocated from this pool at the same time.
- spring.datasource.tomcat.max-active=50
-
- # Validate the connection before borrowing it from the pool.
- spring.datasource.tomcat.test-on-borrow=true
如果将SpringBoot应用程序部署到ApplicationServer,则可能需要使用ApplicationServer的内置特性配置和管理DataSource,并使用JNDI访问它。
这,这个,那,那个spring.datasource.jndi-name
属性可用作spring.datasource.url
, spring.datasource.username
,和spring.datasource.password
属性访问DataSource
从特定的JNDI位置。例如,application.properties
演示如何按定义访问JBossDataSource
:
spring.datasource.jndi-name=java:jboss/datasources/customers
春天的JdbcTemplate
和NamedParameterJdbcTemplate
类是自动配置的,您可以@Autowire
它们直接进入您自己的bean中,如下面的示例所示:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final JdbcTemplate jdbcTemplate; @Autowired public MyBean(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } // ... }
控件可以自定义模板的某些属性。spring.jdbc.template.*
属性,如以下示例所示:
spring.jdbc.template.max-rows=500
![]() |
这,这个,那,那个 |
JavaPersistenceAPI是一种标准技术,允许您将对象“映射”到关系数据库。这,这个,那,那个spring-boot-starter-data-jpa
POM提供了一种快速入门的方法。它提供了以下关键依赖项:
![]() |
我们不会详细讨论JPA或弹簧数据这里你可以跟着“使用JPA访问数据”从spring.io并阅读春季数据JPA和冬眠参考文件。 |
传统上,JPA“实体”类是在persistence.xml
档案。对于SpringBoot,这个文件是不必要的,取而代之的是“实体扫描”。默认情况下,主配置类下面的所有包(用@EnableAutoConfiguration
或@SpringBootApplication
)被搜查。
带注释的任何类@Entity
, @Embeddable
,或@MappedSuperclass
都被考虑了。典型的实体类似于以下示例:
package com.example.myapp.domain; import java.io.Serializable; import javax.persistence.*; @Entity public class City implements Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private String state; // ... additional members, often include @OneToMany mappings protected City() { // no-args constructor required by JPA spec // this one is protected since it shouldn't be used directly } public City(String name, String state) { this.name = name; this.state = state; } public String getName() { return this.name; } public String getState() { return this.state; } // ... etc }
![]() |
属性自定义实体扫描位置。 |
春季数据JPA存储库是您可以定义的访问数据的接口。JPA查询是根据您的方法名称自动创建的。例如,CityRepository
接口可能会声明findAllByState(String state)
方法来查找处于给定状态的所有城市。
对于更复杂的查询,可以使用Spring数据的Query
注释
Spring数据存储库通常从Repository
或CrudRepository
接口。如果使用自动配置,则从包含主配置类的包(带注释的类)中搜索存储库。@EnableAutoConfiguration
或@SpringBootApplication
)趴下。
下面的示例显示了典型的Spring数据存储库接口定义:
- package com.example.myapp.domain;
-
- import org.springframework.data.domain.*;
- import org.springframework.data.repository.*;
-
- public interface CityRepository extends Repository<City, Long> {
-
- Page<City> findAll(Pageable pageable);
-
- City findByNameAndStateAllIgnoringCase(String name, String state);
-
- }
SpringDataJPA存储库支持三种不同的引导模式:默认模式、延迟模式和延迟模式。若要启用延迟或延迟引导,请将spring.data.jpa.repositories.bootstrap-mode
到deferred
或lazy
分别。使用延迟或延迟引导时,自动配置EntityManagerFactoryBuilder
将使用上下文的异步任务执行器(如果有的话)作为引导执行器。
![]() |
我们几乎没有触及SpringDataJPA的表面。有关详细信息,请参阅Spring数据JPA参考文档. |
默认情况下,会自动创建jpa数据库。只如果使用嵌入式数据库(H2、HSQL或Derby)。可以通过以下方法显式配置JPA设置:spring.jpa.*
财产。例如,要创建和删除表,可以将以下行添加到application.properties
:
spring.jpa.hibernate.ddl-auto=create-drop
![]() |
Hibernate自己的内部属性名(如果您更好地记住它)是 |
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
前面示例中的行传递的值为true
为hibernate.globally_quoted_identifiers
属性设置为Hibernate实体管理器。
默认情况下,DDL执行(或验证)将推迟到ApplicationContext
已经开始了。还有一个spring.jpa.generate-ddl
标志,但如果Hibernate自动配置处于活动状态,则不使用它,因为ddl-auto
设置更细粒度.
如果正在运行web应用程序,默认情况下SpringBoot注册OpenEntityManagerInViewInterceptor
应用“OpenEntityManager in View”模式,允许在web视图中延迟加载。如果不想要这种行为,则应设置spring.jpa.open-in-view
到false
在你的application.properties
.
Spring数据包括对jdbc的存储库支持,并将自动为CrudRepository
。对于更高级的查询,@Query
提供了注释。
当类路径上有必要的依赖项时,SpringBoot将自动配置Spring数据的JDBC存储库。可以通过一个依赖项将它们添加到您的项目中。spring-boot-starter-data-jdbc
。如果有必要,可以通过添加@EnableJdbcRepositories
注释或JdbcConfiguration
应用程序的子类。
![]() |
有关SpringDataJDBC的详细信息,请参阅参考文献. |
这,这个,那,那个H2数据库提供一个基于浏览器的控制台Spring Boot可以自动为您配置。当满足下列条件时,控制台将自动配置:
com.h2database:h2
在类路径上。![]() |
如果您没有使用SpringBoot的开发工具,但仍然希望使用h2的控制台,则可以配置 |
![]() |
h2控制台仅供开发期间使用,因此您应注意确保 |
默认情况下,控制台可在/h2-console
。控件可以自定义控制台的路径。spring.h2.console.path
财产。
面向Java对象的查询(JOOQ)是一种流行的产品数据奇才它从数据库中生成Java代码,并允许您通过其FLUENT API构建类型安全的SQL查询。商业版本和开源版本都可以与SpringBoot一起使用。
为了使用jOOQ类型安全查询,需要从数据库模式生成Java类。您可以按照JOOQ用户手册。如果您使用jooq-codegen-maven
插件,您也可以使用spring-boot-starter-parent
“父POM”,您可以安全地省略插件的<version>
标签。还可以使用SpringBoot定义的版本变量(如h2.version
)声明插件的数据库依赖关系。下面的清单显示了一个示例:
- <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>

jOOQ提供的Fluent API是通过org.jooq.DSLContext
接口。Spring Boot自动配置DSLContext
作为SpringBean并将其连接到应用程序DataSource
。使用DSLContext
,你可以@Autowire
如以下示例所示:
- @Component
- public class JooqExample implements CommandLineRunner {
-
- private final DSLContext create;
-
- @Autowired
- public JooqExample(DSLContext dslContext) {
- this.create = dslContext;
- }
-
- }
![]() |
jOOQ手册倾向于使用一个名为 |
然后,您可以使用DSLContext
若要构造查询,请参见以下示例:
- 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);
- }
除非spring.jooq.sql-dialect
属性,Spring Boot将确定要用于数据源的SQL方言。如果SpringBoot无法检测到方言,它将使用DEFAULT
.
![]() |
SpringBoot只能自动配置jOOQ开源版本支持的方言。 |
可以通过定义自己的自定义来实现更高级的自定义。@Bean
定义,当jOOQ使用时使用Configuration
是被创造出来的。可以为以下jOOQ类型定义bean:
ConnectionProvider
ExecutorProvider
TransactionProvider
RecordMapperProvider
RecordUnmapperProvider
RecordListenerProvider
ExecuteListenerProvider
VisitListenerProvider
TransactionListenerProvider
您也可以创建自己的org.jooq.Configuration
@Bean
如果您想完全控制jOOQ配置。
Spring数据提供了帮助您访问各种NoSQL技术的其他项目,包括:MongoDB, Neo4J, 弹性搜索, 索尔, 雷迪斯, 双子火, 卡桑德拉, Couchbase和LDAP。SpringBoot为Redis、MongoDB、Neo4j、Elasticsearch、Solr Cassandra、Couchbase和LDAP提供了自动配置。您可以使用其他项目,但您必须自己配置它们。请参阅适当的参考文件projects.spring.io/spring-data.
雷迪斯是一个缓存、消息代理和功能丰富的键值存储。Spring Boot为生菜和吉迪斯客户端库及其之上的抽象春季数据红宝石.
有一个spring-boot-starter-data-redis
用于以方便的方式收集依赖项的“初学者”。默认情况下,它使用生菜。该启动器同时处理传统应用程序和反应性应用程序。
![]() |
我们还提供 |
您可以注入一个自动配置的RedisConnectionFactory
, StringRedisTemplate
或香草RedisTemplate
实例,就像其他SpringBean一样。默认情况下,实例试图连接到localhost:6379
。下面的清单显示了这样一个bean的示例:
- @Component
- public class MyBean {
-
- private StringRedisTemplate template;
-
- @Autowired
- public MyBean(StringRedisTemplate template) {
- this.template = template;
- }
-
- // ...
-
- }
![]() |
您还可以注册任意数量的bean,这些bean实现了 |
如果你加上你自己的@Bean
在任何自动配置的类型中,它都将替换默认值(除非在RedisTemplate
,当排除基于bean名称时,redisTemplate
,而不是它的类型)。默认情况下,如果commons-pool2
在类路径上,您将得到一个池连接工厂。
MongoDB是一个开源的NoSQL文档数据库,它使用类似JSON的模式,而不是传统的基于表的关系数据。SpringBoot为使用MongoDB提供了一些方便,包括spring-boot-starter-data-mongodb
和spring-boot-starter-data-mongodb-reactive
“先开始”。
要访问MONGO数据库,可以注入一个自动配置的org.springframework.data.mongodb.MongoDbFactory
。默认情况下,实例尝试连接到mongodb://localhost/test
下面的示例演示如何连接到MongoDB数据库:
import org.springframework.data.mongodb.MongoDbFactory; import com.mongodb.DB; @Component public class MyBean { private final 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
或者,只要使用mongo2.x,就可以指定host
/port
。例如,您可以在application.properties
:
- spring.data.mongodb.host=mongoserver
- spring.data.mongodb.port=27017
如果你已经定义了你自己的MongoClient
,它将用于自动配置合适的MongoDbFactory
。双管齐下com.mongodb.MongoClient
和com.mongodb.client.MongoClient
是支持的。
![]() |
如果您使用MONGO3.0 Java驱动程序, |
![]() |
如果 |
![]() |
如果不使用SpringDataMONGO,则可以插入 |
![]() |
如果您使用的是反应性驱动程序,则SSL需要Netty。如果Netty可用,并且尚未定制要使用的工厂,则自动配置将自动配置此工厂。 |
春季数据MongoDB提供一个MongoTemplate
类,它的设计与Spring的非常相似。JdbcTemplate
。同.一样JdbcTemplate
,SpringBoot自动配置bean以注入模板,如下所示:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final MongoTemplate mongoTemplate; @Autowired public MyBean(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } // ... }
见MongoOperations
Javadoc获得完整的细节。
Spring数据包括对MongoDB的存储库支持。与前面讨论的JPA存储库一样,基本原则是根据方法名称自动构造查询。
实际上,SpringDataJPA和SpringDataMongoDB共享相同的公共基础设施。您可以从前面的JPA示例开始,假设City
现在是MONGO数据类,而不是JPA。@Entity
,它以同样的方式工作,如下面的示例所示:
- package com.example.myapp.domain;
-
- import org.springframework.data.domain.*;
- import org.springframework.data.repository.*;
-
- public interface CityRepository extends Repository<City, Long> {
-
- Page<City> findAll(Pageable pageable);
-
- City findByNameAndStateAllIgnoringCase(String name, String state);
-
- }
![]() |
控件可以自定义文档扫描位置。 |
![]() |
有关SpringDataMongoDB(包括其富对象映射技术)的详细信息,请参阅参考文献. |
Spring Boot为嵌入式蒙戈。若要在SpringBoot应用程序中使用它,请在de.flapdoodle.embed:de.flapdoodle.embed.mongo
.
可以通过设置spring.data.mongodb.port
财产。若要使用随机分配的空闲端口,请使用值0。这,这个,那,那个MongoClient
由MongoAutoConfiguration
自动配置为使用随机分配的端口。
![]() |
如果不配置自定义端口,默认情况下,嵌入式支持将使用随机端口(而不是27017)。 |
如果类路径上有SLF4J,则MONGO产生的输出将自动路由到名为org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo
.
你可以宣布你自己的IMongodConfig
和IRuntimeConfig
bean来控制MONGO实例的配置和日志路由。
Neo4j是一个开源的NoSQL图形数据库,它使用由一级关系连接的节点的丰富数据模型,比传统的RDBMS方法更适合连接大数据。SpringBoot为使用Neo4j提供了一些方便,包括spring-boot-starter-data-neo4j
“初学者”。
要访问neo4j服务器,可以注入一个自动配置的org.neo4j.ogm.session.Session
。默认情况下,实例尝试连接到localhost:7687
使用博尔特协议。下面的示例演示如何注入Neo4jSession
:
- @Component
- public class MyBean {
-
- private final Session session;
-
- @Autowired
- public MyBean(Session session) {
- this.session = session;
- }
-
- // ...
-
- }
可以通过设置spring.data.neo4j.*
属性,如以下示例所示:
- spring.data.neo4j.uri=bolt://my-server:7687
- spring.data.neo4j.username=neo4j
- spring.data.neo4j.password=secret
可以通过添加org.neo4j.ogm.config.Configuration
@Bean
。同时,添加一个@Bean
类型SessionFactory
禁用自动配置,并给予您完全控制。
如果你加上org.neo4j:neo4j-ogm-embedded-driver
对于应用程序的依赖项,SpringBoot会自动配置一个在进程内嵌入的Neo4j实例,该实例在应用程序关闭时不会持久化任何数据。
![]() |
由于嵌入的Neo4jOGM驱动程序不提供Neo4j内核本身,所以必须声明 |
当类路径上有多个驱动程序时,嵌入式驱动程序优先于其他驱动程序。通过设置,可以显式禁用嵌入模式。spring.data.neo4j.embedded.enabled=false
.
数据Neo4j试验如果嵌入式驱动程序和Neo4j内核位于上述类路径上,则自动使用嵌入式Neo4j实例。
![]() |
您可以通过为配置中的数据库文件提供路径来启用嵌入式模式的持久性。 |
默认情况下,如果您正在运行Web应用程序,会话将绑定到请求的整个处理过程中的线程(也就是说,它使用“OpenSession in View”模式)。如果不想要这种行为,请将以下行添加到application.properties
档案:
spring.data.neo4j.open-in-view=false
Spring数据包括对Neo4j的存储库支持。
与许多其他Spring数据模块一样,SpringDataNeo4j与SpringDataJPA共享公共基础设施。您可以从前面的JPA示例开始,并定义City
作为Neo4j OGM@NodeEntity
而不是JPA@Entity
存储库抽象以同样的方式工作,如下面的示例所示:
- package com.example.myapp.domain;
-
- import java.util.Optional;
-
- import org.springframework.data.neo4j.repository.*;
-
- public interface CityRepository extends Neo4jRepository<City, Long> {
-
- Optional<City> findOneByNameAndState(String name, String state);
-
- }
这,这个,那,那个spring-boot-starter-data-neo4j
“初学者”启用了存储库支持和事务管理。可以自定义查找存储库和实体的位置,方法是@EnableNeo4jRepositories
和@EntityScan
分别在@Configuration
-豆子
![]() |
有关SpringDataNeo4j(包括其对象映射技术)的详细信息,请参阅参考文献. |
弹簧数据Gemfire提供方便的Spring友好工具来访问枢轴双子火数据管理平台。有一个spring-boot-starter-data-gemfire
用于以方便的方式收集依赖项的“初学者”。Gemfire目前不支持自动配置,但是可以使用单一注释:@EnableGemfireRepositories
.
阿帕奇索尔是搜索引擎。Spring Boot为Solr 5客户端库提供了基本的自动配置,并且它之上的抽象由弹簧数据Solr。有一个spring-boot-starter-data-solr
用于以方便的方式收集依赖项的“初学者”。
您可以注入一个自动配置的SolrClient
实例,就像其他Springbean一样。默认情况下,实例尝试连接到localhost:8983/solr
。下面的示例演示如何注入Solrbean:
- @Component
- public class MyBean {
-
- private SolrClient solr;
-
- @Autowired
- public MyBean(SolrClient solr) {
- this.solr = solr;
- }
-
- // ...
-
- }
如果你加上你自己的@Bean
类型SolrClient
,它将替换默认值。
Spring数据包括对ApacheSolr的存储库支持。与前面讨论的JPA存储库一样,基本原则是根据方法名称自动为\You构造查询。
实际上,SpringDataJPA和SpringDataSolr共享相同的公共基础设施。您可以从前面的JPA示例开始,假设City
现在是@SolrDocument
类而不是JPA@Entity
,以同样的方式工作。
![]() |
有关SpringDataSolr的详细信息,请参阅参考文献. |
弹性搜索是一个开源、分布式、RESTful的搜索和分析引擎。SpringBoot为弹力搜索提供了基本的自动配置。
SpringBoot支持几个HTTP客户端:
传输客户端仍由弹簧数据弹性搜索,您可以开始使用spring-boot-starter-data-elasticsearch
“初学者”。
ElasticSearch船两个不同的REST客户端您可以用来查询集群:“低级”客户端和“高级”客户端。
如果你有org.elasticsearch.client:elasticsearch-rest-client
依赖于类路径,SpringBoot将自动配置和注册RestClient
bean,在默认情况下是目标。localhost:9200
。你可以进一步调整RestClient
配置,如以下示例所示:
- spring.elasticsearch.rest.uris=http://search.example.com:9200
- spring.elasticsearch.rest.username=user
- spring.elasticsearch.rest.password=secret
您还可以注册任意数量的bean,这些bean实现了RestClientBuilderCustomizer
用于更高级的自定义。若要完全控制注册,请定义RestClient
豆子
如果你有org.elasticsearch.client:elasticsearch-rest-high-level-client
依赖于类路径,SpringBoot将自动配置RestHighLevelClient
,它封装了任何现有的RestClient
bean,重用它的HTTP配置。
如果你有Jest
在类路径上,您可以注入一个自动配置的JestClient
默认目标localhost:9200
。您可以进一步优化客户端的配置方式,如以下示例所示:
- 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
您还可以注册任意数量的bean,这些bean实现了HttpClientConfigBuilderCustomizer
用于更高级的自定义。下面的示例优化其他HTTP设置:
- static class HttpSettingsCustomizer implements HttpClientConfigBuilderCustomizer {
-
- @Override
- public void customize(HttpClientConfig.Builder builder) {
- builder.maxTotalConnection(100).defaultMaxTotalConnectionPerRoute(5);
- }
-
- }
若要完全控制注册,请定义JestClient
豆子
要连接到Elasticearch,必须提供一个或多个群集节点的地址。可以通过设置spring.data.elasticsearch.cluster-nodes
属性以逗号分隔。host:port
名单。配置就位后,ElasticsearchTemplate
或TransportClient
可以像任何其他Springbean一样注入,如下面的示例所示:
spring.data.elasticsearch.cluster-nodes=localhost:9300
- @Component
- public class MyBean {
-
- private final ElasticsearchTemplate template;
-
- public MyBean(ElasticsearchTemplate template) {
- this.template = template;
- }
-
- // ...
-
- }
如果你加上你自己的ElasticsearchTemplate
或TransportClient
@Bean
,它将替换默认值。
Spring数据包括对Elasticearch的存储库支持。与前面讨论的JPA存储库一样,基本原则是根据方法名称自动为您构造查询。
实际上,SpringDataJPA和SpringDataElasticearch共享相同的公共基础设施。您可以从前面的JPA示例开始,假设City
现在是一个弹性搜索@Document
类而不是JPA@Entity
,以同样的方式工作。
![]() |
有关Spring数据弹性搜索的详细信息,请参阅参考文献. |
卡桑德拉是一个开放源码的分布式数据库管理系统,旨在处理跨越许多商品服务器的大量数据。Spring Boot为Cassandra提供了自动配置,并在此基础上提供了春季数据卡桑德拉。有一个spring-boot-starter-data-cassandra
用于以方便的方式收集依赖项的“初学者”。
您可以注入一个自动配置的CassandraTemplate
或者卡桑德拉Session
实例,就像对任何其他SpringBean一样。这,这个,那,那个spring.data.cassandra.*
属性可用于自定义连接。一般来说,你提供keyspace-name
和contact-points
属性,如以下示例所示:
- spring.data.cassandra.keyspace-name=mykeyspace
- spring.data.cassandra.contact-points=cassandrahost1,cassandrahost2
下面的代码清单显示了如何注入Cassandrabean:
- @Component
- public class MyBean {
-
- private CassandraTemplate template;
-
- @Autowired
- public MyBean(CassandraTemplate template) {
- this.template = template;
- }
-
- // ...
-
- }
如果你加上你自己的@Bean
类型CassandraTemplate
,它将替换默认值。
Spring数据包括对Cassandra的基本存储库支持。目前,这比前面讨论的JPA存储库更有限,需要用@Query
.
![]() |
有关SpringDataCassandra的详细信息,请参阅参考文献. |
Couchbase是一个开源的、分布式的、面向多模型的面向NoSQL文档的数据库,它是为交互式应用程序优化的.Spring Boot为Couchbase提供了自动配置,并且它之上的抽象由弹簧数据库。确实有。spring-boot-starter-data-couchbase
和spring-boot-starter-data-couchbase-reactive
用于以方便的方式收集依赖项的“启动器”。
你可以得到一个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
![]() |
你需要提供至少引导主机,在这种情况下,桶名是 |
还可以自定义一些CouchbaseEnvironment
设置。例如,以下配置将超时更改为打开新的Bucket
并启用SSL支持:
- 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.*
属性获取更多详细信息。
Spring数据包括对Couchbase的存储库支持。有关SpringDataCouchbase的详细信息,请参阅参考文献.
您可以注入一个自动配置的CouchbaseTemplate
实例,与任何其他SpringBean一样,提供了一个违约 CouchbaseConfigurer
是可用的(正如前面所解释的,启用Couchbase支持时会发生这种情况)。
下面的示例演示如何注入Couchbase bean:
- @Component
- public class MyBean {
-
- private final CouchbaseTemplate template;
-
- @Autowired
- public MyBean(CouchbaseTemplate template) {
- this.template = template;
- }
-
- // ...
-
- }
您可以在自己的配置中定义几个bean来覆盖自动配置提供的bean:
CouchbaseTemplate
@Bean
名为couchbaseTemplate
.IndexManager
@Bean
名为couchbaseIndexManager
.CustomConversions
@Bean
名为couchbaseCustomConversions
.为了避免在您自己的配置中对这些名称进行硬编码,您可以重用这些名称。BeanNames
由SpringDataCouchbase提供。例如,您可以自定义要使用的转换器,如下所示:
- @Configuration
- public class SomeConfiguration {
-
- @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
- public CustomConversions myCustomConversions() {
- return new CustomConversions(...);
- }
-
- // ...
-
- }
![]() |
如果您希望完全绕过SpringDataCouchbase的自动配置,请提供您自己的实现 |
LDAP(轻量级目录访问协议)是一种开放的、与供应商无关的、行业标准的应用程序协议,用于通过IP网络访问和维护分布式目录信息服务。Spring Boot为任何兼容的ldap服务器提供自动配置,以及对内存中嵌入式ldap服务器的支持。无边.
LDAP抽象由春季数据LDAP。有一个spring-boot-starter-data-ldap
用于以方便的方式收集依赖项的“初学者”。
若要连接到LDAP服务器,请确保在spring-boot-starter-data-ldap
“起始”或spring-ldap-core
然后在applicy.properties中声明服务器的URL,如下面的示例所示:
- spring.ldap.urls=ldap://myserver:1235
- spring.ldap.username=admin
- spring.ldap.password=secret
如果需要自定义连接设置,可以使用spring.ldap.base
和spring.ldap.base-environment
财产。
阿LdapContextSource
是基于这些设置自动配置的。如果您需要自定义它,例如使用PooledContextSource
,您仍然可以注入自动配置的LdapContextSource
。确保标记您的定制ContextSource
如@Primary
以便自动配置LdapTemplate
用它。
Spring数据包括对LDAP的存储库支持。有关SpringDataLDAP的详细信息,请参阅参考文献.
您还可以注入一个自动配置的LdapTemplate
实例,与任何其他SpringBean一样,如下面的示例所示:
- @Component
- public class MyBean {
-
- private final LdapTemplate template;
-
- @Autowired
- public MyBean(LdapTemplate template) {
- this.template = template;
- }
-
- // ...
-
- }
出于测试目的,SpringBoot支持自动配置内存中的ldap服务器。无边。若要配置服务器,请将依赖项添加到com.unboundid:unboundid-ldapsdk
并声明base-dn
财产如下:
spring.ldap.embedded.base-dn=dc=spring,dc=io
![]() |
可以定义多个基DN值,但是,由于可分辨名称通常包含逗号,因此必须使用正确的表示法来定义它们。 在YAML文件中,可以使用YAML列表符号: 在属性文件中,必须将索引作为属性名称的一部分: |
默认情况下,服务器在随机端口上启动并触发常规LDAP支持。不需要指定spring.ldap.urls
财产。
如果有一个schema.ldif
文件在您的类路径上,它用于初始化服务器。如果要从其他资源加载初始化脚本,也可以使用spring.ldap.embedded.ldif
财产。
默认情况下,标准模式用于验证LDIF
档案。通过设置spring.ldap.embedded.validation.enabled
财产。如果您有自定义属性,则可以使用spring.ldap.embedded.validation.schema
若要定义自定义属性类型或对象类,请执行以下操作。
InfluxDB它是一个开放源码的时间序列数据库,用于快速、高可用性地存储和检索诸如操作监视、应用度量、物联网传感器数据和实时分析等领域的时间序列数据。
Spring Boot自动配置InfluxDB
实例,只要influxdb-java
客户端位于类路径上,并且设置了数据库的URL,如下面的示例所示:
spring.influx.url=http://172.0.0.1:8086
如果连接到InFluxDB需要用户和密码,则可以将spring.influx.user
和spring.influx.password
相应的属性。
InfluxDB依赖于OkHttp。如果您需要调优http客户端InfluxDB
在幕后使用,您可以注册OkHttpClient.Builder
豆子
SpringFramework支持透明地向应用程序添加缓存。在其核心,抽象将缓存应用于方法,从而减少了基于缓存中可用信息的执行次数。缓存逻辑是透明地应用的,对调用方没有任何干扰。Spring Boot自动配置缓存基础结构,只要通过@EnableCaching
注释
![]() |
检查相关部分更多细节,请参考Spring框架。 |
简而言之,向服务的操作添加缓存就像将相关注释添加到其方法中一样简单,如下面的示例所示:
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.stereotype.Component;
-
- @Component
- public class MathService {
-
- @Cacheable("piDecimals")
- public int computePiDecimal(int i) {
- // ...
- }
-
- }
此示例演示如何在可能代价高昂的操作上使用缓存。在调用computePiDecimal
,抽象将在piDecimals
匹配i
争论。如果找到一个条目,缓存中的内容将立即返回给调用方,并且不会调用该方法。否则,将调用该方法,并在返回值之前更新缓存。
![]() | 谨慎 |
---|---|
您还可以使用标准的jsr-107(Jcache)注释(如 |
如果没有添加任何特定的缓存库,则SpringBoot自动配置简单提供者它使用内存中的并发映射。当需要缓存时(如piDecimals
),此提供程序将为您创建该提供程序。简单的提供程序并不是真正推荐用于生产使用的,但是它对于开始使用和确保您理解这些特性是很好的。当您决定使用缓存提供程序时,请确保阅读其文档,以了解如何配置应用程序使用的缓存。几乎所有提供程序都要求您显式地配置在应用程序中使用的每个缓存。有些提供了一种自定义由spring.cache.cache-names
财产。
缓存抽象没有提供实际的存储,而是依赖于由org.springframework.cache.Cache
和org.springframework.cache.CacheManager
接口。
如果尚未定义类型的beanCacheManager
或者是CacheResolver
命名cacheResolver
(见CachingConfigurer
),SpringBoot尝试检测以下提供程序(按指定的顺序):
![]() |
也有可能力设置 |
![]() |
使用 |
如果CacheManager
是由SpringBoot自动配置的,您可以在它完全初始化之前进一步调优它的配置,方法是公开一个实现CacheManagerCustomizer
接口。下面的示例设置一个标志,表示应该将空值传递给基础映射:
- @Bean
- public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
- return new CacheManagerCustomizer<ConcurrentMapCacheManager>() {
- @Override
- public void customize(ConcurrentMapCacheManager cacheManager) {
- cacheManager.setAllowNullValues(false);
- }
- };
- }
![]() |
在前面的示例中,自动配置 |
如果上下文定义至少一org.springframework.cache.Cache
豆子一个CacheManager
将创建该类型的所有bean。
JCache通过存在的javax.cache.spi.CachingProvider
在类路径(即,与JSR-107兼容的缓存库存在于类路径上)上,JCacheCacheManager
由spring-boot-starter-cache
“初学者”。有各种兼容的库,SpringBoot为Ehcache 3、Hazelcast和InfinisPAN提供了依赖关系管理。任何其他兼容的库也可以添加。
可能存在多个提供程序,在这种情况下,必须显式指定提供程序。即使JSR-107标准没有强制执行一种标准的方法来定义配置文件的位置,SpringBoot也会尽最大努力适应设置带有实现细节的缓存,如下面的示例所示:
- # Only necessary if more than one provider is present
- spring.cache.jcache.provider=com.acme.MyCachingProvider
- spring.cache.jcache.config=classpath:acme.xml
![]() |
当缓存库同时提供本机实现和JSR-107支持时,SpringBoot更喜欢JSR-107支持,因此如果切换到不同的JSR-107实现,也可以使用相同的特性。 |
![]() |
春靴对Hazelcast的一般支持。如果一个人 |
有两种方法可以自定义基础javax.cache.cacheManager
:
spring.cache.cache-names
财产。如果一个习俗javax.cache.configuration.Configuration
bean是定义的,它用于自定义它们。org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer
类的引用调用bean。CacheManager
完全定制。![]() |
如果一个标准 |
EhCache如果一个名为ehcache.xml
可以在类路径的根部找到。如果找到EhCache 2.x,则EhCacheCacheManager
由spring-boot-starter-cache
“初学者”用于引导缓存管理器。还可以提供另一个配置文件,如以下示例所示:
spring.cache.ehcache.config=classpath:config/another-config.xml
春靴对Hazelcast的一般支持。如果HazelcastInstance
已自动配置,它将自动包装在CacheManager
.
英菲尼斯潘没有默认配置文件位置,因此必须显式指定。否则,将使用默认引导程序。
spring.cache.infinispan.config=infinispan.xml
可以在启动时通过设置spring.cache.cache-names
财产。如果一个习俗ConfigurationBuilder
bean是定义的,它用于自定义缓存。
![]() |
InfinisPAN在SpringBoot中的支持仅限于嵌入式模式,是相当基础的。如果您想要更多的选项,您应该使用正式的InfinispanSpringBootStart。看见英菲尼斯潘文件更多细节。 |
如果CouchbaseJava客户端和couchbase-spring-cache
实现是可用的,Couchbase是配置..CouchbaseCacheManager
是自动配置的。还可以在启动时通过设置spring.cache.cache-names
财产。这些缓存在Bucket
那是自动配置的。你可以的。也在另一个上创建额外的缓存Bucket
通过使用自定义程序。假设您需要两个缓存(cache1
和cache2
)关于“主要”Bucket
还有一个(cache3
)具有自定义时间的缓存,在“另一个”上生存2秒。Bucket
。您可以通过配置创建前两个缓存,如下所示:
spring.cache.cache-names=cache1,cache2
然后,您可以定义@Configuration
类来配置额外的Bucket
而cache3
缓存如下:
- @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("cache3", CacheBuilder.newInstance(anotherBucket())
- .withExpiration(2));
- };
- }
-
- }

此示例配置重用Cluster
这是通过自动配置创建的。
如果雷迪斯是否可用并配置,则RedisCacheManager
是自动配置的。在启动时可以通过设置spring.cache.cache-names
属性和缓存默认值可以通过使用spring.cache.redis.*
财产。例如,下面的配置创建cache1
和cache2
缓存活下去的时间10分钟:
- spring.cache.cache-names=cache1,cache2
- spring.cache.redis.time-to-live=600000
![]() |
默认情况下,会添加一个键前缀,这样,如果两个单独的缓存使用相同的键,Redis就不会有重叠的键,并且不能返回无效的值。如果您创建自己的设置,我们强烈建议将此设置保持为启用状态。 |
![]() |
可以通过添加 |
咖啡因Java 8重写了番石榴的缓存,取代了对番石榴的支持。如果咖啡因存在,CaffeineCacheManager
(由spring-boot-starter-cache
是自动配置的。可以在启动时通过设置spring.cache.cache-names
属性,并且可以通过以下之一进行自定义(按指定的顺序):
spring.cache.caffeine.spec
com.github.benmanes.caffeine.cache.CaffeineSpec
bean被定义为com.github.benmanes.caffeine.cache.Caffeine
bean被定义为例如,下面的配置创建cache1
和cache2
缓存的最大大小为500,并且活下去的时间10分钟
- spring.cache.cache-names=cache1,cache2
- spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
如果com.github.benmanes.caffeine.cache.CacheLoader
bean被定义,它将自动关联到CaffeineCacheManager
。因为CacheLoader
将与全缓存管理器管理的缓存,它必须定义为CacheLoader<Object, Object>
。自动配置忽略任何其他泛型类型.
如果找不到其他提供程序,则使用ConcurrentHashMap
在配置缓存存储时。如果应用程序中没有缓存库,这是默认的。默认情况下,缓存是根据需要创建的,但可以通过设置cache-names
财产。例如,如果你只想cache1
和cache2
缓存,设置cache-names
财产如下:
spring.cache.cache-names=cache1,cache2
如果这样做,并且应用程序使用未列出的缓存,那么当需要缓存时,它会在运行时失败,而不是在启动时失败。如果使用未声明的缓存,这与“真实”缓存提供程序的行为方式类似。
什么时候@EnableCaching
在您的配置中,还需要一个合适的缓存配置。如果需要在某些环境中完全禁用缓存,请强制缓存类型为none
若要使用NO-OP实现,请参见以下示例:
spring.cache.type=none
Spring框架为与消息传递系统集成提供了广泛的支持,简化了JMSAPI的使用JmsTemplate
异步接收消息的完整基础结构。SpringAMQP为高级消息队列协议提供了类似的功能集。Spring Boot还提供了自动配置选项。RabbitTemplate
还有拉比·MQ。SpringWebSocket内置了对STOMP消息传递的支持,SpringBoot通过启动器和少量的自动配置对此提供了支持。SpringBoot还支持ApacheKafka。
这,这个,那,那个javax.jms.ConnectionFactory
接口提供了创建javax.jms.Connection
用于与JMS代理交互。尽管春天需要一个ConnectionFactory
要使用JMS,通常不需要自己直接使用它,而是可以依赖更高级别的消息抽象。(见相关部分)的详细信息。)SpringBoot还自动配置发送和接收消息所需的基础设施。
什么时候ActiveMQ在类路径上可用,SpringBoot也可以配置ConnectionFactory
。如果存在代理,则会自动启动和配置嵌入式代理(前提是没有通过配置指定代理URL)。
![]() |
如果你用 |
中的外部配置属性控制ActiveMQ配置。spring.activemq.*
。例如,您可以在application.properties
:
- spring.activemq.broker-url=tcp://192.168.1.210:9876
- spring.activemq.user=admin
- spring.activemq.password=secret
默认情况下,CachingConnectionFactory
包裹本地人ConnectionFactory
中的可由外部配置属性控制的合理设置。spring.jms.*
:
spring.jms.cache.session-cache-size=5
如果您希望使用本机池,可以通过向org.messaginghub:pooled-jms
和配置JmsPoolConnectionFactory
因此,如以下示例所示:
- spring.activemq.pool.enabled=true
- spring.activemq.pool.max-connections=50
![]() |
看见 |
默认情况下,如果还不存在ActiveMQ,则ActiveMQ将创建一个目的地,以便根据其提供的名称解析目的地。
Spring Boot可以自动配置ConnectionFactory
当它发现阿耳特米斯在类路径上可用。如果存在代理,则会自动启动和配置嵌入式代理(除非模式属性已显式设置)。支持的模式如下embedded
(明确表示需要嵌入代理,如果类路径上无法使用代理,则应发生错误)native
(使用netty
运输协议)。配置后者时,SpringBoot将配置ConnectionFactory
它连接到具有默认设置的本地计算机上运行的代理。
![]() |
如果你用 |
中的外部配置属性控制artemis配置。spring.artemis.*
。例如,您可以在application.properties
:
- spring.artemis.mode=native
- spring.artemis.host=192.168.1.210
- spring.artemis.port=9876
- spring.artemis.user=admin
- spring.artemis.password=secret
嵌入代理时,您可以选择是否要启用持久性,并列出应该可用的目的地。可以将它们指定为逗号分隔的列表,以便使用默认选项创建它们,或者可以定义类型的bean(S)。org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration
或org.apache.activemq.artemis.jms.server.config.TopicConfiguration
,分别用于高级队列和主题配置。
默认情况下,CachingConnectionFactory
包裹本地人ConnectionFactory
中的可由外部配置属性控制的合理设置。spring.jms.*
:
spring.jms.cache.session-cache-size=5
如果您希望使用本机池,可以通过向org.messaginghub:pooled-jms
和配置JmsPoolConnectionFactory
因此,如以下示例所示:
- spring.artemis.pool.enabled=true
- spring.artemis.pool.max-connections=50
看见ArtemisProperties
获得更多支持的选项。
不涉及JNDI查找,目的地将根据其名称进行解析,使用name
属性在Artemis配置中或通过配置提供的名称中。
如果在应用程序服务器中运行应用程序,SpringBoot尝试定位JMSConnectionFactory
通过使用JNDI。默认情况下,java:/JmsXA
和java:/XAConnectionFactory
检查位置。您可以使用spring.jms.jndi-name
如果需要指定替代位置,请创建以下示例:
spring.jms.jndi-name=java:/MyConnectionFactory
春天的JmsTemplate
是自动配置的,您可以直接将它自动放入自己的bean中,如下面的示例所示:
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; } // ... }
![]() |
|
当JMS基础设施存在时,任何bean都可以用@JmsListener
若要创建侦听器端点,请执行以下操作。如果没有JmsListenerContainerFactory
已定义了默认配置,则会自动配置默认配置。如果DestinationResolver
或者是MessageConverter
bean是定义的,它会自动与默认工厂相关联。
默认情况下,默认工厂是事务性的。如果您在一个基础设施中运行,其中JtaTransactionManager
默认情况下,它与侦听器容器相关联。如果没有,则sessionTransacted
已启用标志。在后一种情况下,可以通过添加以下方法将本地数据存储事务与传入消息的处理相关联@Transactional
在侦听器方法(或其委托)上。这确保本地事务完成后确认传入消息。这还包括发送在同一JMS会话上执行的响应消息。
下面的组件在someQueue
目的地:
- @Component
- public class MyBean {
-
- @JmsListener(destination = "someQueue")
- public void processMessage(String content) {
- // ...
- }
-
- }
![]() |
看见.的Javadoc |
如果您需要创建更多JmsListenerContainerFactory
实例,或者如果要覆盖默认值,SpringBoot将提供一个DefaultJmsListenerContainerFactoryConfigurer
可以用来初始化DefaultJmsListenerContainerFactory
具有与自动配置的设置相同的设置。
例如,下面的示例公开另一个使用特定MessageConverter
:
- @Configuration
- static class JmsConfiguration {
-
- @Bean
- public DefaultJmsListenerContainerFactory myFactory(
- DefaultJmsListenerContainerFactoryConfigurer configurer) {
- DefaultJmsListenerContainerFactory factory =
- new DefaultJmsListenerContainerFactory();
- configurer.configure(factory, connectionFactory());
- factory.setMessageConverter(myMessageConverter());
- return factory;
- }
-
- }
那么你可以在任何地方使用这个工厂。@JmsListener
-附加说明的方法如下:
- @Component
- public class MyBean {
-
- @JmsListener(destination = "someQueue", containerFactory="myFactory")
- public void processMessage(String content) {
- // ...
- }
-
- }
高级消息队列协议(AMQP)是一种面向消息中间件的平台中立、线级协议.SpringAMQP项目将核心Spring概念应用于基于AMQP的消息传递解决方案的开发。SpringBoot为通过RabbitMQ使用AMQP提供了一些方便,包括spring-boot-starter-amqp
“初学者”。
兔MQ是基于AMQP协议的轻量级、可靠、可伸缩和可移植的消息代理。弹簧使用RabbitMQ
通过AMQP协议进行通信。
中的外部配置属性控制RabbitMQ配置。spring.rabbitmq.*
。例如,您可以在application.properties
:
- spring.rabbitmq.host=localhost
- spring.rabbitmq.port=5672
- spring.rabbitmq.username=admin
- spring.rabbitmq.password=secret
如果ConnectionNameStrategy
bean存在于上下文中,它将自动用于命名由自动配置的连接。ConnectionFactory
。看见RabbitProperties
有关更多受支持的选项。
![]() |
看见理解AMQP,RabbitMQ使用的协议更多细节。 |
春天的AmqpTemplate
和AmqpAdmin
是自动配置的,您可以直接将它们自动放入自己的bean中,如下面的示例所示:
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; } // ... }
![]() |
|
如有需要,任何org.springframework.amqp.core.Queue
它被定义为bean自动用于在RabbitMQ实例上声明相应的队列。
若要重试操作,可以在AmqpTemplate
(例如,在代理连接丢失时):
- spring.rabbitmq.template.retry.enabled=true
- spring.rabbitmq.template.retry.initial-interval=2s
默认情况下将禁用重试。您还可以自定义RetryTemplate
以编程方式声明RabbitRetryTemplateCustomizer
豆子
当存在兔子基础设施时,任何bean都可以用@RabbitListener
若要创建侦听器端点,请执行以下操作。如果没有RabbitListenerContainerFactory
已定义为默认值。SimpleRabbitListenerContainerFactory
自动配置,您可以使用spring.rabbitmq.listener.type
财产。如果MessageConverter
或者是MessageRecoverer
bean是定义的,它会自动与默认工厂相关联。
下面的示例组件在someQueue
排队:
- @Component
- public class MyBean {
-
- @RabbitListener(queues = "someQueue")
- public void processMessage(String content) {
- // ...
- }
-
- }
![]() |
看见.的Javadoc |
如果您需要创建更多RabbitListenerContainerFactory
实例,或者如果要覆盖默认值,SpringBoot将提供一个SimpleRabbitListenerContainerFactoryConfigurer
和一个DirectRabbitListenerContainerFactoryConfigurer
可以用来初始化SimpleRabbitListenerContainerFactory
和一个DirectRabbitListenerContainerFactory
具有与自动配置使用的工厂相同的设置。
![]() |
您所选择的容器类型并不重要。这两个bean由自动配置公开。 |
例如,下面的配置类公开了另一个使用特定MessageConverter
:
- @Configuration
- static class RabbitConfiguration {
-
- @Bean
- public SimpleRabbitListenerContainerFactory myFactory(
- SimpleRabbitListenerContainerFactoryConfigurer configurer) {
- SimpleRabbitListenerContainerFactory factory =
- new SimpleRabbitListenerContainerFactory();
- configurer.configure(factory, connectionFactory);
- factory.setMessageConverter(myMessageConverter());
- return factory;
- }
-
- }
那么你可以在任何地方使用这个工厂。@RabbitListener
-附加说明的方法如下:
- @Component
- public class MyBean {
-
- @RabbitListener(queues = "someQueue", containerFactory="myFactory")
- public void processMessage(String content) {
- // ...
- }
-
- }
您可以启用重试来处理侦听器抛出异常的情况。默认情况下,RejectAndDontRequeueRecoverer
,但您可以定义MessageRecoverer
你自己的。当重试用尽时,消息将被拒绝,如果代理被配置为删除或路由到死信交换。默认情况下,将禁用重试。您还可以自定义RetryTemplate
以编程方式声明RabbitRetryTemplateCustomizer
豆子
![]() | 重要 |
---|---|
默认情况下,如果禁用重试并引发异常,则将无限期地重新尝试传递。可以通过两种方式修改此行为: |
阿帕奇卡夫卡的自动配置支持spring-kafka
项目。
中的外部配置属性控制Kafka配置。spring.kafka.*
。例如,您可以在application.properties
:
- spring.kafka.bootstrap-servers=localhost:9092
- spring.kafka.consumer.group-id=myGroup
![]() |
若要在启动时创建主题,请添加类型为 |
看见KafkaProperties
获得更多支持的选项。
春天的KafkaTemplate
是自动配置的,您可以直接在自己的bean中自动配置它,如下面的示例所示:
- @Component
- public class MyBean {
-
- private final KafkaTemplate kafkaTemplate;
-
- @Autowired
- public MyBean(KafkaTemplate kafkaTemplate) {
- this.kafkaTemplate = kafkaTemplate;
- }
-
- // ...
-
- }
![]() |
如果财产 |
当apache Kafka基础设施存在时,任何bean都可以用@KafkaListener
若要创建侦听器端点,请执行以下操作。如果没有KafkaListenerContainerFactory
已经定义好了,默认的键将自动配置为spring.kafka.listener.*
.
下面的组件在someTopic
题目:
- @Component
- public class MyBean {
-
- @KafkaListener(topics = "someTopic")
- public void processMessage(String content) {
- // ...
- }
-
- }
如果KafkaTransactionManager
bean是定义的,它自动与容器工厂相关联。类似地,如果RecordMessageConverter
, ErrorHandler
或AfterRollbackProcessor
bean是定义的,它会自动与默认工厂相关联。
![]() |
风俗 |
SpringforApacheKafka提供了一个工厂bean来创建一个StreamsBuilder
对象并管理其流的生命周期。Spring Boot自动配置所需的KafkaStreamsConfiguration
豆子kafka-streams
在类路径上,Kafka流通过@EnableKafkaStreams
注释
启用Kafka流意味着必须设置应用程序id和引导服务器。前者可以使用spring.kafka.streams.application-id
,拖欠spring.application.name
如果没有设定。后者可以全局设置,也可以仅针对流进行特殊重写。
使用专用属性可以获得其他几个属性;其他任意的Kafka属性可以使用spring.kafka.streams.properties
命名空间。另见第32.3.4节,“额外的Kafka属性”想了解更多信息。
要使用工厂bean,只需连接StreamsBuilder
进入你的@Bean
如以下示例所示:
- @Configuration
- @EnableKafkaStreams
- static class KafkaStreamsExampleConfiguration {
-
- @Bean
- public KStream<Integer, String> kStream(StreamsBuilder streamsBuilder) {
- KStream<Integer, String> stream = streamsBuilder.stream("ks1In");
- stream.map((k, v) -> new KeyValue<>(k, v.toUpperCase())).to("ks1Out",
- Produced.with(Serdes.Integer(), new JsonSerde<>()));
- return stream;
- }
-
- }
默认情况下,由StreamBuilder
对象自动启动。您可以使用spring.kafka.streams.auto-startup
财产。
自动配置支持的属性显示在附录A,通用应用特性。注意,在大多数情况下,这些属性(连字符或CamelCase)直接映射到ApacheKafka虚线属性。有关详细信息,请参阅ApacheKafka文档。
前几个属性适用于所有组件(生产者、消费者、管理员和流),但如果您希望使用不同的值,则可以在组件级别指定。ApacheKafka指定的属性具有高、中或低的重要性。SpringBoot自动配置支持所有高重要性属性、一些选定的中、低属性以及没有默认值的任何属性。
只有一部分由Kafka支持的属性可以通过KafkaProperties
班级,等级如果希望使用不直接支持的其他属性配置生产者或使用者,请使用以下属性:
- spring.kafka.properties.prop.one=first
- spring.kafka.admin.properties.prop.two=second
- spring.kafka.consumer.properties.prop.three=third
- spring.kafka.producer.properties.prop.four=fourth
- spring.kafka.streams.properties.prop.five=fifth
这设置了公共prop.one
卡夫卡first
(适用于生产者、消费者和管理员)prop.two
管理属性second
,prop.three
消费者财产third
,prop.four
生产者财产fourth
而prop.five
流属性fifth
.
您还可以配置SpringKafkaJsonDeserializer
详情如下:
- spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer
- spring.kafka.consumer.properties.spring.json.value.default.type=com.example.Invoice
- spring.kafka.consumer.properties.spring.json.trusted.packages=com.example,org.acme
类似地,您可以禁用JsonSerializer
在标头中发送类型信息的默认行为:
- spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer
- spring.kafka.producer.properties.spring.json.add.type.headers=false
![]() | 重要 |
---|---|
以这种方式设置的属性覆盖SpringBoot显式支持的任何配置项。 |
RestTemplate
如果需要从应用程序调用远程REST服务,可以使用Spring框架的RestTemplate
班级,等级自RestTemplate
实例在使用之前通常需要进行自定义,SpringBoot不提供任何单独的自动配置。RestTemplate
豆子但是,它会自动配置一个RestTemplateBuilder
,可以用来创建RestTemplate
需要时执行实例。自动配置RestTemplateBuilder
确保明智HttpMessageConverters
适用于RestTemplate
实例。
下面的代码显示了一个典型的示例:
- @Service
- public class MyService {
-
- private final RestTemplate restTemplate;
-
- public MyService(RestTemplateBuilder restTemplateBuilder) {
- this.restTemplate = restTemplateBuilder.build();
- }
-
- public Details someRestCall(String name) {
- return this.restTemplate.getForObject("/{name}/details", Details.class, name);
- }
-
- }
![]() |
|
有三种主要的方法RestTemplate
自定义,取决于您希望自定义应用的范围。
若要使任何自定义的范围尽可能窄,请插入自动配置的RestTemplateBuilder
然后根据需要调用它的方法。每个方法调用返回一个新的RestTemplateBuilder
实例,因此自定义只影响构建器的这种使用。
若要进行应用程序范围内的附加定制,请使用RestTemplateCustomizer
豆子所有这些bean都会自动注册到自动配置的RestTemplateBuilder
并应用于任何用它构建的模板。
下面的示例显示了一个自定义程序,该自定义程序配置除以下之外的所有主机的代理使用。192.168.0.5
:
static class ProxyCustomizer implements RestTemplateCustomizer { @Override public void customize(RestTemplate restTemplate) { HttpHost proxy = new HttpHost("proxy.example.com"); HttpClient httpClient = HttpClientBuilder.create() .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { @Override public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (target.getHostName().equals("192.168.0.5")) { return null; } return super.determineProxy(target, request, context); } }).build(); restTemplate.setRequestFactory( new HttpComponentsClientHttpRequestFactory(httpClient)); } }
最后,最极端的(而且很少使用)选项是创建自己的RestTemplateBuilder
豆子这样做可以关闭RestTemplateBuilder
并阻止任何RestTemplateCustomizer
被使用的豆子。
WebClient
如果类路径上有SpringWebFlux,也可以选择使用WebClient
呼叫远程休息服务。相比较RestTemplate
,这个客户有一种功能更强的感觉和完全的反应。您可以了解更多关于WebClient
在奉献中Spring框架文档中的.
Spring Boot创建并预先配置WebClient.Builder
对于您;强烈建议将其注入组件并使用它创建WebClient
实例。SpringBoot将构建器配置为共享HTTP资源,以与服务器相同的方式反映编解码器的设置(请参见WebFlux HTTP编解码器自动配置),还有更多。
下面的代码显示了一个典型的示例:
- @Service
- public class MyService {
-
- private final WebClient webClient;
-
- public MyService(WebClient.Builder webClientBuilder) {
- this.webClient = webClientBuilder.baseUrl("http://example.org").build();
- }
-
- public Mono<Details> someRestCall(String name) {
- return this.webClient.get().uri("/{name}/details", name)
- .retrieve().bodyToMono(Details.class);
- }
-
- }
Spring Boot将自动检测哪个ClientHttpConnector
开车WebClient
,取决于应用程序类路径上可用的库。
这,这个,那,那个spring-boot-starter-webflux
取决于io.projectreactor.netty:reactor-netty
默认情况下,这会同时带来服务器和客户端实现。如果选择使用Jetty作为反应性服务器,则应添加对JettyReactiveHTTP客户端库的依赖关系,org.eclipse.jetty:jetty-reactive-httpclient
,因为它将自动与服务器共享HTTP资源。
开发人员可以通过定义自己的ClientHttpConnector
在这种情况下,并且取决于您选择的HTTP客户机库,您还应该定义一个资源工厂bean来管理该客户端的HTTP资源。例如,ReactorResourceFactory
用于反应堆Netty客户端。
您可以了解更多关于WebClient
Spring框架参考文档中的配置选项.
有三种主要的方法WebClient
自定义,取决于您希望自定义应用的范围。
若要使任何自定义的范围尽可能窄,请插入自动配置的WebClient.Builder
然后根据需要调用它的方法。WebClient.Builder
实例是有状态的:构建器上的任何更改都反映在随后使用它创建的所有客户端中。如果希望使用相同的构建器创建多个客户端,还可以考虑使用WebClient.Builder other = builder.clone();
.
对所有用户进行应用程序范围的、附加的自定义。WebClient.Builder
实例,您可以声明WebClientCustomizer
和更改WebClient.Builder
局部注射点。
最后,您可以回到原来的api并使用WebClient.create()
。在这种情况下,没有自动配置或WebClientCustomizer
被应用。
只要JSR-303实现(例如Hibernate验证器)在类路径上,Bean Validation1.1支持的方法验证功能就会自动启用。这允许使用bean方法进行注释。javax.validation
对其参数和/或其返回值的约束。具有此类注释方法的目标类需要用@Validated
类型级别的注释,以便搜索它们的方法以查找内联约束注释。
例如,以下服务触发第一个参数的验证,确保其大小介于8到10之间:
- @Service
- @Validated
- public class MyBean {
-
- public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code,
- Author author) {
- ...
- }
-
- }
Spring框架为发送电子邮件提供了一个简单的抽象,使用JavaMailSender
接口,SpringBoot提供了它的自动配置以及一个启动模块.
![]() |
见参考文献有关如何使用 |
如果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
还可以配置JavaMailSender
现有的Session
来自JNDI:
spring.mail.jndi-name=mail/Session
当jndi-name
设置后,它将优先于所有其他与会话相关的设置。
Spring Boot支持跨多个XA资源的分布式JTA事务,方法是使用Atomikos或比特罗尼嵌入式事务管理器当部署到适当的JavaEE应用服务器时,也支持JTA事务。
当检测到JTA环境时,Spring的JtaTransactionManager
用于管理事务。自动配置的JMS、DataSource和JPAbean被升级,以支持XA事务。您可以使用标准的Spring成语,例如@Transactional
,以参与分布式事务。如果您位于JTA环境中,并且仍然希望使用本地事务,则可以将spring.jta.enabled
财产false
若要禁用JTA自动配置,请执行以下操作。
Atomikos是一个流行的开源事务管理器,可以嵌入到SpringBoot应用程序中。您可以使用spring-boot-starter-jta-atomikos
启动引入适当的Atomikos库。SpringBoot自动配置Atomikos并确保depends-on
将设置应用于Springbean以进行正确的启动和关闭排序。
默认情况下,Atomikos事务日志被写入transaction-logs
应用程序主目录中的目录(应用程序JAR文件所在的目录)。您可以通过设置spring.jta.log-dir
你的财产application.properties
档案。属性以spring.jta.atomikos.properties
也可用于自定义AtomikosUserTransactionServiceImp
。见AtomikosProperties
Javadoc获得完整的细节。
![]() |
为了确保多个事务管理器能够安全地协调相同的资源管理器,每个Atomikos实例必须配置一个唯一的ID。默认情况下,此ID是运行Atomikos的机器的IP地址。若要确保生产中的唯一性,应配置 |
比特罗尼是一个流行的开源JTA事务管理器实现。您可以使用spring-boot-starter-jta-bitronix
启动将适当的Bitronix依赖项添加到项目中。与Atomikos一样,SpringBoot会自动配置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地址。若要确保生产中的唯一性,应配置 |
如果将SpringBoot应用程序打包为war
或ear
文件并将其部署到JavaEE应用服务器上,您可以使用应用程序服务器的内置事务管理器。SpringBoot试图通过查看常见的JNDI位置来自动配置事务管理器(java:comp/UserTransaction
, java:comp/TransactionManager
等等)。如果使用应用服务器提供的事务服务,通常还希望确保所有资源都由服务器管理,并通过JNDI公开。Spring Boot试图通过查找ConnectionFactory
在JNDI路径上(java:/JmsXA
或java:/XAConnectionFactory
),您可以使用spring.datasource.jndi-name
财产若要配置您的DataSource
.
当使用JTA时,主JMSConnectionFactory
bean是XA感知的,并参与分布式事务。在某些情况下,您可能希望使用非XA处理某些JMS消息。ConnectionFactory
。例如,JMS处理逻辑可能比XA超时时间更长。
如果您想使用非XAConnectionFactory
,您可以将nonXaJmsConnectionFactory
而不是@Primary
jmsConnectionFactory
豆子为了保持一致性,jmsConnectionFactory
bean还通过使用bean别名提供。xaJmsConnectionFactory
.
下面的示例演示如何注入ConnectionFactory
实例:
- // Inject the primary (XA aware) ConnectionFactory
- @Autowired
- private ConnectionFactory defaultConnectionFactory;
-
- // Inject the XA aware ConnectionFactory (uses the alias and injects the same as above)
- @Autowired
- @Qualifier("xaJmsConnectionFactory")
- private ConnectionFactory xaConnectionFactory;
-
- // Inject the non-XA aware ConnectionFactory
- @Autowired
- @Qualifier("nonXaJmsConnectionFactory")
- private ConnectionFactory nonXaConnectionFactory;
这,这个,那,那个XAConnectionFactoryWrapper
和XADataSourceWrapper
接口可用于支持其他嵌入式事务管理器。接口负责包装。XAConnectionFactory
和XADataSource
豆类,并将它们作为常规公开。ConnectionFactory
和DataSource
bean,它透明地注册在分布式事务中。DataSource和JMS自动配置使用JTA变体,只要您有JtaTransactionManager
中注册的bean和适当的XA包装bean。ApplicationContext
.
这,这个,那,那个BitronixXAConnectionFactoryWrapper和BitronixXADataSourceWrapper提供关于如何编写XA包装器的良好示例。
如果哈泽尔卡斯特在类路径上,并找到合适的配置,SpringBoot自动配置HazelcastInstance
你可以在你的应用程序中注入。
如果定义com.hazelcast.config.Config
BeanSpring Boot使用这个。如果您的配置定义了实例名,SpringBoot将尝试定位一个现有实例,而不是创建一个新实例。
您还可以指定hazelcast.xml
要通过配置使用的配置文件,如以下示例所示:
spring.hazelcast.config=classpath:config/my-hazelcast.xml
否则,SpringBoot尝试从默认位置查找Hazelcast配置:hazelcast.xml
在工作目录或类路径的根目录中。我们还检查hazelcast.config
设置系统属性。见Hazelcast文件更多细节。
如果hazelcast-client
在类路径中,SpringBoot第一次尝试通过检查以下配置选项来创建客户端:
com.hazelcast.client.config.ClientConfig
豆子spring.hazelcast.config
财产。hazelcast.client.config
系统属性hazelcast-client.xml
在工作目录或类路径的根目录中。![]() |
春靴也有对Hazelcast的显式缓存支持。如果启用了缓存,则 |
Spring Boot为使用石英调度器,包括spring-boot-starter-quartz
“初学者”。如果石英可用,Scheduler
是自动配置的(通过SchedulerFactoryBean
抽象)
将自动获取下列类型的bean并将其与Scheduler
:
JobDetail
*定义特定职务。JobDetail
实例可以使用JobBuilder
APICalendar
.Trigger
*定义何时触发特定作业。默认情况下,内存中的JobStore
被利用了。但是,如果DataSource
bean在您的应用程序中可用,如果spring.quartz.job-store-type
属性进行相应配置,如以下示例所示:
spring.quartz.job-store-type=jdbc
当使用JDBC存储时,模式可以在启动时初始化,如下面的示例所示:
spring.quartz.jdbc.initialize-schema=always
![]() |
默认情况下,使用Quartz库提供的标准脚本检测和初始化数据库。还可以通过设置 |
默认情况下,配置创建的作业不会覆盖已从持久性作业存储区读取的已注册作业。若要启用覆盖现有作业定义,请将spring.quartz.overwrite-existing-jobs
财产。
石英调度器配置可以使用spring.quartz
属性和SchedulerFactoryBeanCustomizer
bean,它允许编程。SchedulerFactoryBean
定制。高级Quartz配置属性可以使用spring.quartz.properties.*
.
![]() |
特别是, |
作业可以定义设置器来注入数据映射属性。也可以类似的方式注入常规bean,如下例所示:
public class SampleJob extends QuartzJobBean { private MyService myService; private String name; // Inject "MyService" bean public void setMyService(MyService myService) { ... } // Inject the "name" job data property public void setName(String name) { ... } @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { ... } }
在没有TaskExecutor
bean在上下文中,SpringBoot自动配置ThreadPoolTaskExecutor
具有可自动关联到异步任务执行的合理默认值(@EnableAsync
)和SpringMVC异步请求处理。
线程池使用8个核心线程,它们可以根据负载增长和收缩。这些默认设置可以使用spring.task.execution
命名空间,如以下示例所示:
- spring.task.execution.pool.max-threads=16
- spring.task.execution.pool.queue-capacity=100
- spring.task.execution.pool.keep-alive=10s
这将线程池更改为使用有界队列,以便当队列满(100个任务)时,线程池将增加到最多16个线程。当线程空闲10秒时(而不是默认的60秒),线程的收缩更具有侵略性。
A ThreadPoolTaskScheduler
如果需要与计划的任务执行相关联,也可以自动配置(@EnableScheduling
)线程池默认使用一个线程,这些设置可以使用spring.task.scheduling
命名空间。
双双TaskExecutorBuilder
豆和aTaskSchedulerBuilder
如果需要创建自定义执行器或调度程序,则可以在上下文中使用bean。
SpringBoot为使用弹簧集成,包括spring-boot-starter-integration
“初学者”。SpringIntegration通过消息传递和其他传输(如HTTP、TCP和其他传输)提供抽象。如果SpringIntegration在类路径上可用,则通过@EnableIntegration
注释
SpringBoot还配置了一些特性,这些特性是由其他SpringIntegration模块的存在触发的。如果spring-integration-jmx
也在类路径上,消息处理统计信息是通过JMX发布的。如果spring-integration-jdbc
可用时,可以在启动时创建默认数据库架构,如下所示:
spring.integration.jdbc.initialize-schema=always
见IntegrationAutoConfiguration
和IntegrationProperties
有关更多细节的类。
默认情况下,如果千分尺meterRegistry
bean是存在的,Spring集成度量将通过千分尺进行管理。如果希望使用遗留的SpringIntegration度量,请添加DefaultMetricsFactory
bean到应用程序上下文。
弹簧启动春季会议用于多种数据存储的自动配置。在构建Servlet Web应用程序时,可以自动配置以下存储:
在构建反应性Web应用程序时,可以自动配置以下存储:
如果类路径上存在单个Spring会话模块,SpringBoot将自动使用该存储实现。如果有多个实现,则必须选择StoreType
来存储会话。例如,要使用JDBC作为后端存储,可以按照以下方式配置应用程序:
spring.session.store-type=jdbc
![]() |
可以通过设置 |
每个商店都有特定的附加设置。例如,可以自定义JDBC存储的表名,如下面的示例所示:
spring.session.jdbc.table-name=SESSIONS
若要设置会话的超时,可以使用spring.session.timeout
财产。如果未设置该属性,则自动配置将返回到server.servlet.session.timeout
.
Java管理扩展(JMX)提供了监视和管理应用程序的标准机制。默认情况下,SpringBoot创建一个MBeanServer
ID为mbeanServer
并公开任何用SpringJMX注释的bean(@ManagedResource
, @ManagedAttribute
,或@ManagedOperation
).
见JmxAutoConfiguration
获取更多详细信息。
SpringBoot在测试应用程序时提供了许多实用程序和注释来帮助您。测试支持由两个模块提供:spring-boot-test
包含核心项,以及spring-boot-test-autoconfigure
支持测试的自动配置。
大多数开发人员使用spring-boot-starter-test
“初学者”,它导入SpringBoot测试模块以及JUnit、AssertJ、Hamcrest和许多其他有用的库。
这,这个,那,那个spring-boot-starter-test
“初学者”(在test
scope
)包含下列提供的库:
我们通常认为这些公共库在编写测试时很有用。如果这些库不适合您的需要,则可以添加您自己的其他测试依赖项。
依赖注入的主要优点之一是它应该使您的代码更容易进行单元测试。属性实例化对象。new
操作员甚至不涉及Spring。您也可以使用模拟对象而不是真正的依赖关系。
通常,您需要超越单元测试,开始集成测试(使用Spring)ApplicationContext
)能够在不需要部署应用程序或连接到其他基础结构的情况下执行集成测试是非常有用的。
Spring框架包括一个专门用于这种集成测试的测试模块。可以将依赖项直接声明为org.springframework:spring-test
或使用spring-boot-starter-test
“起动机”把它临时拉进来。
如果您没有使用spring-test
模块之前,您应该从读取相关部分Spring框架参考文档。
Spring引导应用程序是SpringApplicationContext
因此,除了通常使用普通Spring上下文所做的工作之外,没有什么特别的事情要做来测试它。
![]() |
外部属性、日志记录和SpringBoot的其他特性在默认情况下仅在以下情况下才会安装在上下文中 |
Spring Boot提供了一个@SpringBootTest
注释,可以作为标准的替代。spring-test
@ContextConfiguration
当您需要SpringBoot特性时进行注释。注释的作用是创建ApplicationContext
在您的测试中使用SpringApplication
。除了……之外@SpringBootTest
还提供了一些其他注释。测试更具体的切片一份申请书。
![]() |
如果您使用的是JUnit 4,请不要忘记添加 |
默认情况下,@SpringBootTest
不会启动服务器。您可以使用webEnvironment
属性@SpringBootTest
为了进一步完善测试的运行方式:
MOCK
(默认):加载WebApplicationContext
并提供一个模拟Web环境。使用此注释时不会启动嵌入式服务器。如果您的类路径上没有web环境,则此模式将透明地退回到创建常规的非web环境。ApplicationContext
。它可以与@AutoConfigureMockMvc
或@AutoConfigureWebTestClient
用于基于模拟的web应用程序测试。RANDOM_PORT
*装载WebServerApplicationContext
并提供了一个真实的网络环境。嵌入式服务器将启动并在随机端口上侦听。DEFINED_PORT
*装载WebServerApplicationContext
并提供了一个真实的网络环境。嵌入式服务器将在定义的端口上启动并侦听(从application.properties
)或在默认端口8080
.NONE
*加载ApplicationContext
用SpringApplication
但没有提供任何Web环境(模拟或其他)。![]() |
如果你的测试是 |
![]() |
|
如果SpringMVC可用,则配置一个基于MVC的常规应用程序上下文。如果您只有SpringWebFlux,我们将检测它并配置一个基于WebFlux的应用程序上下文。
如果两者都存在,则优先考虑SpringMVC。如果要在此方案中测试反应性web应用程序,则必须将spring.main.web-application-type
财产:
- @RunWith(SpringRunner.class)
- @SpringBootTest(properties = "spring.main.web-application-type=reactive")
- public class MyWebFluxTests { ... }
如果您熟悉Spring测试框架,您可能已经习惯于使用@ContextConfiguration(classes=…)
为了指定哪个Spring@Configuration
装货。或者,您可能经常使用嵌套。@Configuration
测试中的类。
在测试SpringBoot应用程序时,这通常不是必需的。弹簧靴@*Test
当您没有显式定义主配置时,注释会自动搜索您的主配置。
搜索算法从包含测试的包开始工作,直到找到带注释的类。@SpringBootApplication
或@SpringBootConfiguration
。只要你结构化代码以一种明智的方式,通常可以找到您的主要配置。
![]() |
如果您使用测试注释以测试应用程序中更特定的部分,则应避免添加特定于主要方法的应用类. 的基础组件扫描配置 |
如果要自定义主配置,可以使用嵌套的@TestConfiguration
班级,等级不像嵌套的@Configuration
类,它将用于替代应用程序的主要配置,即嵌套的@TestConfiguration
类除了应用程序的主要配置外,还使用。
![]() |
Spring的测试框架在测试之间缓存应用程序上下文。因此,只要您的测试共享相同的配置(无论如何发现),加载上下文的潜在耗时过程只会发生一次。 |
如果应用程序使用组件扫描(例如,如果您使用@SpringBootApplication
或@ComponentScan
),您可能会发现只为特定测试创建的顶级配置类在任何地方都会意外地被选中。
因为我们之前见过, @TestConfiguration
可以在测试的内部类上使用,以自定义主配置。当被安排到顶级班级时,@TestConfiguration
表示src/test/java
不应通过扫描来拾取。然后,可以在需要的地方显式导入该类,如以下示例所示:
- @RunWith(SpringRunner.class)
- @SpringBootTest
- @Import(MyTestsConfiguration.class)
- public class MyTests {
-
- @Test
- public void exampleTest() {
- ...
- }
-
- }
![]() |
如果你直接用 |
默认情况下,@SpringBootTest
没有启动服务器。如果您有要在此模拟环境中测试的web端点,则可以另外配置MockMvc
如以下示例所示:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class MockMvcExampleTests { @Autowired private MockMvc mvc; @Test public void exampleTest() throws Exception { this.mvc.perform(get("/")).andExpect(status().isOk()) .andExpect(content().string("Hello World")); } }
![]() |
如果希望只关注web层而不启动完整的 |
或者,您可以配置WebTestClient
如以下示例所示:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureWebTestClient public class MockWebTestClientExampleTests { @Autowired private WebTestClient webClient; @Test public void exampleTest() { this.webClient.get().uri("/").exchange().expectStatus().isOk() .expectBody(String.class).isEqualTo("Hello World"); } }
如果您需要启动一个完整运行的服务器,我们建议您使用随机端口。如果你用@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
,每次测试运行时都会随机选择可用端口。
这,这个,那,那个@LocalServerPort
注释可用于注入实际使用的端口进入你的测试。为了方便起见,需要对已启动的服务器进行REST调用的测试可以另外使用。@Autowire
a WebTestClient
,它解析与正在运行的服务器的相对链接,并附带一个用于验证响应的专用API,如以下示例所示:
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.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class RandomPortWebTestClientExampleTests { @Autowired private WebTestClient webClient; @Test public void exampleTest() { this.webClient.get().uri("/").exchange().expectStatus().isOk() .expectBody(String.class).isEqualTo("Hello World"); } }
此设置要求spring-webflux
在类路径上。如果您不能或不愿添加网络流量,SpringBoot还提供了一个TestRestTemplate
设施:
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 RandomPortTestRestTemplateExampleTests { @Autowired private TestRestTemplate restTemplate; @Test public void exampleTest() { String body = this.restTemplate.getForObject("/", String.class); assertThat(body).isEqualTo("Hello World"); } }
由于测试上下文框架缓存上下文,因此默认情况下禁用JMX以防止相同组件在同一域中注册。如果这种测试需要访问MBeanServer
,也考虑将其标记为脏的:
- @RunWith(SpringRunner.class)
- @SpringBootTest(properties = "spring.jmx.enabled=true")
- @DirtiesContext
- public class SampleJmxTests {
-
- @Autowired
- private MBeanServer mBeanServer;
-
- @Test
- public void exampleTest() {
- // ...
- }
-
- }
在运行测试时,有时需要在应用程序上下文中模拟某些组件。例如,在开发期间不可用的远程服务上可能有一个外观。当您想要模拟在实际环境中可能很难触发的失败时,模拟也是非常有用的。
弹簧启动包括一个@MockBean
注释,可用于为您内部的bean定义一个Mockito模拟。ApplicationContext
。您可以使用注释添加新bean或替换单个现有bean定义。该注释可直接用于测试类、测试中的字段或@Configuration
类别和字段。在字段上使用时,也会注入创建的模拟实例。模拟bean在每个测试方法之后都会自动重置。
![]() |
如果您的测试使用SpringBoot的测试注释之一(如 |
下面的示例替换现有的RemoteService
带有模拟实现的bean:
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"); } }
此外,您还可以使用@SpyBean
若要用Mockito包装现有的bean,请执行以下操作spy
。见Javadoc详细情况。
![]() |
Spring的测试框架在测试之间缓存应用程序上下文,并重用用于共享相同配置的测试的上下文,而使用 |
SpringBoot的自动配置系统在应用程序中运行良好,但有时对测试来说可能有点过了。它通常帮助只加载测试应用程序的“片段”所需的配置部分。例如,您可能希望测试SpringMVC控制器是否正确地映射URL,并且不希望在这些测试中涉及数据库调用,或者您可能希望测试JPA实体,并且在这些测试运行时对Web层不感兴趣。
这,这个,那,那个spring-boot-test-autoconfigure
模块包含许多注释,这些注释可用于自动配置此类“片”。它们中的每一个都以类似的方式工作,提供了一个@…Test
加载ApplicationContext
和一个或多个@AutoConfigure…
可用于自定义自动配置设置的注释。
![]() |
每个切片限制组件扫描到适当的组件,并加载一组非常受限的自动配置类。如果你需要排除其中一个 |
![]() |
也可以使用 |
若要测试对象JSON序列化和反序列化是否正常工作,可以使用@JsonTest
注释@JsonTest
自动配置可用的受支持的JSON映射程序,它可以是以下库之一:
ObjectMapper
,任何@JsonComponent
豆子和杰克逊Module
sGson
Jsonb
![]() |
启用的自动配置的列表。 |
如果需要配置自动配置的元素,可以使用@AutoConfigureJsonTesters
注释
SpringBoot包括基于AssertJ的帮助程序,它们使用JSONAssert和JsonPath库来检查JSON是否如预期的那样出现。这,这个,那,那个JacksonTester
, GsonTester
,JsonbTester
,和BasicJsonTester
类可以分别用于Jackson、GSON、Jsonb和String。测试类上的任何辅助字段都可以是@Autowired
使用时@JsonTest
。下面的示例显示了Jackson的测试类:
- 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助手类也可以直接用于标准单元测试。为此,请调用 |
若要测试SpringMVC控制器是否按预期工作,请使用@WebMvcTest
注释@WebMvcTest
自动配置SpringMVC基础结构,并将扫描bean限制为@Controller
, @ControllerAdvice
, @JsonComponent
, Converter
, GenericConverter
, Filter
, WebMvcConfigurer
,和HandlerMethodArgumentResolver
。正规化@Component
使用此注释时不会扫描bean。
![]() |
启用的自动配置设置的列表。 |
![]() |
如果您需要注册额外的组件,比如Jackson |
通常,@WebMvcTest
仅限于单个控制器,并与@MockBean
为所需的协作者提供模拟实现。
@WebMvcTest
也自动配置MockMvc
。模拟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 private MockMvc mvc; @MockBean private UserVehicleService userVehicleService; @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); } }
![]() |
如果需要配置自动配置的元素(例如,何时应用servlet筛选器),则可以在 |
如果使用htmlUnit或Selenium,则自动配置还提供了HTMLUnit。WebClient
豆和/或aWebDriver
豆子以下示例使用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 private WebClient webClient; @MockBean private UserVehicleService userVehicleService; @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); } }
![]() |
默认情况下,SpringBoot |
如果你在类路径上有Spring保安,@WebMvcTest
也会扫描WebSecurityConfigurer
豆子您可以使用SpringSecurity的测试支持,而不是完全禁用此类测试的安全性。关于如何使用Spring安全的更多详细信息MockMvc
支持可在以下内容中找到:第79章,用Spring安全性进行测试如何-到部分。
![]() |
有时候编写SpringMVC测试是不够的;SpringBoot可以帮助您运行使用实际服务器进行完整的端到端测试。. |
来测试一下春季WebFlux控制器按预期工作,可以使用@WebFluxTest
注释@WebFluxTest
自动配置SpringWebFlux基础结构,并将扫描bean限制为@Controller
, @ControllerAdvice
, @JsonComponent
, Converter
, GenericConverter
,和WebFluxConfigurer
。正规化@Component
对象时不扫描bean。@WebFluxTest
使用注释。
![]() |
启用的自动配置的列表。 |
![]() |
如果您需要注册额外的组件,比如Jackson |
通常,@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 private WebTestClient webClient; @MockBean private UserVehicleService userVehicleService; @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); this.webClient.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo("Honda Civic"); } }
![]() |
此设置仅受WebFlux应用程序支持,因为 |
![]() |
|
![]() |
有时编写SpringWebFlux测试是不够的;SpringBoot可以帮助您运行使用实际服务器进行完整的端到端测试。. |
您可以使用@DataJpaTest
用于测试JPA应用程序的注释。默认情况下,它配置内存内嵌入式数据库,扫描@Entity
类,并配置Spring数据JPA存储库。正规化@Component
bean未加载到ApplicationContext
.
![]() |
启用的自动配置设置的列表。 |
默认情况下,数据JPA测试是事务性的,并且在每个测试结束时回滚。见相关部分在SpringFramework参考文档中获得更多细节。如果这不是您想要的,您可以禁用测试或整个类的事务管理,如下所示:
- 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 {
-
- }
DataJPA测试也可能会注入一个TestEntityManager
,它提供了标准JPA的替代方案。EntityManager
这是专门为测试设计的。如果你想用TestEntityManager
外@DataJpaTest
实例,也可以使用@AutoConfigureTestEntityManager
注释一个JdbcTemplate
如果你需要的话也可以。下面的示例显示@DataJpaTest
正在使用的注释:
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 private TestEntityManager entityManager; @Autowired private UserRepository repository; @Test public void testExample() throws 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 {
-
- // ...
-
- }
@JdbcTest
类似于@DataJpaTest
而是用于只需要DataSource
也不要使用SpringDataJDBC。默认情况下,它配置内存内嵌入数据库和JdbcTemplate
。正规化@Component
bean未加载到ApplicationContext
.
![]() |
启用的自动配置的列表。 |
默认情况下,JDBC测试是事务性的,并且在每个测试结束时回滚。见相关部分在SpringFramework参考文档中获得更多细节。如果这不是您想要的,您可以禁用测试或整个类的事务管理,如下所示:
- 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
。(见“第44.3.12节,“自动配置数据JPA测试”".)
@DataJdbcTest
类似于@JdbcTest
而是用于使用Spring数据JDBC存储库的测试。默认情况下,它配置内存内嵌入数据库,JdbcTemplate
,以及Spring数据JDBC存储库。正规化@Component
bean未加载到ApplicationContext
.
![]() |
启用的自动配置的列表。 |
默认情况下,数据JDBC测试是事务性的,并且在每个测试结束时回滚。见相关部分在SpringFramework参考文档中获得更多细节。如果这不是您想要的,您可以将测试或整个测试类的事务管理禁用为如jdbc示例所示.
如果您希望在实际数据库上运行测试,则可以使用@AutoConfigureTestDatabase
注释的方式与DataJpaTest
。(见“第44.3.12节,“自动配置数据JPA测试”".)
你可以用@JooqTest
以类似的方式@JdbcTest
但对于与jOOQ相关的测试。由于jOOQ严重依赖与数据库模式相对应的基于Java的模式,DataSource
被利用了。如果要用内存中的数据库替换它,可以使用@AutoConfigureTestDatabase
覆盖这些设置。(有关在SpringBoot中使用jOOQ的更多信息,请参见“第29.6节,“使用jOOQ”“,在本章前面。@Component
bean未加载到ApplicationContext
.
![]() |
启用的自动配置的列表。 |
@JooqTest
配置DSLContext
。正规化@Component
bean未加载到ApplicationContext
。下面的示例显示@JooqTest
正在使用的注释:
- 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测试是事务性的,默认情况下在每个测试结束时回滚。如果这不是您想要的,您可以将测试或整个测试类的事务管理禁用为如jdbc示例所示.
你可以用@DataMongoTest
测试MongoDB应用程序。默认情况下,它配置内存中嵌入的MongoDB(如果可用),配置MongoTemplate
,扫描@Document
类,并配置Spring数据MongoDB存储库。正规化@Component
bean未加载到ApplicationContext
。(有关在SpringBoot中使用MongoDB的更多信息,请参见“第30.2节,“MongoDB”“,在本章前面。
![]() |
启用的自动配置设置的列表。 |
下面的类显示@DataMongoTest
正在使用的注释:
- 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;
-
- //
- }
内存中嵌入的MongoDB通常适用于测试,因为它速度快,不需要任何开发人员安装。但是,如果您更愿意对真实的MongoDB服务器运行测试,则应该排除嵌入的MongoDB自动配置,如下面的示例所示:
- 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 {
-
- }
你可以用@DataNeo4jTest
测试Neo4j应用程序。默认情况下,它使用内存内嵌入的neo4j(如果嵌入式驱动程序可用),扫描@NodeEntity
类,并配置Spring数据Neo4j存储库。正规化@Component
bean未加载到ApplicationContext
。(有关在SpringBoot中使用Neo4J的更多信息,请参见“第30.3节,“Neo4j”“,在本章前面。
![]() |
启用的自动配置设置的列表。 |
下面的示例展示了在SpringBoot中使用Neo4J测试的典型设置:
- 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;
-
- //
- }
默认情况下,DataNeo4j测试是事务性的,在每个测试结束时回滚。见相关部分在SpringFramework参考文档中获得更多细节。如果这不是您想要的,您可以禁用测试或整个类的事务管理,如下所示:
- 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 {
-
- }
你可以用@DataRedisTest
测试Redis应用程序。默认情况下,它扫描@RedisHash
类和配置SpringDataRedis存储库。正规化@Component
bean未加载到ApplicationContext
。(有关在SpringBoot中使用Redis的更多信息,请参见“第30.1节,“Redis”“,在本章前面。
![]() |
启用的自动配置设置的列表。 |
下面的示例显示@DataRedisTest
正在使用的注释:
- 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;
-
- //
- }
你可以用@DataLdapTest
测试LDAP应用程序。默认情况下,它配置内存中嵌入的ldap(如果可用),配置LdapTemplate
,扫描@Entry
类,并配置Spring数据LDAP存储库。正规化@Component
bean未加载到ApplicationContext
。(有关在SpringBoot中使用LDAP的更多信息,请参见“第30.9节,“LDAP”“,在本章前面。
![]() |
启用的自动配置设置的列表。 |
下面的示例显示@DataLdapTest
正在使用的注释:
- 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 {
-
- }
您可以使用@RestClientTest
用于测试REST客户端的注释。默认情况下,它自动配置Jackson、gson和jsonb支持,配置RestTemplateBuilder
,并增加了对MockRestServiceServer
。正规化@Component
bean未加载到ApplicationContext
.
![]() |
启用的自动配置设置的列表。 |
属性指定要测试的特定bean。value
或components
属性@RestClientTest
,如以下示例所示:
@RunWith(SpringRunner.class) @RestClientTest(RemoteVehicleDetailsService.class) public class ExampleRestClientTest { @Autowired private RemoteVehicleDetailsService service; @Autowired private MockRestServiceServer server; @Test public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() throws Exception { this.server.expect(requestTo("/greet/details")) .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN)); String greeting = this.service.callRestService(); assertThat(greeting).isEqualTo("hello"); } }
您可以使用@AutoConfigureRestDocs
要使用的注释弹簧休息文档在您的测试中使用Mock MVC还是放心。它消除了SpringREST文档中对JUnit规则的需求。
@AutoConfigureRestDocs
可以用来覆盖默认输出目录(target/generated-snippets
如果您正在使用Maven或build/generated-snippets
如果您正在使用Gradle)。它还可以用于配置出现在任何文档URI中的主机、方案和端口。
用Mock MVC自动配置SpringREST文档测试
@AutoConfigureRestDocs
自定义MockMvc
bean使用SpringREST文档。您可以使用@Autowired
并在测试中使用它,就像在使用Mock MVC和SpringREST文档时一样,如下面的示例所示:
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")); } }
如果您需要对SpringRESTDocs配置的控制比@AutoConfigureRestDocs
,您可以使用RestDocsMockMvcConfigurationCustomizer
bean,如以下示例所示:
- @TestConfiguration
- static class CustomizationConfiguration
- implements RestDocsMockMvcConfigurationCustomizer {
-
- @Override
- public void customize(MockMvcRestDocumentationConfigurer configurer) {
- configurer.snippets().withTemplateFormat(TemplateFormats.markdown());
- }
-
- }
如果要使用SpringRESTDocs对参数化输出目录的支持,可以创建RestDocumentationResultHandler
豆子自动配置调用alwaysDo
使用此结果处理程序,从而导致每个MockMvc
调用以自动生成默认代码段。下面的示例显示RestDocumentationResultHandler
定义如下:
- @TestConfiguration
- static class ResultHandlerConfiguration {
-
- @Bean
- public RestDocumentationResultHandler restDocumentation() {
- return MockMvcRestDocumentation.document("{method-name}");
- }
-
- }
自动配置的SpringREST文档测试
@AutoConfigureRestDocs
使.RequestSpecification
bean,预先配置为使用SpringREST文档,可用于测试。您可以使用@Autowired
并在测试中使用它,就像在使用REST和SpringREST文档时一样,如下面的示例所示:
import io.restassured.specification.RequestSpecification; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureRestDocs public class UserDocumentationTests { @LocalServerPort private int port; @Autowired private RequestSpecification documentationSpec; @Test public void listUsers() { given(this.documentationSpec).filter(document("list-users")).when() .port(this.port).get("/").then().assertThat().statusCode(is(200)); } }
如果您需要对SpringRESTDocs配置的控制比@AutoConfigureRestDocs
..RestDocsRestAssuredConfigurationCustomizer
可以使用bean,如以下示例所示:
- @TestConfiguration
- public static class CustomizationConfiguration
- implements RestDocsRestAssuredConfigurationCustomizer {
-
- @Override
- public void customize(RestAssuredRestDocumentationConfigurer configurer) {
- configurer.snippets().withTemplateFormat(TemplateFormats.markdown());
- }
-
- }
每个切片提供一个或多个@AutoConfigure…
注释,即定义应该作为片的一部分包含的自动配置。可以通过创建自定义来添加其他自动配置。@AutoConfigure…
注释或简单地添加@ImportAutoConfiguration
如下面的示例所示:
- @RunWith(SpringRunner.class)
- @JdbcTest
- @ImportAutoConfiguration(IntegrationAutoConfiguration.class)
- public class ExampleJdbcTests {
-
- }
![]() |
确保不使用常规 |
如果你构造代码以一种明智的方式,你的@SpringBootApplication
类是默认使用作为测试的配置。
然后,重要的是不要用特定于特定功能领域的配置设置丢弃应用程序的主类。
假设您正在使用Spring批处理,并依赖于它的自动配置。你可以定义你的@SpringBootApplication
详情如下:
- @SpringBootApplication
- @EnableBatchProcessing
- public class SampleApplication { ... }
因为这个类是测试的源配置,所以任何片测试实际上都试图启动Spring批处理,这肯定不是您想要做的。推荐的方法是将特定区域的配置移动到单独的。@Configuration
在与应用程序相同的级别初始化,如以下示例所示:
- @Configuration
- @EnableBatchProcessing
- public class BatchConfiguration { ... }
![]() |
根据应用程序的复杂性,您可能有一个 |
另一个造成混乱的原因是类路径扫描。假设,当您以合理的方式构造您的代码时,您需要扫描一个额外的包。您的应用程序可能类似以下代码:
- @SpringBootApplication
- @ComponentScan({ "com.example.app", "org.acme.another" })
- public class SampleApplication { ... }
这样做可以有效地覆盖默认组件扫描指令,并附带扫描这两个包的副作用,而不管您选择的是哪个切片。例如,@DataJpaTest
似乎突然扫描了应用程序的组件和用户配置。同样,将自定义指令移动到单独的类是解决此问题的好方法。
![]() |
如果这不是一个选项,您可以创建一个 |
如果希望使用Spock测试SpringBoot应用程序,则应该添加对Spock的依赖项spock-spring
模块到应用程序的构建。spock-spring
将Spring的测试框架集成到Spock中。建议您使用Spock 1.1或更高版本,以受益于对Spock的Spring框架和SpringBoot集成的许多改进。看见Spock的Spring模块文档更多细节。
测试应用程序时通常有用的一些测试实用程序类打包为spring-boot
.
ConfigFileApplicationContextInitializer
是ApplicationContextInitializer
可以应用于测试来加载SpringBootapplication.properties
档案。当您不需要@SpringBootTest
,如以下示例所示:
- @ContextConfiguration(classes = Config.class,
- initializers = ConfigFileApplicationContextInitializer.class)
![]() |
使用 |
TestPropertyValues
允许您快速将属性添加到ConfigurableEnvironment
或ConfigurableApplicationContext
。你可以用key=value
字符串如下:
TestPropertyValues.of("org=Spring", "name=Boot").applyTo(env);
OutputCapture
是JUnitRule
你可以用来捕捉System.out
和System.err
输出。可以将捕获声明为@Rule
然后使用toString()
对于断言,如下所示:
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")); } }
![]() |
SpringFramework5.0提供了一个新的 |
TestRestTemplate
是春天的另一种方便的选择RestTemplate
这在集成测试中很有用。您可以获得一个普通模板或发送基本HTTP身份验证的模板(带有用户名和密码)。在这两种情况下,模板都以一种测试友好的方式运行,不对服务器端错误抛出异常。建议使用ApacheHTTP客户端(4.3.2或更高版本),但不是强制性的。如果你的类路径上有这个,TestRestTemplate
通过适当配置客户端进行响应。如果您确实使用了Apache的HTTP客户端,则启用了一些额外的测试友好特性:
TestRestTemplate
可以在集成测试中直接实例化,如以下示例所示:
- public class MyTest {
-
- private TestRestTemplate template = new TestRestTemplate();
-
- @Test
- public void testRequest() throws Exception {
- HttpHeaders headers = this.template.getForEntity(
- "http://myhost.example.com/example", String.class).getHeaders();
- assertThat(headers.getLocation()).hasHost("other.example.com");
- }
-
- }
或者,如果您使用@SpringBootTest
注释WebEnvironment.RANDOM_PORT
或WebEnvironment.DEFINED_PORT
,您可以注入一个完全配置的TestRestTemplate
然后开始使用它。如果有必要,可以通过RestTemplateBuilder
豆子没有指定主机和端口的任何URL都会自动连接到嵌入式服务器,如下面的示例所示:
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class SampleWebClientTests { @Autowired private TestRestTemplate template; @Test public void testRequest() { HttpHeaders headers = this.template.getForEntity("/example", String.class) .getHeaders(); assertThat(headers.getLocation()).hasHost("other.example.com"); } @TestConfiguration static class Config { @Bean public RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(1)) .setReadTimeout(Duration.ofSeconds(1)); } } }
SpringBoot提供了用于嵌入式Tomcat、Jetty和Under拖车的WebSocket自动配置。如果将WAR文件部署到独立容器,SpringBoot假定容器负责WebSocket支持的配置。
Spring框架提供富WebSocket支持对于mvc web应用程序,可以通过spring-boot-starter-websocket
模块。
WebSocket支持也可用于反应性Web应用并要求将WebSocketAPI与spring-boot-starter-webflux
:
- <dependency>
- <groupId>javax.websocket</groupId>
- <artifactId>javax.websocket-api</artifactId>
- </dependency>
Spring Boot提供了Web服务的自动配置,所以您必须做的就是定义Endpoints
.
这,这个,那,那个SpringWeb服务特性可以轻松地使用spring-boot-starter-webservices
模块。
SimpleWsdl11Definition
和SimpleXsdSchema
bean可以分别为WSDL和XSD自动创建。为此,配置它们的位置,如下面的示例所示:
spring.webservices.wsdl-locations=classpath:/wsdl
WebServiceTemplate
如果需要从应用程序调用远程Web服务,可以使用WebServiceTemplate
班级,等级自WebServiceTemplate
实例在使用之前通常需要进行自定义,SpringBoot不提供任何单独的自动配置。WebServiceTemplate
豆子但是,它会自动配置一个WebServiceTemplateBuilder
,可以用来创建WebServiceTemplate
需要时执行实例。
下面的代码显示了一个典型的示例:
- @Service
- public class MyService {
-
- private final WebServiceTemplate webServiceTemplate;
-
- public MyService(WebServiceTemplateBuilder webServiceTemplateBuilder) {
- this.webServiceTemplate = webServiceTemplateBuilder.build();
- }
-
- public DetailsResp someWsCall(DetailsReq detailsReq) {
- return (DetailsResp) this.webServiceTemplate.marshalSendAndReceive(detailsReq, new SoapActionCallback(ACTION));
-
- }
-
- }
默认情况下,WebServiceTemplateBuilder
检测合适的基于HTTP的WebServiceMessageSender
在类路径上使用可用的HTTP客户端库。您还可以自定义读取和连接超时,如下所示:
- @Bean
- public WebServiceTemplate webServiceTemplate(WebServiceTemplateBuilder builder) {
- return builder.messageSenders(new HttpWebServiceMessageSenderBuilder()
- .setConnectTimeout(5000).setReadTimeout(2000).build()).build();
- }
如果您在开发共享库的公司工作,或者在开源或商业库上工作,您可能需要开发自己的自动配置。自动配置类可以打包在外部JAR中,并且仍然可以通过SpringBoot来获取。
自动配置可以与提供自动配置代码的“初学者”相关联,以及您将与其一起使用的典型库。我们首先介绍构建您自己的自动配置所需的知识,然后继续讨论创建自定义启动程序所需的典型步骤.
![]() |
A 演示项目演示如何一步地创建初学者。 |
在引擎盖下,自动配置是用标准实现的。@Configuration
上课。额外@Conditional
注释用于限制何时应用自动配置。通常,自动配置类使用@ConditionalOnClass
和@ConditionalOnMissingBean
注释。这确保了自动配置只在找到相关类和尚未声明自己的类时应用。@Configuration
.
的源代码。spring-boot-autoconfigure
去看@Configuration
Spring提供的类(请参阅META-INF/spring.factories
档案)。
弹簧启动检查是否存在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
注释,但为自动配置类提供了专用订单。
![]() |
自动配置必须以这种方式加载。只。确保它们是在特定的包空间中定义的,特别是,它们永远不是组件扫描的目标。 |
您几乎总是希望包含一个或多个@Conditional
自动配置类的注释。这,这个,那,那个@ConditionalOnMissingBean
注释是一个常见的示例,用于允许开发人员在不满意默认设置的情况下覆盖自动配置。
Spring Boot包括@Conditional
注释,您可以通过注释在自己的代码中重用这些注释。@Configuration
阶级或个人@Bean
方法。这些说明包括:
这,这个,那,那个@ConditionalOnClass
和@ConditionalOnMissingClass
注释允许根据特定类的存在与否包括配置。由于注释元数据是通过ASM,您可以使用value
属性来引用真正的类,即使该类可能不会实际出现在正在运行的应用程序类路径中。您还可以使用name
属性指定类名时,请使用String
价值。
![]() |
如果你用 |
这,这个,那,那个@ConditionalOnBean
和@ConditionalOnMissingBean
注释允许根据是否存在特定bean来包含bean。您可以使用value
属性指定bean的类型或name
若要按名称指定bean,请执行以下操作。这,这个,那,那个search
属性允许您限制ApplicationContext
在搜索bean时应考虑的层次结构。
当放置在@Bean
方法时,目标类型默认为方法的返回类型,如以下示例所示:
- @Configuration
- public class MyAutoConfiguration {
-
- @Bean
- @ConditionalOnMissingBean
- public MyService myService() { ... }
-
- }
在前面的示例中,myService
如果没有类型的bean,则将创建bean。MyService
已包含在ApplicationContext
.
![]() |
对于添加bean定义的顺序,您需要非常小心,因为这些条件是根据到目前为止处理的内容来计算的。因此,我们建议只使用 |
![]() |
|
这,这个,那,那个@ConditionalOnProperty
注释允许基于SpringEnvironment属性包括配置。使用prefix
和name
属性指定应该检查的属性。默认情况下,存在和不等于false
是匹配的。还可以使用havingValue
和matchIfMissing
属性。
这,这个,那,那个@ConditionalOnResource
注释只允许在存在特定资源时包含配置。可以通过使用通常的Spring约定来指定资源,如下面的示例所示:file:/home/user/test.dat
.
这,这个,那,那个@ConditionalOnWebApplication
和@ConditionalOnNotWebApplication
注释允许包含配置,这取决于应用程序是否是“web应用程序”。Web应用程序是使用Spring的任何应用程序WebApplicationContext
,定义session
范围,或具有StandardServletEnvironment
.
这,这个,那,那个@ConditionalOnExpression
注释允许根据Spel表达式.
自动配置可能受到许多因素的影响:用户配置(@Bean
定义和Environment
(定制)、条件评估(存在特定库)以及其他。具体而言,每个测试都应该创建一个定义良好的ApplicationContext
表示这些自定义的组合。ApplicationContextRunner
为实现这一目标提供了一种很好的方法。
ApplicationContextRunner
通常定义为测试类的一个字段来收集基本的、通用的配置。下面的示例确保UserServiceAutoConfiguration
总是被引用:
- private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
- .withConfiguration(AutoConfigurations.of(UserServiceAutoConfiguration.class));
![]() |
如果必须定义多个自动配置,则不需要对它们的声明排序,因为它们的调用顺序与运行应用程序时的顺序完全相同。 |
每个测试都可以使用运行程序来表示特定的用例。例如,下面的示例调用一个用户配置(UserConfiguration
)并检查自动配置是否正确回退。调用run
提供可与Assert4J
.
@Test public void defaultServiceBacksOff() { this.contextRunner.withUserConfiguration(UserConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(UserService.class); assertThat(context.getBean(UserService.class)).isSameAs( context.getBean(UserConfiguration.class).myUserService()); }); } @Configuration static class UserConfiguration { @Bean public UserService myUserService() { return new UserService("mine"); } }
还可以轻松自定义Environment
,如以下示例所示:
- @Test
- public void serviceNameCanBeConfigured() {
- this.contextRunner.withPropertyValues("user.name=test123").run((context) -> {
- assertThat(context).hasSingleBean(UserService.class);
- assertThat(context.getBean(UserService.class).getName()).isEqualTo("test123");
- });
- }
转轮也可用于显示ConditionEvaluationReport
。报告可在INFO
或DEBUG
水平。下面的示例演示如何使用ConditionEvaluationReportLoggingListener
若要在自动配置测试中打印报表,请执行以下操作。
- @Test
- public void autoConfigTest {
- ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener(
- LogLevel.INFO);
- ApplicationContextRunner contextRunner = new ApplicationContextRunner()
- .withInitializer(initializer).run((context) -> {
- // Do something...
- });
- }
如果需要测试仅在servlet或反应性web应用程序上下文中操作的自动配置,请使用WebApplicationContextRunner
或ReactiveWebApplicationContextRunner
分别。
还可以测试在运行时不存在特定的类和/或包时会发生什么。弹簧启动船FilteredClassLoader
这很容易被跑步者使用。在下面的示例中,我们断言如果UserService
不存在,则自动配置被正确禁用:
- @Test
- public void serviceIsIgnoredIfLibraryIsNotPresent() {
- this.contextRunner.withClassLoader(new FilteredClassLoader(UserService.class))
- .run((context) -> assertThat(context).doesNotHaveBean("userService"));
- }
库的完整Spring启动程序可能包含以下组件:
autoconfigure
模块,其中包含自动配置代码。starter
提供依赖项的autoconfigure
模块以及库和任何通常有用的附加依赖项。简而言之,添加启动器应该提供开始使用该库所需的一切。![]() |
如果不需要将这两个关注点分开,则可以将自动配置代码和依赖关系管理组合在一个模块中。 |
您应该确保为初学者提供适当的命名空间。不要以spring-boot
,即使您使用不同的MavengroupId
。我们可能会提供官方支持的东西,您的自动配置在未来。
根据经验,您应该以初学者的名字命名组合模块。例如,假设您正在为“acme”创建一个启动程序,并将其命名为自动配置模块。acme-spring-boot-autoconfigure
和启动器acme-spring-boot-starter
。如果只有一个模块组合了这两个模块,请命名它。acme-spring-boot-starter
.
另外,如果初学者提供配置键,请为它们使用唯一的命名空间。尤其是,不要将键包含在SpringBoot使用的命名空间中(例如server
, management
, spring
等等)。如果您使用相同的命名空间,我们将来可能会以破坏模块的方式修改这些命名空间。
确保触发元数据生成这样,IDE辅助也可以用于您的密钥。您可能需要查看生成的元数据(META-INF/spring-configuration-metadata.json
)以确保您的钥匙有正确的文档记录。
autoconfigure
模块这,这个,那,那个autoconfigure
模块包含开始使用库所需的所有内容。它还可能包含配置键定义(如@ConfigurationProperties
)和任何可用于进一步自定义组件初始化方式的回调接口。
![]() |
应该将库的依赖项标记为可选的,以便可以将 |
SpringBoot使用注释处理器来收集元数据文件中自动配置的条件(META-INF/spring-autoconfigure-metadata.properties
)如果该文件存在,则用于筛选不匹配的自动配置,这将缩短启动时间。建议在包含自动配置的模块中添加以下依赖项:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-autoconfigure-processor</artifactId>
- <optional>true</optional>
- </dependency>
对于Gradle 4.5和更早版本,应该在compileOnly
配置,如以下示例所示:
- dependencies {
- compileOnly "org.springframework.boot:spring-boot-autoconfigure-processor"
- }
对于Gradle 4.6及更高版本,应该在annotationProcessor
配置,如以下示例所示:
- dependencies {
- annotationProcessor "org.springframework.boot:spring-boot-autoconfigure-processor"
- }
起动机实际上是一个空罐子。它的唯一目的是提供使用库所需的依赖项。你可以把它看作是对开始所需要的东西的一种固执己见的看法。
不要对添加启动程序的项目进行假设。如果您要自动配置的库通常需要其他启动程序,那么也要提到它们。提供一套合适的违约如果可选依赖项的数量很高,则依赖关系可能很困难,因为您应该避免包含对于库的典型使用来说不必要的依赖关系。换句话说,您不应该包括可选的依赖项。
![]() |
无论哪种方式,您的启动程序都必须引用核心SpringBootStart( |
科特林是一种针对jvm(和其他平台)的静态类型语言,它允许编写简洁而优雅的代码,同时提供互操作性使用Java编写的现有库。
SpringBoot通过利用Spring框架、Spring数据和反应堆等其他Spring项目中的支持来提供Kotlin支持。见Spring Framework Kotlin支持文档想了解更多信息。
从SpringBoot和Kotlin开始,最简单的方法就是遵循本综合教程。您可以通过以下方式创建新的kotlin项目start.spring.io。欢迎加入#Spring频道科特林·斯拉克或者用spring
和kotlin
标签上堆栈溢出如果你需要支持的话。
Spring Boot支持Kotlin 1.2.x。利用Kotlin,org.jetbrains.kotlin:kotlin-stdlib
和org.jetbrains.kotlin:kotlin-reflect
一定在类路径上。这,这个,那,那个kotlin-stdlib
变体kotlin-stdlib-jdk7
和kotlin-stdlib-jdk8
也可以使用。
自默认情况下,kotlin类是最终类。,您可能希望配置科特林-弹簧插件,以便自动打开Spring注释的类,以便它们可以被代理.
Jackson的Kotlin模块用于序列化/反序列化Kotlin中的JSON数据。当在类路径上找到它时,它会自动注册。如果Jackson和Kotlin存在,则会记录一条警告消息,但Jackson Kotlin模块不存在。
![]() |
这些依赖项和插件是默认情况下提供的,如果一个引导程序将kotlin项目引导到start.spring.io. |
Kotlin的主要特征之一是零安全。它处理的是null
值,而不是将问题推迟到运行时并遇到NullPointerException
。这有助于消除常见的bug来源,而无需支付包装器的费用,例如Optional
。Kotlin还允许使用带有可空值的函数构造,如科特林空安全综合指南.
尽管Java不允许在其类型系统中表示空安全性,但是Spring框架、Spring数据和反应堆现在通过工具友好的注释提供了API的空安全性。默认情况下,Kotlin中使用的JavaAPI中的类型被识别为平台类型对此,空检查是放松的。Kotlin对JSR 305注释的支持结合可空性,注释为Kotlin中相关的SpringAPI提供了空安全性。
可以通过添加-Xjsr305
具有下列选项的编译器标志:-Xjsr305={strict|warn|ignore}
。默认行为与-Xjsr305=warn
。这,这个,那,那个strict
值需要在从SpringAPI推断的Kotlin类型中被考虑到空安全性,但在使用时应该知道SpringAPI的可空性声明甚至可能在次要版本之间发展,而且将来可能会增加更多的检查)。
Spring Boot提供了一种惯用的方法来运行应用程序runApplication<MyApplication>(*args)
如以下示例所示:
- import org.springframework.boot.autoconfigure.SpringBootApplication
- import org.springframework.boot.runApplication
-
- @SpringBootApplication
- class MyApplication
-
- fun main(args: Array<String>) {
- runApplication<MyApplication>(*args)
- }
这是对SpringApplication.run(MyApplication::class.java, *args)
。它还允许定制应用程序,如以下示例所示:
- runApplication<MyApplication>(*args) {
- setBannerMode(OFF)
- }
科特林扩展提供扩展具有其他功能的现有类的能力。SpringBootKotlinAPI利用这些扩展为现有的API添加新的Kotlin专用便利。
TestRestTemplate
扩展,类似于Spring框架为RestOperations
在Spring框架中提供。除其他外,扩展可以利用Kotlin具体化的类型参数。
为了避免在类路径上混合不同版本的Kotlin依赖项,提供了以下Kotlin依赖项的依赖关系管理:
kotlin-reflect
kotlin-runtime
kotlin-stdlib
kotlin-stdlib-jdk7
kotlin-stdlib-jdk8
kotlin-stdlib-jre7
kotlin-stdlib-jre8
使用Maven,Kotlin版本可以通过kotlin.version
属性和插件管理是为kotlin-maven-plugin
。使用Gradle,SpringBoot插件自动对齐kotlin.version
用Kotlin插件的版本。
@ConfigurationProperties
@ConfigurationProperties
目前只适用于lateinit
或可空var
属性(建议使用前者),因为由构造函数初始化的不可变类是尚未得到支持.
@ConfigurationProperties("example.kotlin") class KotlinExampleProperties { lateinit var name: String lateinit var description: String val myService = MyService() class MyService { lateinit var apiToken: String lateinit var uri: URI } }
虽然可以使用JUnit 4(默认情况下由spring-boot-starter-test
)为了测试Kotlin代码,建议使用JUnit 5。JUnit 5使测试类能够实例化一次,并在类的所有测试中重用。这样就可以使用@BeforeAll
和@AfterAll
关于非静态方法的注释,这很适合Kotlin。
若要使用JUnit 5,请排除junit:junit
依赖于spring-boot-starter-test
,添加JUnit 5依赖项,并相应地配置Maven或Gradle插件。见JUnit 5文件更多细节。你也需要将测试实例生命周期切换到“每类”。.
spring
和kotlin
标签如果您想了解本节中讨论的任何类的更多信息,可以查看SpringBootAPI文档或者您可以浏览直接源代码。如果您有特定的问题,请查看如何部分。
如果您对SpringBoot的核心特性感到满意,您可以继续阅读生产准备功能.
SpringBoot包含了许多其他特性,以帮助您在将应用程序推向生产时监视和管理它。您可以选择使用HTTP端点或使用JMX来管理和监视应用程序。审计、健康和度量收集也可以自动应用于应用程序。
这,这个,那,那个spring-boot-actuator
模块提供了SpringBoot的所有生产准备功能。启用这些特性的最简单方法是将依赖项添加到spring-boot-starter-actuator
“Starter”
执行器的定义
执行器是指用于移动或控制某物的机械装置的制造术语。执行器可以从一个小的变化中产生大量的运动。
若要将执行器添加到基于Maven的项目中,请添加以下“初学者”依赖项:
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-actuator</artifactId>
- </dependency>
- </dependencies>
对于Gradle,使用以下声明:
- dependencies {
- compile("org.springframework.boot:spring-boot-starter-actuator")
- }
执行器端点允许您监视应用程序并与其交互。SpringBoot包含许多内置端点,并允许您添加自己的端点。例如,health
端点提供了基本的应用程序健康信息。
每个端点可以是启用或禁用。这将控制端点是否已创建,其bean是否存在于应用程序上下文中。要远程访问,端点还必须是通过JMX或HTTP公开。大多数应用程序选择HTTP,其中端点的ID以及前缀为/actuator
映射到URL。例如,默认情况下,health
端点映射到/actuator/health
.
有以下与技术无关的端点:
ID | 描述 | 默认启用 |
---|---|---|
| 公开当前应用程序的审核事件信息。 | 是 |
| 显示应用程序中所有Springbean的完整列表。 | 是 |
| 公开可用的缓存。 | 是 |
| 显示在配置类和自动配置类上计算的条件以及它们匹配或不匹配的原因。 | 是 |
| 显示所有 | 是 |
| 公开Spring的属性 | 是 |
| 显示已应用的任何天桥数据库迁移。 | 是 |
| 显示应用程序健康信息。 | 是 |
| 显示HTTP跟踪信息(默认情况下,最后100个HTTP请求-响应交换)。 | 是 |
| 显示任意应用程序信息。 | 是 |
| 显示Spring集成图。 | 是 |
| 显示和修改应用程序中记录器的配置。 | 是 |
| 显示已应用的任何Liquibase数据库迁移。 | 是 |
| 显示当前应用程序的“度量”信息。 | 是 |
| 显示所有 | 是 |
| 显示应用程序中的计划任务。 | 是 |
| 允许从Spring会话支持的会话存储中检索和删除用户会话。当使用Spring会话对反应性Web应用程序的支持时不可用。 | 是 |
| 让应用程序优雅地关闭。 | 否 |
| 执行线程转储。 | 是 |
如果您的应用程序是Web应用程序(SpringMVC、SpringWebFlux或泽西岛),则可以使用以下附加端点:
ID | 描述 | 默认启用 |
---|---|---|
| 返回压缩的GZip | 是 |
| 通过HTTP公开JMX bean(当Jolokia在类路径上时,WebFlux不可用)。 | 是 |
| 返回日志文件的内容(如果 | 是 |
| 以Prometheus服务器可以刮取的格式公开度量。 | 是 |
要了解更多关于Actuator端点及其请求和响应格式的信息,请参阅单独的API文档(HTML或PDF).
默认情况下,除shutdown
都启用了。若要配置端点的启用,请使用其management.endpoint.<id>.enabled
财产。下面的示例启用shutdown
端点:
management.endpoint.shutdown.enabled=true
如果希望启用端点而不是选择退出,请将management.endpoints.enabled-by-default
财产false
并使用单个端点enabled
属性选择返回。下面的示例启用info
终结点并禁用所有其他端点:
- management.endpoints.enabled-by-default=false
- management.endpoint.info.enabled=true
![]() |
禁用的端点将从应用程序上下文中完全删除。如果只想更改公开端点的技术,请使用 |
由于端点可能包含敏感信息,因此应该仔细考虑何时公开它们。下表显示了内置端点的默认公开:
ID | JMX | 万维网 |
---|---|---|
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 是 |
| N/A | 否 |
| 是 | 否 |
| 是 | 是 |
| 是 | 是 |
| N/A | 否 |
| N/A | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
| N/A | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
| 是 | 否 |
若要更改公开的端点,请使用下列特定技术include
和exclude
物业:
财产 | 违约 |
---|---|
| |
|
|
| |
|
|
这,这个,那,那个include
属性列出公开的端点的ID。这,这个,那,那个exclude
属性列出不应公开的端点的ID。这,这个,那,那个exclude
属性优先于include
财产。双管齐下include
和exclude
属性可以配置为端点ID列表。
例如,停止在JMX上公开所有端点,而只公开health
和info
端点,使用以下属性:
management.endpoints.jmx.exposure.include=health,info
*
可用于选择所有端点。例如,要通过HTTP公开所有内容,除了env
和beans
端点,使用以下属性:
- management.endpoints.web.exposure.include=*
- management.endpoints.web.exposure.exclude=env,beans
![]() |
|
![]() |
如果您的应用程序是公开的,我们强烈建议您也保护你的端点. |
![]() |
如果要实现自己的端点公开策略,可以注册 |
您应该注意以与任何其他敏感URL相同的方式保护HTTP端点。如果SpringSecurity存在,则使用SpringSecurity的内容协商策略在默认情况下保护端点。如果您希望为HTTP端点配置自定义安全性,例如,只允许具有特定角色的用户访问它们,SpringBoot提供了一些方便RequestMatcher
对象,这些对象可以与SpringSecurity组合使用。
典型的Spring安全配置可能如下所示:
- @Configuration
- public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
- .anyRequest().hasRole("ENDPOINT_ADMIN")
- .and()
- .httpBasic();
- }
-
- }
前面的示例使用EndpointRequest.toAnyEndpoint()
若要将请求与任何端点匹配,然后确保所有请求都具有ENDPOINT_ADMIN
角色。其他几种匹配方法也可用于EndpointRequest
。请参阅API文档(HTML或PDF)的细节。
如果您在防火墙后部署应用程序,您可能更希望您的所有执行器端点都可以被访问,而不需要身份验证。您可以通过更改management.endpoints.web.exposure.include
财产如下:
应用特性。
management.endpoints.web.exposure.include=*
此外,如果SpringSecurity存在,则需要添加自定义安全配置,该配置允许对端点进行未经身份验证的访问,如下面的示例所示:
- @Configuration
- public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
- .anyRequest().permitAll();
- }
-
- }
端点自动缓存不接受任何参数的读取操作的响应。若要配置端点缓存响应的时间量,请使用其cache.time-to-live
财产。下面的示例设置beans
端点的缓存为10秒:
应用特性。
management.endpoint.beans.cache.time-to-live=10s
![]() |
前缀 |
![]() |
发出经过身份验证的HTTP请求时, |
添加了一个“发现页”,其中包含指向所有端点的链接。“发现页”可在/actuator
默认情况下。
配置自定义管理上下文路径时,“发现页”将自动从/actuator
管理上下文的根。例如,如果管理上下文路径是/management
,则发现页可从/management
。当管理上下文路径设置为/
,则禁用发现页以防止与其他映射发生冲突的可能性。
跨源资源共享(CORS)是W3C规范这允许您以灵活的方式指定什么类型的跨域请求被授权。如果使用SpringMVC或SpringWebFlux,则可以配置Actuator的Web端点以支持此类场景。
默认情况下,CORS支持是禁用的,并且仅在management.endpoints.web.cors.allowed-origins
属性已设置。以下配置允许GET
和POST
从example.com
域:
- management.endpoints.web.cors.allowed-origins=http://example.com
- management.endpoints.web.cors.allowed-methods=GET,POST
![]() |
看见CorsEndpoint性质有关选项的完整列表。 |
如果添加@Bean
带注释@Endpoint
,任何带有注释的方法@ReadOperation
, @WriteOperation
,或@DeleteOperation
自动在JMX上公开,在Web应用程序中也通过HTTP公开。可以使用泽西、SpringMVC或SpringWebFlux通过HTTP公开端点。
还可以通过以下方法编写特定于技术的端点:@JmxEndpoint
或@WebEndpoint
。这些端点仅限于各自的技术。例如@WebEndpoint
只能通过HTTP而不是通过JMX公开。
可以通过以下方法编写特定于技术的扩展:@EndpointWebExtension
和@EndpointJmxExtension
。这些注释允许您提供特定于技术的操作来增强现有端点。
最后,如果需要访问特定于web框架的功能,则可以实现servlet或Spring。@Controller
和@RestController
端点的代价是它们无法通过JMX或使用不同的Web框架获得。
端点上的操作通过其参数接收输入。当通过Web公开时,这些参数的值将从URL的查询参数和JSON请求体中获取。当通过JMX公开时,参数将映射到MBean操作的参数。默认情况下需要参数。它们可以通过用@org.springframework.lang.Nullable
.
JSON请求体中的每个根属性都可以映射到端点的一个参数。考虑以下JSON请求体:
- {
- "name": "test",
- "counter": 42
- }
这可用于调用一个写操作,该操作将String name
和int counter
参数。
![]() |
因为端点与技术无关,所以只能在方法签名中指定简单类型。特别是声明具有自定义类型的单个参数,该类型定义 |
![]() |
为了允许将输入映射到操作方法的参数,实现端点的Java代码应该用 |
输入类型转换
如果有必要,传递给端点操作方法的参数将自动转换为所需的类型。在调用操作方法之前,通过JMX或HTTP请求接收的输入将使用ApplicationConversionService
.
上的操作。@Endpoint
, @WebEndpoint
,或@EndpointWebExtension
使用泽西、SpringMVC或SpringWebFlux通过HTTP自动公开。
Web端点请求谓词
对于Web公开的端点上的每个操作,都会自动生成请求谓词.
路径
谓词的路径由端点的ID和Web暴露的端点的基本路径决定。默认的基本路径是/actuator
。例如,具有ID的端点sessions
将使用/actuator/sessions
作为谓词中的路径。
通过注释操作方法的一个或多个参数,可以进一步定制路径。@Selector
。这样的参数作为路径变量添加到路径谓词中。当调用端点操作时,变量的值将传递给操作方法。
http方法
谓词的HTTP方法由操作类型确定,如下表所示:
操作 | http方法 |
---|---|
|
|
|
|
|
|
消费
为了@WriteOperation
(httpPOST
),它使用请求体,谓词的USEES子句是application/vnd.spring-boot.actuator.v2+json, application/json
。对于所有其他操作,USPES子句为空。
产
谓词的Products子句可以由produces
属性的@DeleteOperation
, @ReadOperation
,和@WriteOperation
注释。属性是可选的。如果不使用它,则会自动确定Products子句。
如果操作方法返回void
或Void
Products子句为空。如果操作方法返回org.springframework.core.io.Resource
,产生子句是application/octet-stream
。对于所有其他操作,Products子句为application/vnd.spring-boot.actuator.v2+json, application/json
.
Web端点响应状态
端点操作的默认响应状态取决于操作类型(读、写或删除)以及操作返回的内容(如果有的话)。
A @ReadOperation
返回一个值,响应状态为200(OK)。如果不返回值,则响应状态为404(未找到)。
如果@WriteOperation
或@DeleteOperation
返回一个值,响应状态为200(OK)。如果不返回值,则响应状态为204(无内容)。
如果在没有必需参数的情况下调用操作,或者使用不能转换为所需类型的参数调用操作方法,则响应状态将为400(坏请求)。
Web端点范围请求
HTTP范围请求可用于请求HTTP资源的一部分。当使用SpringMVC或SpringWebFlux时,返回org.springframework.core.io.Resource
自动支持范围请求。
![]() |
使用泽西时不支持范围请求。 |
Web端点安全
web端点或特定于web的端点扩展上的操作可以接收当前java.security.Principal
或org.springframework.boot.actuate.endpoint.SecurityContext
作为方法参数。前者通常与@Nullable
为经过身份验证的用户和未经身份验证的用户提供不同的行为。后者通常用于使用其isUserInRole(String)
方法。
A Servlet
通过实现带注释的类,可以将其公开为端点。@ServletEndpoint
也实现了Supplier<EndpointServlet>
。Servlet端点提供与servlet容器更深层次的集成,但代价是可移植性。它们用于公开现有的Servlet
作为终点。对于新的端点,@Endpoint
和@WebEndpoint
只要有可能,应该首选注释。
@ControllerEndpoint
和@RestControllerEndpoint
可以用于实现仅由SpringMVC或SpringWebFlux公开的端点。使用SpringMVC和SpringWebFlux的标准注释映射方法,如@RequestMapping
和@GetMapping
,将端点的ID用作路径的前缀。控制器端点提供与Spring的Web框架更深层次的集成,但代价是可移植性。这,这个,那,那个@Endpoint
和@WebEndpoint
只要有可能,应该首选注释。
您可以使用健康信息来检查正在运行的应用程序的状态。当生产系统发生故障时,监控软件经常使用它来警告某人。公开的信息health
端点依赖于management.endpoint.health.show-details
属性,可以使用以下值之一配置该属性:
名字,姓名 | 描述 |
---|---|
| 细节永远不会显示。 |
| 详细信息只显示给授权用户。授权角色可以使用 |
| 详细信息显示给所有用户。 |
默认值是never
。当用户处于端点的一个或多个角色时,他们被认为是被授权的。如果端点没有配置角色(默认),则所有经过身份验证的用户都被视为已授权。可以使用management.endpoint.health.roles
财产。
![]() |
如果您已经保护了您的应用程序并希望使用 |
健康信息是从 HealthIndicatorRegistry
(默认情况下,所有HealthIndicator
中定义的实例。ApplicationContext
。Spring Boot包括许多自动配置的HealthIndicators
你也可以自己写。默认情况下,最终系统状态由HealthAggregator
对每个状态进行排序。HealthIndicator
基于一个有序的状态列表。排序列表中的第一个状态用作总体健康状态。如果没有HealthIndicator
返回已知的状态。HealthAggregator
..UNKNOWN
使用状态。
![]() |
这,这个,那,那个 |
以下内容HealthIndicators
在适当情况下由SpringBoot自动配置:
名字,姓名 | 描述 |
---|---|
检查卡桑德拉数据库是否启动。 | |
检查低磁盘空间。 | |
检查连接到 | |
检查Elasticearch集群是否已启动。 | |
检查InfluxDB服务器是否已启动。 | |
检查JMS代理是否已运行。 | |
检查邮件服务器是否已启动。 | |
检查蒙戈数据库是否打开。 | |
检查Neo4j服务器是否已启动。 | |
检查兔子服务器是否启动。 | |
检查Redis服务器是否已启动。 | |
检查Solr服务器是否已启动。 |
![]() |
可以通过设置 |
若要提供自定义健康信息,可以注册实现HealthIndicator
接口。您需要提供health()
方法并返回Health
回应。这,这个,那,那个Health
响应应该包括状态,并且可以选择包括要显示的其他详细信息。下面的代码显示了一个示例HealthIndicator
执行情况:
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(); } }
![]() |
给定值的标识符。 |
除了SpringBoot的预定义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)。如果通过HTTP访问健康端点,还可能希望注册自定义状态映射。例如,以下属性映射FATAL
至503(服务不可用):
management.health.status.http-mapping.FATAL=503
![]() |
如果您需要更多的控制,您可以定义自己的 |
下表显示了内置状态的默认状态映射:
地位 | 映射 |
---|---|
向下 | 服务不可用(503) |
停用 | 服务不可用(503) |
向上 | 默认情况下不进行映射,因此http状态为200。 |
未知数 | 默认情况下不进行映射,因此http状态为200。 |
对于反应性应用程序,如使用SpringWebFlux的应用程序,ReactiveHealthIndicator
提供非阻塞契约,以获得应用程序健康。类似于传统HealthIndicator
的内容收集健康信息。 ReactiveHealthIndicatorRegistry
(默认情况下,所有HealthIndicator
和 ReactiveHealthIndicator
中定义的实例。ApplicationContext
。正规化HealthIndicator
在弹性调度程序上执行不针对反应性API的检查。
![]() |
在反应性应用程序中, |
若要从反应性API中提供自定义健康信息,可以注册实现ReactiveHealthIndicator
接口。下面的代码显示了一个示例ReactiveHealthIndicator
执行情况:
- @Component
- public class MyReactiveHealthIndicator implements ReactiveHealthIndicator {
-
- @Override
- public Mono<Health> health() {
- return doHealthCheck() //perform some specific health check that returns a Mono<Health>
- .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build())));
- }
-
- }
![]() |
若要自动处理错误,请考虑从 |
以下内容ReactiveHealthIndicators
在适当情况下由SpringBoot自动配置:
名字,姓名 | 描述 |
---|---|
检查卡桑德拉数据库是否启动。 | |
检查蒙戈数据库是否打开。 | |
检查Redis服务器是否已启动。 |
![]() |
如有必要,应采用反应性指标取代常规指标。还有,任何 |
应用程序信息公开从所有InfoContributor
中定义的beanApplicationContext
。Spring Boot包括许多自动配置的InfoContributor
豆子,你可以自己写。
以下内容InfoContributor
在适当的情况下,Spring Boot会自动配置bean:
名字,姓名 | 描述 |
---|---|
公开 | |
如果 | |
如果 |
![]() |
可以通过设置 |
您可以自定义由info
通过设置端点info.*
弹簧特性。全Environment
属性下的属性。info
键会自动暴露。例如,可以将下列设置添加到application.properties
档案:
- info.app.encoding=UTF-8
- info.app.java.source=1.8
- info.app.java.target=1.8
![]() |
与其硬编码这些值,您还可以在构建时展开info属性. 假设您使用了Maven,您可以重写前面的示例,如下所示: |
的另一个有用特性info
端点是它发布有关git
构建项目时的源代码存储库。如果GitProperties
bean可用,则git.branch
, git.commit.id
,和git.commit.time
属性暴露了。
![]() |
A |
如果要显示完整的git信息(即git.properties
),使用management.info.git.mode
财产如下:
management.info.git.mode=full
如果BuildProperties
bean可用,则info
端点还可以发布有关生成的信息。如果META-INF/build-info.properties
文件可在类路径中使用。
![]() |
Maven和Gradle插件都可以生成该文件。见“生成信息“更多细节。 |
若要提供自定义应用程序信息,可以注册实现InfoContributor
接口。
下面的示例提供了一个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 public class ExampleInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail("example", Collections.singletonMap("key", "value")); } }
如果你到达info
端点,您应该会看到一个包含以下附加条目的响应:
- {
- "example": {
- "key" : "value"
- }
- }
如果您正在开发一个Web应用程序,SpringBootActuator会自动配置所有启用的端点,以便通过HTTP公开。默认约定是使用id
的端点的前缀为/actuator
作为URL路径。例如health
暴露为/actuator/health
。提示:SpringMVC、SpringWebFlux和泽西支持执行机构。
有时,自定义管理端点的前缀是有用的。例如,您的应用程序可能已经使用了/actuator
为了另一个目的。您可以使用management.endpoints.web.base-path
属性更改管理端点的前缀,如以下示例所示:
management.endpoints.web.base-path=/manage
前文application.properties
示例将端点更改为/actuator/{id}
到/manage/{id}
(例如,/manage/info
).
![]() |
除非已将管理端口配置为使用不同的HTTP端口公开端点, |
如果要将端点映射到其他路径,则可以使用management.endpoints.web.path-mapping
财产。
下面的示例映射/actuator/health
到/healthcheck
:
应用特性。
- management.endpoints.web.base-path=/
- management.endpoints.web.path-mapping.health=healthcheck
使用默认的HTTP端口公开管理端点是基于云的部署的明智选择。但是,如果应用程序在您自己的数据中心内运行,您可能更愿意使用不同的HTTP端口来公开端点。
您可以设置management.server.port
属性更改HTTP端口,如以下示例所示:
management.server.port=8081
当配置为使用自定义端口时,管理服务器也可以使用它自己的ssl通过以下各种配置management.server.ssl.*
财产。例如,这样做可以让管理服务器在HTTP上可用,而主应用程序则使用HTTPS,如以下属性设置所示:
- server.port=8443
- server.ssl.enabled=true
- server.ssl.key-store=classpath:store.jks
- server.ssl.key-password=secret
- management.server.port=8080
- management.server.ssl.enabled=false
或者,主服务器和管理服务器都可以使用SSL,但可以使用不同的密钥存储,如下所示:
- server.port=8443
- server.ssl.enabled=true
- server.ssl.key-store=classpath:main.jks
- server.ssl.key-password=secret
- management.server.port=8080
- management.server.ssl.enabled=true
- management.server.ssl.key-store=classpath:management.jks
- management.server.ssl.key-password=secret
属性来自定义管理端点可用的地址。management.server.address
财产。如果您只想在内部或面向操作的网络上侦听,或者只想侦听来自localhost
.
![]() |
只有当端口与主服务器端口不同时,才能侦听不同的地址。 |
下面的示例application.properties
不允许远程管理连接:
- management.server.port=8081
- management.server.address=127.0.0.1
如果不希望通过HTTP公开端点,可以将管理端口设置为-1
,如以下示例所示:
management.server.port=-1
这可以使用management.endpoints.web.exposure.exclude
属性,如下面的示例所示:
management.endpoints.web.exposure.exclude=*
Java管理扩展(JMX)提供了监视和管理应用程序的标准机制。默认情况下,SpringBoot将管理端点作为JMX MBean公开在org.springframework.boot
域。
MBean的名称通常是从id
端点。例如,health
端点公开为org.springframework.boot:type=Endpoint,name=Health
.
如果应用程序包含多个SpringApplicationContext
,你可能会发现名字冲突。若要解决此问题,可以将spring.jmx.unique-names
财产true
所以MBean名称总是唯一的。
您还可以自定义暴露端点的JMX域。下面的设置显示了在application.properties
:
- spring.jmx.unique-names=true
- management.endpoints.jmx.domain=com.example.myapp
如果不希望在JMX上公开端点,则可以将management.endpoints.jmx.exposure.exclude
财产*
,如以下示例所示:
management.endpoints.jmx.exposure.exclude=*
Jolokia是一种JMX-HTTP桥,它提供了一种访问JMXbean的替代方法。若要使用Jolokia,请将依赖项包含到org.jolokia:jolokia-core
。例如,对于Maven,可以添加以下依赖项:
- <dependency>
- <groupId>org.jolokia</groupId>
- <artifactId>jolokia-core</artifactId>
- </dependency>
然后,可以通过添加jolokia
或*
到management.endpoints.web.exposure.include
财产。然后,您可以通过以下方式访问它:/actuator/jolokia
在您的管理HTTP服务器上。
Jolokia有许多设置,传统上通过设置servlet参数来配置这些设置。使用SpringBoot,您可以使用application.properties
档案。若要这样做,请在参数前面加上management.endpoint.jolokia.config.
,如以下示例所示:
management.endpoint.jolokia.config.debug=true
如果使用Jolokia但不希望SpringBoot配置它,请将management.endpoint.jolokia.enabled
财产false
,如下:
management.endpoint.jolokia.enabled=false
SpringBootActuator包括在运行时查看和配置应用程序日志级别的能力。您可以查看整个列表或单个记录器的配置,该配置由显式配置的日志级别以及日志框架提供的有效日志级别组成。这些级别可以是:
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
OFF
null
null
指示没有显式配置。
若要配置给定的记录器,POST
资源URI的部分实体,如以下示例所示:
- {
- "configuredLevel": "DEBUG"
- }
![]() |
若要“重置”记录器的特定级别(并使用默认配置),可以传递 |
SpringBoot执行器提供依赖关系管理和自动配置千分尺,支持多个监视系统的应用程序度量外观,包括:
Spring Boot自动配置复合MeterRegistry
并为它在类路径上找到的每个受支持的实现向复合添加一个注册表。依赖于micrometer-registry-{system}
在运行时,类路径足以让SpringBoot配置注册表。
大多数注册中心都有共同的特性。例如,即使千分尺注册表实现在类路径上,也可以禁用特定的注册表。例如,要禁用Datadog:
management.metrics.export.datadog.enabled=false
Spring Boot还会将任何自动配置的注册表添加到Metrics
除非您显式地告诉它不要:
management.metrics.use-global-registry=false
您可以注册任意数量的MeterRegistryCustomizer
bean以进一步配置注册表,例如在向注册表注册任何表之前应用公共标记:
- @Bean
- MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
- return registry -> registry.config().commonTags("region", "us-east-1");
- }
可以将自定义应用于特定的注册表实现,方法是更具体地说明泛型类型:
- @Bean
- MeterRegistryCustomizer<GraphiteMeterRegistry> graphiteMetricsNamingConvention() {
- return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION);
- }
有了这个设置,你就可以注入MeterRegistry
在组件和注册度量中:
- @Component
- public class SampleBean {
-
- private final Counter counter;
-
- public SampleBean(MeterRegistry registry) {
- this.counter = registry.counter("received.messages");
- }
-
- public void handleMessage(String message) {
- this.counter.increment();
- // handle message implementation
- }
-
- }
春靴配置内置的工具。(即:MeterBinder
实现),您可以通过配置或专用注释标记进行控制。
默认情况下,度量被导出到阿特拉斯在你的本地机器上运行。的位置Atlas服务器可以使用以下方法提供使用:
management.metrics.export.atlas.uri=http://atlas.example.com:7101/api/v1/publish
Datadog注册表将度量推送到datadoghq周期性的。将指标导出到Datadog,必须提供您的API密钥:
management.metrics.export.datadog.api-key=YOUR_KEY
还可以更改将度量发送到Datadog的间隔:
management.metrics.export.datadog.step=30s
DynatraceRegistry周期性地将度量推送到配置的URI。将指标导出到戴纳通,必须提供API令牌、设备ID和URI:
- management.metrics.export.dynatrace.api-token=YOUR_TOKEN
- management.metrics.export.dynatrace.device-id=YOUR_DEVICE_ID
- management.metrics.export.dynatrace.uri=YOUR_URI
您还可以更改将度量发送到Dynatraces的时间间隔:
management.metrics.export.dynatrace.step=30s
默认情况下,度量被导出到弹性在你的本地机器上运行。可以使用以下属性提供要使用的弹性服务器的位置:
management.metrics.export.elastic.hosts=http://elastic.example.com:8086
默认情况下,度量被导出到神经节在你的本地机器上运行。这,这个,那,那个Ganglia服务器可以使用以下方法提供要使用的主机和端口:
- management.metrics.export.ganglia.host=ganglia.example.com
- management.metrics.export.ganglia.port=9649
默认情况下,度量被导出到石墨在你的本地机器上运行。这,这个,那,那个石墨服务器可以使用以下方法提供要使用的主机和端口:
- management.metrics.export.graphite.host=graphite.example.com
- management.metrics.export.graphite.port=9004
千分尺提供缺省值HierarchicalNameMapper
它控制着维度米id的大小。映射到平面层次结构名称.
![]() |
要控制这种行为,请定义 |
- @Bean
- public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) {
- return new GraphiteMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER);
- }
默认情况下,度量被导出到流入在你的本地机器上运行。的位置流入服务器可以使用以下方法提供使用:
management.metrics.export.influx.uri=http://influx.example.com:8086
千分尺提供了一个分层映射到JMX,主要是一种廉价的、可移植的本地查看度量的方法。默认情况下,度量被导出到metrics
JMX域可以使用以下方法提供要使用的域:
management.metrics.export.jmx.domain=com.example.app.metrics
千分尺提供缺省值HierarchicalNameMapper
它控制着维度米id的大小。映射到平面层次结构名称.
![]() |
要控制这种行为,请定义 |
- @Bean
- public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) {
- return new JmxMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER);
- }
新的遗留注册中心将度量推送到新文物周期性的。将指标导出到新文物,必须提供您的API密钥和帐户ID:
- management.metrics.export.newrelic.api-key=YOUR_KEY
- management.metrics.export.newrelic.account-id=YOUR_ACCOUNT_ID
您还可以更改将度量发送到NewRelic的时间间隔:
management.metrics.export.newrelic.step=30s
普罗米修斯期望对单个应用实例进行抓取或轮询,以获得度量标准。Spring Boot提供了一个执行器端点,可在/actuator/prometheus
提出[医]擦伤普罗米修斯(Prometheus)适当的格式。
![]() |
默认情况下,端点不可用,必须公开,请参见暴露端点更多细节。 |
下面是一个例子scrape_config
添加到prometheus.yml
:
- scrape_configs:
- - job_name: 'spring'
- metrics_path: '/actuator/prometheus'
- static_configs:
- - targets: ['HOST:PORT']
SignalFx注册表将度量推送到SignalFx周期性的。将指标导出到SignalFx,必须提供访问令牌:
management.metrics.export.signalfx.access-token=YOUR_ACCESS_TOKEN
还可以更改将度量发送到SignalFx的间隔:
management.metrics.export.signalfx.step=30s
千分尺附带一个简单的内存后端,如果没有配置其他注册表,它将自动用作后备。这允许您查看在度量端点.
当您使用其他可用后端时,内存中的后端会立即禁用自己。您还可以显式禁用它:
management.metrics.export.simple.enabled=false
StatsD注册中心热切地将度量通过UDP推送给StatsD代理。默认情况下,度量被导出到StatsD探员在你的本地机器上运行。可以使用以下方法提供要使用的StatsD代理主机和端口:
- management.metrics.export.statsd.host=statsd.example.com
- management.metrics.export.statsd.port=9125
还可以将StatsD行协议更改为使用(默认为Datadog):
management.metrics.export.statsd.flavor=etsy
波前注册表将度量推送到波前周期性的。如果要将指标导出到波前直接地,必须提供您的API令牌:
management.metrics.export.wavefront.api-token=YOUR_API_TOKEN
或者,您可以使用在您的环境中设置的Wavefront Sideecar或内部代理将度量数据转发到Wavefront API主机:
management.metrics.export.wavefront.uri=proxy://localhost:2878
![]() |
如果将度量发布到Wavefront代理(如文献),主机必须位于 |
还可以更改将度量发送到Wavefront的间隔:
management.metrics.export.wavefront.step=30s
SpringBoot在适用时注册了以下核心指标:
JVM指标,报告以下指标的使用情况:
自动配置支持SpringMVC处理的请求的检测。什么时候management.metrics.web.server.auto-time-requests
是true
,此工具用于所有请求。或者,当设置为false
,您可以通过添加@Timed
请求处理方法:
- @RestController
- @Timed
- public class MyController {
-
- @GetMapping("/api/people")
- @Timed(extraTags = { "region", "us-east-1" }) @Timed(value = "all.people", longTask = true)
- public List<Person> listPeople() { ... }
-
- }
一个控制器类,用于在控制器中的每个请求处理程序上启用时间。 | |
为单个端点启用的一种方法。如果类中有它,这是不必要的,但是可以用于进一步自定义这个特定端点的定时器。 | |
一种方法 |
默认情况下,使用名称生成度量,http.server.requests
。可以通过设置management.metrics.web.server.requests-metric-name
财产。
默认情况下,与SpringMVC相关的指标被标记为以下信息:
标签 | 描述 |
---|---|
| 处理请求时抛出的任何异常的简单类名。 |
| 请求的方法(例如, |
| 请求的结果基于响应的状态代码。1XX是 |
| 响应的HTTP状态代码(例如, |
| 如果可能的话,在变量替换之前请求的URI模板(例如, |
若要自定义标记,请提供@Bean
实现WebMvcTagsProvider
.
自动配置支持由WebFlux控制器和功能处理程序处理的所有请求的检测.
默认情况下,使用名称生成度量。http.server.requests
。可以通过设置management.metrics.web.server.requests-metric-name
财产。
默认情况下,与WebFlux相关的度量使用以下信息进行标记:
标签 | 描述 |
---|---|
| 处理请求时抛出的任何异常的简单类名。 |
| 请求的方法(例如, |
| 请求的结果基于响应的状态代码。1XX是 |
| 响应的HTTP状态代码(例如, |
| 如果可能的话,在变量替换之前请求的URI模板(例如, |
若要自定义标记,请提供@Bean
实现WebFluxTagsProvider
.
弹簧启动执行器管理两个RestTemplate
和WebClient
。为此,必须注入一个自动配置的构建器,并使用它创建实例:
RestTemplateBuilder
为RestTemplate
WebClient.Builder
为WebClient
还可以手动应用负责此工具的自定义器,即MetricsRestTemplateCustomizer
和MetricsWebClientCustomizer
.
默认情况下,使用名称生成度量,http.client.requests
。可以通过设置management.metrics.web.client.requests-metric-name
财产。
默认情况下,工具化客户端生成的度量将使用以下信息进行标记:
method
,请求的方法(例如,GET
或POST
).uri
,在变量替换之前请求的URI模板(如果可能的话)(例如,/api/person/{id}
).status
,响应的HTTP状态代码(例如,200
或500
).clientName
URI的主机部分。若要自定义标记,并根据客户端的选择,可以提供@Bean
实现RestTemplateExchangeTagsProvider
或WebClientExchangeTagsProvider
。中有一些方便的静态函数。RestTemplateExchangeTags
和WebClientExchangeTags
.
自动配置启用所有可用的仪表。Cache
s在启动时以指标为前缀cache
。对于一组基本的度量,缓存检测是标准化的。此外,缓存特定的指标也是可用的.
支持以下缓存库:
指标由缓存的名称和CacheManager
它是从bean名称派生的。
![]() |
只有启动时可用的缓存才绑定到注册表。对于在启动阶段后动态创建或以编程方式创建的缓存,需要显式注册.一个 |
自动配置启用所有可用的仪表。DataSource
对象具有名为jdbc
。数据源检测结果是表示池中当前活动的、最大允许的和最小允许的连接的量规。这些量规中的每一个都有一个前缀为jdbc
.
度量标准也被标记为DataSource
根据bean名称计算。
![]() |
默认情况下,SpringBoot为所有受支持的数据源提供元数据;您可以添加其他 |
另外,Hikari特有的度量也公开了一个hikaricp
前缀。每个度量都由池的名称标记(可以用spring.datasource.name
).
自动配置支持所有可用Hibernate的检测。EntityManagerFactory
实例,这些实例使用名为hibernate
.
度量标准也被标记为EntityManagerFactory
它是从bean名称派生的。
要启用统计信息,标准的jpa属性hibernate.generate_statistics
必须设置为true
。您可以在自动配置的EntityManagerFactory
如以下示例所示:
spring.jpa.properties.hibernate.generate_statistics=true
自动配置将启用所有可用的RabbitMQ连接工厂的仪表,其度量名为rabbitmq
.
若要注册自定义度量,请插入MeterRegistry
在您的组件中,如下面的示例所示:
- class Dictionary {
-
- private final List<String> words = new CopyOnWriteArrayList<>();
-
- Dictionary(MeterRegistry registry) {
- registry.gaugeCollectionSize("dictionary.size", Tags.empty(), this.words);
- }
-
- // …
-
- }
如果您发现在组件或应用程序之间反复测试一组度量,则可以将此套件封装在MeterBinder
执行。默认情况下,所有MeterBinder
bean将自动绑定到Spring管理的MeterRegistry
.
如果需要将自定义应用于特定的Meter
实例可以使用io.micrometer.core.instrument.config.MeterFilter
接口。默认情况下,所有MeterFilter
豆子将自动应用于千分尺。MeterRegistry.Config
.
例如,如果要重命名mytag.region
标记到mytag.area
开始的所有仪表IDcom.example
,您可以这样做:
- @Bean
- public MeterFilter renameRegionTagMeterFilter() {
- return MeterFilter.renameTag("com.example", "mytag.region", "mytag.area");
- }
常见的标签通常用于操作环境中的维度向下钻取,如主机、实例、区域、堆栈等。公用标记应用于所有仪表,可以配置如下示例所示:
- management.metrics.tags.region=us-east-1
- management.metrics.tags.stack=prod
上面的示例添加了region
和stack
标记到所有值为us-east-1
和prod
分别。
![]() |
如果使用Graphite,公共标记的顺序非常重要。由于使用这种方法无法保证公共标记的顺序,因此建议Graphite用户定义自定义 |
除了……之外MeterFilter
bean,也可以使用属性在每米的基础上应用有限的定制集。每米自定义适用于以给定名称开头的所有仪表ID.例如,以下内容将禁用任何具有ID的仪表。example.remote
management.metrics.enable.example.remote=false
以下属性允许每米定制:
表56.1.每米定制
财产 | 描述 |
---|---|
| 是否拒绝仪表发射任何指标。 |
| 是否发布适合于计算聚合(跨维度)百分位数近似的直方图。 |
| 发布应用程序中计算的百分位数 |
| 使用SLA定义的桶发布累积直方图。 |
有关背后概念的更多详细信息percentiles-histogram
, percentiles
和sla
参考“直方图和百分位数”部分千分尺的文件。
Spring Boot提供了一个metrics
可用于诊断性地检查应用程序收集的指标的端点。默认情况下,端点不可用,必须公开,请参见暴露端点更多细节。
导航到/actuator/metrics
显示可用仪表名称的列表。您可以通过提供一个选择器的名称来向下查看有关特定仪表的信息。/actuator/metrics/jvm.memory.max
.
![]() |
您在这里使用的名称应该与代码中使用的名称相匹配,而不是在命名之后使用的名称。换句话说,如果 |
您还可以添加任意数量的tag=KEY:VALUE
将参数查询到URL的末尾,以便在仪表上按尺寸向下钻取。/actuator/metrics/jvm.memory.max?tag=area:nonheap
.
![]() |
报告的测量结果是相加与表名匹配的所有仪表的统计数据以及已应用的任何标记。因此,在上面的示例中,返回的“value”统计数据是堆中“Code Cache”、“压缩类空间”和“Metaspace”区域的最大内存足迹的总和。如果您只想查看“Metaspace”的最大大小,可以添加一个额外的 |
SpringSecurity运行后,SpringBootActuator有一个灵活的审计框架来发布事件(默认情况下,“身份验证成功”、“失败”和“访问拒绝”异常)。此特性对于报告和实现基于身份验证失败的锁定策略非常有用。若要自定义已发布的安全事件,可以提供您自己的AbstractAuthenticationAuditListener
和AbstractAuthorizationAuditListener
.
您还可以将审计服务用于您自己的业务事件。要做到这一点,要么注入现有的AuditEventRepository
在您自己的组件中直接使用该组件,或者发布AuditApplicationEvent
与春天ApplicationEventPublisher
(通过实施ApplicationEventPublisherAware
).
所有HTTP请求都自动启用跟踪。您可以查看httptrace
终结点并获取关于最后100个请求-响应交换的基本信息。
若要自定义每个跟踪中包含的项,请使用management.trace.http.include
配置属性。对于高级定制,请考虑注册自己的HttpExchangeTracer
执行。
默认情况下,InMemoryHttpTraceRepository
它存储最后100个请求响应交换的跟踪。如果需要扩展容量,可以定义您自己的InMemoryHttpTraceRepository
豆子您还可以创建自己的备选方案。HttpTraceRepository
执行。
在.。spring-boot
模块中,您可以找到两个类来创建通常对进程监视有用的文件:
ApplicationPidFileWriter
创建包含应用程序PID的文件(默认情况下,在应用程序目录中,文件名为application.pid
).WebServerPortFileWriter
创建一个文件(或多个文件),其中包含正在运行的web服务器的端口(默认情况下,在应用程序目录中,文件名为application.port
).默认情况下,不会激活这些写入器,但可以启用:
在.。META-INF/spring.factories
文件,您可以激活写入PID文件的监听器,如下面的示例所示:
- org.springframework.context.ApplicationListener=\
- org.springframework.boot.context.ApplicationPidFileWriter,\
- org.springframework.boot.web.context.WebServerPortFileWriter
还可以通过调用SpringApplication.addListeners(…)
方法并传递适当的Writer
对象。此方法还允许您自定义Writer
构造函数
SpringBoot的执行器模块包括在部署到兼容的CloudFoundry实例时激活的额外支持。这,这个,那,那个/cloudfoundryapplication
PATH为所有用户提供了另一种安全路由。@Endpoint
豆子
扩展支持使CloudFoundryManagementUI(例如可以用来查看已部署应用程序的Web应用程序)可以通过SpringBoot执行器信息得到增强。例如,应用程序状态页可能包含完整的健康信息,而不是典型的“运行”或“停止”状态。
![]() |
这,这个,那,那个 |
如果要完全禁用/cloudfoundryapplication
端点,可以将以下设置添加到application.properties
档案:
应用特性。
management.cloudfoundry.enabled=false
默认情况下,/cloudfoundryapplication
端点对各种CloudFoundry服务进行SSL调用。如果您的CloudFoundryUAA或CloudController服务使用自签名证书,则需要设置以下属性:
应用特性。
management.cloudfoundry.skip-ssl-validation=true
如果服务器的上下文路径已配置为/
,CloudFoundry端点将无法在应用程序的根目录上使用。例如,如果server.servlet.context-path=/app
,CloudFoundry端点将在/app/cloudfoundryapplication/*
.
如果您期望CloudFoundry端点始终可用在/cloudfoundryapplication/*
无论服务器的上下文路径如何,您都需要在应用程序中显式地配置它。根据使用中的Web服务器,配置将有所不同。对于Tomcat,可以添加以下配置:
@Bean public TomcatServletWebServerFactory servletWebServerFactory() { return new TomcatServletWebServerFactory() { @Override protected void prepareContext(Host host, ServletContextInitializer[] initializers) { super.prepareContext(host, initializers); StandardContext child = new StandardContext(); child.addLifecycleListener(new Tomcat.FixContextListener()); child.setPath("/cloudfoundryapplication"); ServletContainerInitializer initializer = getServletContextInitializer( getContextPath()); child.addServletContainerInitializer(initializer, Collections.emptySet()); child.setCrossContext(true); host.addChild(child); } }; } private ServletContainerInitializer getServletContextInitializer(String contextPath) { return (c, context) -> { Servlet servlet = new GenericServlet() { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { ServletContext context = req.getServletContext() .getContext(contextPath); context.getRequestDispatcher("/cloudfoundryapplication").forward(req, res); } }; context.addServlet("cloudfoundry", servlet).addMapping("/*"); }; }
如果您想探索本章中讨论的一些概念,您可以看看执行器。样本应用。您还可能希望阅读有关绘图工具的内容,例如石墨.
否则,您可以继续阅读有关“部署选项”或者跳出一些关于SpringBoot的深度信息构建工具插件.
SpringBoot的软包装选项在部署应用程序时提供了大量的选择。您可以将SpringBoot应用程序部署到各种云平台、容器映像(如Docker)或虚拟/真实机器上。
本节介绍了一些更常见的部署场景。
SpringBoot的可执行JAR已经为大多数流行的云PaaS(平台即服务)提供商做好了准备。这些提供者倾向于要求您“携带您自己的容器”。它们管理应用程序进程(而不是特定的Java应用程序),因此它们需要一个适配的中间层。你的向云的正在运行的进程的概念。
两个流行的云提供商Heroku和CloudFoundry采用了一种“buildpack”方法。构建包将部署的代码封装在所需的任何内容中。启动你的申请。它可能是一个JDK和一个调用java
、嵌入式Web服务器或成熟的应用服务器。构建包是可插拔的,但理想情况下,您应该能够尽可能少地对其进行自定义。这减少了不受您控制的功能的占用。它最大限度地减少了开发环境和生产环境之间的差异。
理想情况下,您的应用程序,如SpringBoot可执行JAR,包含了在其中打包运行所需的一切。
在本节中,我们将讨论如何获得我们开发的简单应用程序在“入门”部分启动并在云中运行。
云Foundry提供默认的构建包,如果没有指定其他的buildpack,这些包就会发挥作用。云铸造Javabuildpack对Spring应用程序有很好的支持,包括SpringBoot。您可以部署独立的可执行的jar应用程序以及传统的.war
打包应用程序。
一旦构建了应用程序(例如,通过使用mvn clean package
)安装cf
命令行工具,使用cf push
命令替换编译后的路径。.jar
。一定要用你的cf
命令行客户端在推送申请之前。下面的行使用cf push
命令部署应用程序:
$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar
![]() |
在前面的示例中,我们将 |
见cf push
文献资料寻找更多的选择。如果有云铸造厂manifest.yml
文件存在于同一目录中,则考虑。
在这一点上,cf
开始上载应用程序,生成类似于以下示例的输出:
Uploading acloudyspringtime... OK Preparing to start acloudyspringtime... OK -----> Downloaded app package (8.9M) -----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e -----> Downloading Open Jdk JRE 1.8.0_121 from https://java-buildpack.cloudfoundry.org/openjdk/trusty/x86_64/openjdk-1.8.0_121.tar.gz (found in cache) Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s) -----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache) Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K -----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache) Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s) -----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache) Checking status of app 'acloudyspringtime'... 0 of 1 instances running (1 starting) ... 0 of 1 instances running (1 starting) ... 0 of 1 instances running (1 starting) ... 1 of 1 instances running (1 running) App started
祝贺你!应用程序现在正在运行!
一旦应用程序处于活动状态,就可以使用cf apps
命令,如以下示例所示:
- $ cf apps
- Getting applications in ...
- OK
-
- name requested state instances memory disk urls
- ...
- acloudyspringtime started 1/1 512M 1G acloudyspringtime.cfapps.io
- ...
一旦CloudFoundry确认您的应用程序已经部署,您就可以在给定的URI中找到应用程序。在前面的示例中,您可以在http://acloudyspringtime.cfapps.io/
.
默认情况下,有关正在运行的应用程序的元数据以及服务连接信息将作为环境变量公开给应用程序(例如:$VCAP_SERVICES
)这个架构决定是由于CloudFoundry的Polyglot(任何语言和平台都可以作为构建包来支持)。过程范围内的环境变量与语言无关。
环境变量并不总是最简单的API,因此SpringBoot会自动提取它们,并将数据扁平化成可以通过Spring的属性访问的属性。Environment
抽象,如以下示例所示:
- @Component
- class MyBean implements EnvironmentAware {
-
- private String instanceId;
-
- @Override
- public void setEnvironment(Environment environment) {
- this.instanceId = environment.getProperty("vcap.application.instance_id");
- }
-
- // ...
-
- }
所有云铸造属性都以前缀vcap
。你可以用vcap
属性访问应用程序信息(例如应用程序的公共URL)和服务信息(例如数据库凭据)。见“CloudFoundryVcapEnvironment-PostProcessor”有关详细信息的Javadoc。
![]() |
这,这个,那,那个弹簧云连接器项目更适合于配置DataSource等任务。Spring Boot包括自动配置支持和 |
Heroku是另一个流行的PaaS平台。若要自定义Heroku构建,请提供Procfile
,它提供了部署应用程序所需的咒语。Heroku分配port
使Java应用程序使用并确保到外部URI的路由工作。
必须将应用程序配置为侦听正确的端口。下面的示例显示Procfile
对于初学者REST应用程序:
web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar
春靴-D
作为从Spring访问的属性可用的参数Environment
举个例子。这,这个,那,那个server.port
Configuration属性被输入到嵌入的Tomcat、Jetty或Undertu实例,然后在启动时使用端口。这,这个,那,那个$PORT
环境变量由Heroku PaaS分配给我们。
这应该是你需要的一切。Heroku部署最常见的部署工作流是git push
生产代码,如以下示例所示:
$ git push heroku master Initializing repository, done. Counting objects: 95, done. Delta compression using up to 8 threads. 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: https://repo.spring.io/... Downloaded: https://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
您的应用程序现在应该在Heroku上启动并运行。
OpenShift是Kubernetes容器编排平台的RedHat公共(和企业)扩展。与Kubernetes类似,OpenShift有许多安装基于SpringBoot的应用程序的选项。
OpenShift有许多描述如何部署SpringBoot应用程序的资源,包括:
AmazonWebServices提供多种方法来安装基于SpringBoot的应用程序,或者作为传统的Web应用程序(WAR)安装,或者作为带有嵌入式Web服务器的可执行JAR文件安装。备选方案包括:
每一种都有不同的特点和定价模式。在本文档中,我们只描述了最简单的选项:AWS弹性豆柄。
如该官员所述弹性豆柄Java指南,部署Java应用程序有两个主要选项。您可以使用“Tomcat平台”或“JavaSE平台”。
使用Tomcat平台
此选项适用于生成WAR文件的SpringBoot项目。不需要特殊配置。你只需要遵循官方指南就行了。
使用JavaSE平台
此选项适用于生成JAR文件并运行嵌入式Web容器的SpringBoot项目。弹性Bean秸秆环境在端口80上运行一个nginx实例来代理实际应用程序,运行在端口5000上。若要配置它,请将以下行添加到您的application.properties
档案:
server.port=5000
![]() |
默认情况下,ElasticBean秸秆会上传源并在AWS中编译它们。但是,最好还是上传二进制文件。为此,请将类似于以下内容的行添加到您的 |
![]() |
默认情况下,弹性豆柄环境是负载平衡的。负载均衡器的成本很高。为了避免这种成本,请将环境类型设置为“单个实例”,如Amazon文档。还可以使用CLI和以下命令创建单个实例环境: |
这是实现AWS的最简单的方法之一,但是还有更多的事情要讨论,比如如何将ElasticBean秸秆集成到任何CI/CD工具中,使用ElasticBeansarMaven插件而不是CLI,等等。有一个博客帖子详细介绍这些主题。
箱式保险丝工作方式是将SpringBoot、可执行JAR或WAR转换成一个最小的VM映像,可以在VirtualBox或AWS上不作改动地部署。Box引信为SpringBoot提供了深度集成,并使用SpringBoot配置文件中的信息自动配置端口和健康检查URL。Box引信对它生成的图像以及它提供的所有资源(实例、安全组、弹性负载平衡器等)都利用了这些信息。
一旦创建了一个BOXFUSE帐户,将其连接到AWS帐户,安装BoxFUSE客户端的最新版本,并确保应用程序已由Maven或Gradle构建(例如,使用mvn clean package
),您可以使用类似于以下命令的命令将SpringBoot应用程序部署到AWS:
$ boxfuse run myapp-1.0.jar -env=prod
见boxfuse run
文献资料寻找更多的选择。如果有一个boxfuse.conf
文件存在于当前目录中,则考虑。
![]() |
默认情况下,BoxFUSE激活一个名为Spring的概要文件 |
在这一点上,boxfuse
为您的应用程序创建一个映像,上传它,并在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/
您的应用程序现在应该在AWS上启动并运行。
请看博客上的文章在EC2上部署SpringBoot应用程序以及BoxfueSpringBoot集成文档要开始使用Maven构建来运行这个应用程序。
GoogleCloud有几个选项可用于启动SpringBoot应用程序。最容易开始使用的可能是AppEngine,但您也可以找到在容器中运行SpringBoot的方法,或者在带有Compute引擎的虚拟机上运行SpringBoot。
要在AppEngine中运行,您可以首先在UI中创建一个项目,该项目为您设置唯一标识符,还可以设置HTTP路由。将Java应用程序添加到项目中,并将其保留为空,然后使用GoogleCloudSDK要将SpringBoot应用程序从命令行或CI构建中插入到该槽中,请执行以下操作。
应用引擎标准要求您使用WAR包装。跟随这些步骤将AppEngine标准应用程序部署到GoogleCloud。
或者,AppEngine Flex要求您创建一个app.yaml
文件来描述应用程序所需的资源。通常,你把这个文件放进src/main/appengine
,它应该类似于以下文件:
service: default runtime: java env: flex runtime_config: jdk: openjdk8 handlers: - url: /.* script: this field is required, but ignored 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
(如果需要先进行身份验证,则生成失败)。
除了运行SpringBoot应用程序之外,还可以使用java -jar
,也可以为Unix系统制作完全可执行的应用程序。完全可执行的JAR可以像任何其他可执行的二进制文件一样执行,也可以是在init.d
或systemd
。这使得在常见的生产环境中安装和管理SpringBoot应用程序变得非常容易。
![]() | 谨慎 |
---|---|
完全可执行的JAR通过在文件前面嵌入一个额外的脚本来工作。目前,有些工具不接受这种格式,因此您可能并不总是能够使用这种技术。例如 |
若要使用Maven创建一个“完全可执行”的JAR,请使用以下插件配置:
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <executable>true</executable>
- </configuration>
- </plugin>
下面的示例显示了等效的Gradle配置:
- bootJar {
- launchScript()
- }
然后,您可以通过键入./my-application.jar
(在哪里my-application
是你的艺术品的名字)。包含JAR的目录用作应用程序的工作目录。
默认脚本支持大多数Linux发行版,并在CentOS和Ubuntu上进行测试。其他平台,如OSX和FreeBSD,需要使用自定义embeddedLaunchScript
.
可以轻松地以unix/linux服务的形式启动SpringBoot应用程序,方法是init.d
或systemd
.
init.d
服务(系统五)如果您将SpringBoot的Maven或Gradle插件配置为生成一个完全可执行JAR,并且您不使用自定义embeddedLaunchScript
,您的应用程序可以用作init.d
服务。为此,将JAR符号链接到init.d
支持标准start
, stop
, restart
,和status
命令。
该脚本支持以下特性:
/var/run/<appname>/<appname>.pid
/var/log/<appname>.log
假设您已经安装了SpringBoot应用程序/var/myapp
,将SpringBoot应用程序安装为init.d
服务,创建一个符号链接,如下所示:
$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp
安装完毕后,您可以按照通常的方式启动和停止服务。例如,在基于Debian的系统上,可以使用以下命令启动它:
$ service myapp start
![]() |
如果应用程序启动失败,请检查写入的日志文件。 |
还可以使用标准操作系统工具将应用程序标记为自动启动。例如,在Debian上,可以使用以下命令:
$ update-rc.d myapp defaults <priority>
确保init.d
服务
![]() |
下面是一组关于如何保护作为init.d服务运行的SpringBoot应用程序的指导方针。它并不打算是一份详尽的清单,列出为强化应用程序和运行应用程序的环境而应该做的所有事情。 |
当作为root执行时,就像在使用root启动init.d服务时一样,默认的可执行脚本以拥有JAR文件的用户的身份运行应用程序。您不应该将SpringBoot应用程序作为root
因此,应用程序的JAR文件永远不应该属于root。相反,创建一个特定的用户来运行您的应用程序并使用chown
要使它成为JAR文件的所有者,如下面的示例所示:
$ chown bootapp:bootapp your-app.jar
在这种情况下,默认的可执行脚本以bootapp
用户。
![]() |
为了减少应用程序的用户帐户被破坏的可能性,您应该考虑阻止它使用登录shell。例如,可以将帐户的shell设置为 |
您还应该采取措施防止修改应用程序的JAR文件。首先,配置其权限,使其不能被写入,并且只能由其所有者读取或执行,如下面的示例所示:
$ chmod 500 your-app.jar
其次,如果您的应用程序或运行它的帐户被破坏,您还应该采取措施限制损坏。如果攻击者确实获得了访问权限,他们可以使JAR文件可写并更改其内容。防止这种情况的一种方法是通过使用chattr
,如以下示例所示:
$ sudo chattr +i your-app.jar
这将防止任何用户(包括root用户)修改JAR。
如果根用户用于控制应用程序的服务,则用.conf
档案若要自定义其启动,请将.conf
文件由根用户读取和计算。应当相应地加以担保。使用chmod
这样,该文件只能由所有者读取并使用。chown
要使所有者具有根,如下面的示例所示:
- $ chmod 400 your-app.conf
- $ sudo chown root:root your-app.conf
systemd
服务systemd
是SystemV init系统的继承者,现在许多现代Linux发行版都在使用它。虽然您可以继续使用init.d
脚本systemd
,也可以通过以下方式启动SpringBoot应用程序systemd
“服务”脚本。
假设您已经安装了SpringBoot应用程序/var/myapp
,将SpringBoot应用程序安装为systemd
服务,创建一个名为myapp.service
把它放进去/etc/systemd/system
目录。以下脚本提供了一个示例:
- [Unit]
- Description=myapp
- After=syslog.target
-
- [Service]
- User=myapp
- ExecStart=/var/myapp/myapp.jar
- SuccessExitStatus=143
-
- [Install]
- WantedBy=multi-user.target
![]() | 重要 |
---|---|
请记住更改 |
![]() |
这,这个,那,那个 |
注意,与作为init.d
服务,运行应用程序的用户、PID文件和控制台日志文件由systemd
因此,必须通过在“service”脚本中使用适当的字段来配置它本身。咨询服务单元配置手册页更多细节。
若要在系统启动时将应用程序标记为自动启动,请使用以下命令:
$ systemctl enable myapp.service
请参阅man systemctl
更多细节。
由Maven或Gradle插件编写的默认嵌入式启动脚本可以通过多种方式进行定制。对于大多数人来说,使用默认脚本和一些自定义通常就足够了。如果发现无法自定义所需的内容,请使用embeddedLaunchScript
选项可以完全写入您自己的文件。
在编写开始脚本时自定义它
当开始脚本被写入JAR文件时,定制它的元素通常是有意义的。例如,init.d脚本可以提供“描述”。因为您预先知道了描述(并且它不需要更改),所以您最好在JAR生成时提供它。
若要自定义编写的元素,请使用embeddedLaunchScriptProperties
选择SpringBootMaven或Gradle插件。
默认脚本支持以下属性替换:
名字,姓名 | 描述 | 分级违约 | Maven缺省 |
---|---|---|---|
| 脚本模式。 |
|
|
| 这,这个,那,那个 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 单行版本 |
|
|
|
|
|
|
|
|
|
| 的默认值 | 包含罐子的文件夹 | 包含罐子的文件夹 |
| 引用默认启动脚本中应该内联的文件脚本。这可用于设置环境变量,如 | ||
| 默认值 | ||
| 默认值 | ||
| 默认值 | ||
| 中的PID文件名的默认值。 | ||
| 是否 |
|
|
| 默认值 | 60 | 60 |
在脚本运行时自定义脚本
用于需要自定义的脚本项。后已经编写了JAR,您可以使用环境变量或配置文件.
默认脚本支持下列环境属性:
变量 | 描述 |
---|---|
| 操作的“模式”。默认情况取决于JAR的构建方式,但通常是 |
| 是否 |
| PID文件夹的根名称( |
| 要在其中放置日志文件的文件夹的名称( |
| 要从其中读取.conf文件的文件夹的名称(默认情况下,该文件夹与jar-file相同)。 |
| 控件中日志文件的名称。 |
| 应用程序的名称。如果JAR是从符号链接运行的,脚本就会猜测应用程序的名称。如果它不是符号链接,或者您希望显式设置应用程序名称,这可能是有用的。 |
| 传递给程序的参数(SpringBoot应用程序)。 |
| 的位置 |
| 在JVM启动时传递给它的选项。 |
| JAR文件的显式位置,以防脚本被用来启动一个实际上没有嵌入的JAR。 |
| 如果不为空,则设置 |
| 在强制关闭之前停止应用程序时等待的时间(以秒为单位)( |
![]() |
这,这个,那,那个 |
除了.JARFILE
和APP_NAME
,则上一节中列出的设置可以通过使用.conf
档案。该文件应位于JAR文件的旁边,并且具有相同的名称,但后缀为.conf
而不是.jar
。例如,一个名为/var/myapp/myapp.jar
使用名为/var/myapp/myapp.conf
,如以下示例所示:
myapp.conf.
- JAVA_OPTS=-Xmx1024M
- LOG_FOLDER=/custom/log/folder
![]() |
如果不喜欢将配置文件放在JAR文件旁边,则可以设置 |
若要了解如何适当保护此文件,请参见确保init.d服务安全的指南.
可以将SpringBoot应用程序作为Windows服务启动,方法是winsw
.
A(单独维护样本)描述如何为SpringBoot应用程序创建Windows服务。
检查一下云铸造, 赫鲁库, OpenShift,和箱式保险丝有关PaaS可以提供的功能种类的更多信息,请参见网站。这些只是最流行的JavaPaaS供应商中的四个。由于SpringBoot非常适合基于云的部署,所以您也可以自由地考虑其他提供者。
下一节继续讨论弹簧启动CLI或者你可以跳到前面去读构建工具插件.
SpringBootCLI是一个命令行工具,如果您想要快速开发Spring应用程序,可以使用它。它允许您运行Groovy脚本,这意味着您有一个熟悉的类似Java的语法,而没有太多的样板代码。您还可以引导一个新项目或为它编写您自己的命令。
使用SDKMAN可以手动安装SpringBootCLI(命令行接口)!(SDK管理器),如果您是OSX用户,则可以使用HomeBREW或MacPorts。看见10.2节,“安装SpringBoot CLI”在“入门”一节中获得全面的安装说明。
一旦安装了CLI,就可以通过键入spring
并在命令行按Enter。如果你跑spring
在没有任何参数的情况下,将显示一个简单的帮助屏幕,如下所示:
- $ 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
你可以打字spring help
若要获取有关任何受支持命令的更多详细信息,请参见以下示例:
- $ 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 Quiet logging
- -v, --verbose Verbose logging of dependency
- resolution
- --watch Watch the specified file for changes

这,这个,那,那个version
命令提供了一种快速检查使用的SpringBoot版本的方法,如下所示:
- $ spring version
- Spring CLI v2.1.0.BUILD-SNAPSHOT
方法可以编译和运行Groovy源代码。run
命令。SpringBootCLI是完全独立的,所以您不需要安装任何外部Groovy。
下面的示例显示了用Groovy编写的“Hello World”Web应用程序:
你好,太棒了。
- @RestController
- class WebApplication {
-
- @RequestMapping("/")
- String home() {
- "Hello World!"
- }
-
- }
要编译和运行应用程序,输入以下命令:
$ spring run hello.groovy
若要向应用程序传递命令行参数,请使用--
若要将命令与“Spring”命令参数分离,请参见以下示例:
$ spring run hello.groovy -- --server.port=9000
要设置jvm命令行参数,可以使用JAVA_OPTS
环境变量,如以下示例所示:
$ JAVA_OPTS=-Xmx1024m spring run hello.groovy
![]() |
设置时 |
标准Groovy包括@Grab
注释,它允许您声明对第三方库的依赖关系。这个有用的技术可以让Groovy以与Maven或Gradle相同的方式下载JAR,但不需要使用构建工具。
SpringBoot进一步扩展了这一技术,并试图根据您的代码推断出要“抓取”哪些库。例如,由于WebApplication
前面显示的代码使用@RestController
注解,SpringBoot抓住了“Tomcat”和“SpringMVC”。
以下项目用作“抓取提示”:
项目 | 抓取 |
---|---|
| JDBC应用 |
| JMS应用 |
| 缓存抽象。 |
| JUnit |
| 拉比·MQ |
延展 | 史波克测试。 |
| 弹簧批。 |
| 弹簧集成。 |
| SpringMVC+嵌入式Tomcat。 |
| 春季保安。 |
| 春季事务管理 |
![]() |
见 |
SpringBoot扩展了Groovy的标准@Grab
通过允许您在没有组或版本的情况下指定依赖项(例如,@Grab('freemarker')
)这样做可以参考SpringBoot的默认依赖元数据来推断工件的组和版本。
![]() |
默认元数据绑定到您使用的CLI版本。只有当您移动到CLI的新版本时,它才会更改,这将使您控制依赖项的版本何时会更改。显示默认元数据中包含的依赖项及其版本的表可以在附录. |
为了帮助缩小Groovy代码的大小,以下几个import
语句自动包括在内。注意前面的示例如何引用@Component
, @RestController
,和@RequestMapping
不需要使用完全限定的名称或import
陈述。
![]() |
许多Spring注释无需使用 |
与等效的Java应用程序不同,不需要包含public static void main(String[] args)
方法与您的Groovy
剧本。一个SpringApplication
自动创建,编译后的代码将充当source
.
默认情况下,cli使用spring-boot-dependencies
解析时@Grab
依赖关系。可以使用@DependencyManagementBom
注释注释的值应该指定坐标(groupId:artifactId:version
)一个或多个Maven Boms。
例如,考虑以下声明:
@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
在您的应用程序中最多一次。依赖管理的一个有用来源(它是SpringBoot的依赖管理的超集)是弹簧IO平台,您可以将其包含在以下行中:
@DependencyManagementBom('io.spring.platform:platform-bom:1.1.2.RELEASE')
您可以在接受文件输入的所有命令中使用“shell globing”。这样做可以让您使用来自单个目录的多个文件,如下面的示例所示:
$ spring run *.groovy
您可以使用jar
命令将应用程序打包到一个自包含的可执行JAR文件中,如下面的示例所示:
$ spring jar my-app.jar *.groovy
生成的JAR包含通过编译应用程序和应用程序的所有依赖项生成的类,这样就可以使用java -jar
。JAR文件还包含来自应用程序类路径的条目。可以向JAR添加和移除显式路径,方法是--include
和--exclude
。两者都是逗号分隔的,并且都接受前缀,以“+”和“-”的形式表示应该从默认值中删除它们。默认包含如下:
public/**, resources/**, static/**, templates/**, META-INF/**, *
默认排除如下:
.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy
类型spring help jar
在命令行上获取更多信息。
这,这个,那,那个init
命令可以通过以下方式创建一个新项目:start.spring.io而不离开shell,如下面的示例所示:
- $ spring init --dependencies=web,data-jpa my-project
- Using service at https://start.spring.io
- Project extracted to '/Users/developer/example/my-project'
前面的示例创建了my-project
目录中包含一个基于Maven的项目,该项目使用spring-boot-starter-web
和spring-boot-starter-data-jpa
。方法可以列出服务的功能。--list
标志,如以下示例所示:
$ 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) ...
这,这个,那,那个init
命令支持许多选项。见help
输出更多细节。例如,下面的命令创建一个使用Java 8和war
包装:
- $ 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'
SpringBoot包括用于Bash和zsh shell的命令行完成脚本。如果您不使用这些shell(可能您是Windows用户),则可以使用shell
命令启动集成shell,如以下示例所示:
- $ spring shell
- Spring Boot (v2.1.0.BUILD-SNAPSHOT)
- Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit.
在嵌入的shell中,可以直接运行其他命令:
- $ version
- Spring CLI v2.1.0.BUILD-SNAPSHOT
嵌入式外壳支持ANSI颜色输出以及tab
完成。如果需要运行本机命令,可以使用!
前缀。若要退出嵌入的外壳,请按ctrl-c
.
可以使用install
命令。该命令以格式接受一组或多组工件坐标。group:artifact:version
,如以下示例所示:
$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE
除了安装您所提供的坐标所标识的工件之外,还安装了所有工件的依赖关系。
若要卸载依赖项,请使用uninstall
命令。就像install
命令中,它接受一组或多组工件坐标,格式为group:artifact:version
,如以下示例所示:
$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE
它卸载您提供的坐标和它们的依赖项所标识的工件。
若要卸载所有其他依赖项,可以使用--all
选项,如以下示例所示:
$ spring uninstall --all
SpringFramework4.0对beans{}
“DSL”(借用自砂砾),并且可以使用相同的格式将bean定义嵌入到Groovy应用程序脚本中。这有时是包含中间件声明等外部特性的好方法,如下面的示例所示:
@Configuration class Application implements CommandLineRunner { @Autowired SharedService service @Override void run(String... args) { println service.message } } import my.company.SharedService beans { service(SharedService) { message = "Hello World" } }
您可以将类声明与beans{}
在同一个文件中,只要它们停留在顶层,或者,如果您愿意,可以将Beans DSL放在一个单独的文件中。
settings.xml
SpringBootCLI使用Aether(Maven的依赖解析引擎)来解决依赖关系。CLI使用了~/.m2/settings.xml
配置乙醚。CLI遵守下列配置设置:
剖面图
看见Maven设置文档以获取更多信息。
有一些示例groovy脚本可以从GitHub存储库中获得,您可以使用它来尝试SpringBootCLI。也有广泛的Javadoc贯穿于源代码.
如果您发现您已经达到了CLI工具的极限,那么您可能希望将您的应用程序转换为一个完整的Gradle或Maven构建的“Groovy项目”。下一节将介绍SpringBoot的“构建工具插件,可以与Gradle或Maven一起使用。
SpringBoot为Maven和Gradle提供了构建工具插件。插件提供了多种特性,包括可执行JAR的打包。本节提供了更多关于这两个插件的详细信息,以及在需要扩展不受支持的构建系统时提供的一些帮助。如果你才刚开始,你可能想读“第13章,构建系统“从”第三部分,“使用Spring Boot”“第一节。
这,这个,那,那个Spring Boot Maven插件在Maven中提供SpringBoot支持,允许您打包可执行的JAR或WAR存档,并运行应用程序“就地”。要使用它,必须使用Maven 3.2(或更高版本)。
![]() |
见Spring Boot Maven插件站点获得完整的插件文档。 |
若要使用SpringBootMaven插件,请在plugins
你的部分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>
- <!-- ... -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>2.1.0.BUILD-SNAPSHOT</version>
- <executions>
- <execution>
- <goals>
- <goal>repackage</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </project>

前面的配置重新打包了一个JAR或WAR,该JAR或WAR是在package
Maven生命周期的阶段。下面的示例既显示了重新打包的JAR,也显示了target
目录:
- $ mvn package
- $ 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
如果使用里程碑或快照发行版,还需要添加适当的pluginRepository
元素,如以下清单所示:
- <pluginRepositories>
- <pluginRepository>
- <id>spring-snapshots</id>
- <url>https://repo.spring.io/snapshot</url>
- </pluginRepository>
- <pluginRepository>
- <id>spring-milestones</id>
- <url>https://repo.spring.io/milestone</url>
- </pluginRepository>
- </pluginRepositories>
一次spring-boot-maven-plugin
已经包含在您的pom.xml
,它会自动尝试重写档案,以便通过使用spring-boot:repackage
进球。您应该将您的项目配置为构建JAR或WAR(视情况而定),方法是使用通常的packaging
元素,如以下示例所示:
- <?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>
在package
相位。要启动的主类可以通过使用配置选项或添加Main-Class
属性以通常的方式添加到清单。如果未指定主类,则插件将搜索具有public static void main(String[] args)
方法。
要构建和运行项目工件,可以键入以下内容:
- $ mvn package
- $ java -jar target/mymodule-0.0.1-SNAPSHOT.jar
要构建一个既可执行又可部署到外部容器中的WAR文件,您需要将嵌入的容器依赖项标记为“提供”,如下面的示例所示:
- <?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>

![]() |
见“第91.1节,“创建可部署的战争文件”“有关如何创建可部署的WAR文件的更多详细信息,请参见。 |
高级配置选项和示例可在插件信息页面.
SpringBootGradle插件在Gradle中提供了SpringBoot支持,允许您打包可执行的JAR或WAR存档,运行SpringBoot应用程序,并使用由spring-boot-dependencies
。它需要Gradle 4.4或更高版本。请参阅插件的文档以了解更多信息:
SpringBootAntLib模块为ApacheAnt提供了基本的SpringBoot支持。您可以使用该模块创建可执行的JAR。要使用该模块,您需要声明一个额外的spring-boot
命名空间中的build.xml
,如以下示例所示:
- <project xmlns:ivy="antlib:org.apache.ivy.ant"
- xmlns:spring-boot="antlib:org.springframework.boot.ant"
- name="myapp" default="build">
- ...
- </project>
您需要记住使用-lib
选项,如以下示例所示:
$ ant -lib <folder containing spring-boot-antlib-2.1.0.BUILD-SNAPSHOT.jar>
![]() |
“使用SpringBoot”部分包含了一个更完整的示例使用ApacheAnt |
曾经spring-boot-antlib
命名空间已声明,可使用下列附加任务:
spring-boot:exejar
您可以使用exejar
创建SpringBoot可执行JAR的任务。任务支持以下属性:
属性 | 描述 | 所需 |
---|---|---|
| 要创建的目标JAR文件 | 是 |
| Java类文件的根目录 | 是 |
| 要运行的主应用程序类。 | 否(默认值是第一个找到的类,它声明 |
以下嵌套元素可用于该任务:
本节展示了两个Ant任务示例。
指定开始类。
- <spring-boot:exejar destfile="target/my-application.jar"
- classes="target/classes" start-class="com.example.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>
spring-boot:findmainclass
这,这个,那,那个findmainclass
任务在内部由exejar
若要找到声明main
。如果有必要,也可以在构建中直接使用此任务。支持下列属性:
属性 | 描述 | 所需 |
---|---|---|
| Java类文件的根目录 | 是(除非 |
| 可用于短路 | 否 |
| 应该与结果一起设置的Ant属性 | 否(如果未指定结果,将记录结果) |
本节包含三个使用findmainclass
.
找到并记录。
<findmainclass classesroot="target/classes" />
找到并准备好。
<findmainclass classesroot="target/classes" property="main-class" />
覆盖并设置。
<findmainclass mainclass="com.example.MainClass" property="main-class" />
如果您想使用Maven、Gradle或Ant以外的构建工具,则可能需要开发自己的插件。可执行的JAR需要遵循特定的格式,某些条目需要以未压缩的形式编写(请参阅“可执行JAR格式“详见附录中的一节)。
SpringBootMaven和Gradle插件都使用spring-boot-loader-tools
才能真正产生罐子。如果需要,可以直接使用这个库。
若要重新打包现有存档,使其成为自带的可执行存档,请使用org.springframework.boot.loader.tools.Repackager
。这,这个,那,那个Repackager
类接受引用现有JAR或WAR存档的单个构造函数参数。使用两种可用的一种repackage()
方法替换原始文件或写入新目标。在重新打包程序运行之前,还可以在其上配置各种设置。
重新打包存档时,可以使用org.springframework.boot.loader.tools.Libraries
接口。我们没有提供任何具体的实现Libraries
在这里,因为它们通常是特定于构建系统的。
如果您的存档已经包含了库,则可以使用Libraries.NONE
.
如果你不使用Repackager.setMainClass()
若要指定主类,rePackager将使用ASM若要读取类文件并尝试使用public static void main(String[] args)
方法。如果找到多个候选人,则引发异常。
下面的示例显示了一个典型的重新打包实现:
- Repackager repackager = new Repackager(sourceJarFile);
- repackager.setBackupSource(false);
- repackager.repackage(new Libraries() {
- @Override
- public void doWithLibraries(LibraryCallback callback) throws IOException {
- // Build system specific implementation, callback for each dependency
- // callback.library(new Library(nestedFile, LibraryScope.COMPILE));
- }
- });
如果您对构建工具插件的工作方式感兴趣,可以查看spring-boot-tools
GitHub上的模块。可执行JAR格式的更多技术细节将在附录.
如果您有特定的与构建相关的问题,可以查看“如何“向导。
本节给出了一些常见的‘我如何做那个…’的答案在使用SpringBoot时经常出现的问题。它的覆盖范围并非详尽无遗,但确实涵盖了相当多的内容。
如果您有特定的问题,我们在这里不讨论,您可能需要检查。stackoverflow.com看看是否有人已经给出了答案。这也是一个问新问题的好地方(请使用spring-boot
(标签)。
我们也非常乐意扩展这一节。如果您想添加“如何-to”,请给我们发送一个拉请求.
本节包含与SpringBoot应用程序直接相关的主题。
FailureAnalyzer
是一种很好的方法,可以在启动时拦截异常并将其转换为人类可读的消息,包装在FailureAnalysis
。SpringBoot为应用程序上下文相关的异常、JSR-303验证等提供了这样的分析器。您也可以创建自己的。
AbstractFailureAnalyzer
的方便扩展。FailureAnalyzer
它检查要处理的异常中是否存在指定的异常类型。您可以对此进行扩展,以便您的实现只有在异常实际存在时才有机会处理它。如果由于任何原因无法处理异常,则返回null
给另一个实现一个处理异常的机会。
FailureAnalyzer
实现必须在META-INF/spring.factories
。下面的示例注册ProjectConstraintViolationFailureAnalyzer
:
- org.springframework.boot.diagnostics.FailureAnalyzer=\
- com.example.ProjectConstraintViolationFailureAnalyzer
![]() |
如果需要访问 |
SpringBoot自动配置尽力“做正确的事情”,但有时失败,很难说出原因。
有一个非常有用的ConditionEvaluationReport
可在任何SpringBoot中获得ApplicationContext
。如果您启用DEBUG
测井输出如果您使用spring-boot-actuator
(见执行者章节),也有一个conditions
在JSON中呈现报表的端点。使用该端点调试应用程序,并查看SpringBoot在运行时添加了哪些特性(哪些特性尚未添加)。
更多的问题可以通过查看源代码和Javadoc来回答。阅读代码时,请记住以下经验规则:
*AutoConfiguration
阅读他们的资料来源。特别注意@Conditional*
注释,以了解它们启用了哪些特性以及何时启用。加--debug
到命令行或系统属性。-Ddebug
在您的应用程序中获得所有自动配置决策的控制台日志。在运行中的Actuator应用程序中,请查看conditions
端点(/actuator/conditions
或相同信息的JMX等价物)。@ConfigurationProperties
(如ServerProperties
)并从中读取可用的外部配置选项。这,这个,那,那个@ConfigurationProperties
注释有一个name
属性,用作外部属性的前缀。因此,ServerProperties
有prefix="server"
它的配置属性是server.port
, server.address
和其他人。在运行中的Actuator应用程序中,请查看configprops
端点。bind
方法的Binder
将配置值显式地从Environment
以轻松的方式。它常与前缀连用。@Value
直接绑定到Environment
.@ConditionalOnExpression
为响应Spel表达式而打开和关闭功能的注释,通常使用从Environment
.A SpringApplication
有ApplicationListeners
和ApplicationContextInitializers
用于将自定义应用于上下文或环境的。SpringBoot从META-INF/spring.factories
。注册其他自定义的方法不止一种:
addListeners
和addInitializers
方法SpringApplication
在你运行之前。context.initializer.classes
或context.listener.classes
财产。META-INF/spring.factories
并打包应用程序都用作库的JAR文件。这,这个,那,那个SpringApplication
送些特别的ApplicationEvents
到侦听器(有些甚至在创建上下文之前),然后为由ApplicationContext
也是见“第23.5节,“应用程序事件和侦听器”“在‘SpringBoot特性’部分获得完整列表。
还可以自定义Environment
在通过以下方法刷新应用程序上下文之前EnvironmentPostProcessor
。每个实现都应在META-INF/spring.factories
,如以下示例所示:
org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor
实现可以加载任意文件并将它们添加到Environment
。例如,以下示例从类路径加载YAML配置文件:
public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor { private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { Resource path = new ClassPathResource("com/example/myapp/config.yml"); PropertySource<?> propertySource = loadYaml(path); environment.getPropertySources().addLast(propertySource); } private PropertySource<?> loadYaml(Resource path) { if (!path.exists()) { throw new IllegalArgumentException("Resource " + path + " does not exist"); } try { return this.loader.load("custom-resource", path).get(0); } catch (IOException ex) { throw new IllegalStateException( "Failed to load yaml configuration from " + path, ex); } } }
![]() |
这,这个,那,那个 |
![]() | 谨慎 |
---|---|
使用时 |
您可以使用ApplicationBuilder
类来创建父/子ApplicationContext
等级制度。见“第23.4节,“FLUENT Builder API”“在‘SpringBoot特性’一节中可以获得更多信息。
并非所有Spring应用程序都必须是Web应用程序(或Web服务)。如果您想在main
方法,还可以引导Spring应用程序来设置要使用的基础设施,可以使用SpringApplication
春靴的特征。一个SpringApplication
改变它的ApplicationContext
类,取决于它是否认为需要Web应用程序。您可以做的第一件事是将与服务器相关的依赖关系(例如ServletAPI)排除在类路径之外。如果不能这样做(例如,从同一个代码库运行两个应用程序),则可以显式调用setWebApplicationType(WebApplicationType.NONE)
你的SpringApplication
实例或设置applicationContextClass
属性(通过JavaAPI或具有外部属性)。您希望作为业务逻辑运行的应用程序代码可以实现为CommandLineRunner
作为一个@Bean
定义。
本节包括有关设置和读取属性、配置设置及其与SpringBoot应用程序的交互的主题。
您可以使用现有的构建配置来自动展开这些属性,而不是硬编码项目的构建配置中也指定的一些属性。这在Maven和Gradle中都是可能的。
可以使用资源筛选从Maven项目自动展开属性。如果您使用spring-boot-starter-parent
,然后您可以引用Maven的“项目属性”@..@
占位符,如以下示例所示:
- app.encoding=@project.build.sourceEncoding@
- app.java.version=@java.version@
![]() |
只有产品配置是这样过滤的(换句话说,不对其应用过滤)。 |
![]() |
如果启用 |
如果不使用初学者父级,则需要在<build/>
元素pom.xml
:
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- </resource>
- </resources>
您还需要在其中包含以下元素<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>
![]() |
这,这个,那,那个 |
您可以通过配置Java插件来自动扩展Gradle项目中的属性processResources
这样做的任务,如以下示例所示:
- processResources {
- expand(project.properties)
- }
然后,可以使用占位符引用Gradle项目的属性,如以下示例所示:
- app.name=${name}
- app.description=${description}
![]() |
格拉德尔氏 |
SpringApplication
A SpringApplication
有bean属性(主要是setter),所以在创建应用程序以修改其行为时,可以使用它的JavaAPI。或者,您可以通过在spring.main.*
。例如,在application.properties
,您可能具有以下设置:
- spring.main.web-application-type=none
- spring.main.banner-mode=off
然后SpringBoot横幅不会在启动时打印,应用程序也不会启动嵌入式Web服务器。
外部配置中定义的属性覆盖用Java API指定的值,但用于创建ApplicationContext
。考虑以下申请:
- new SpringApplicationBuilder()
- .bannerMode(Banner.Mode.OFF)
- .sources(demo.MyApp.class)
- .run(args);
现在考虑以下配置:
- spring.main.sources=com.acme.Config,com.acme.ExtraConfig
- spring.main.banner-mode=console
实际应用现在显示横幅(由配置覆盖),并使用三个源作为ApplicationContext
(按以下顺序排列):demo.MyApp
, com.acme.Config
,和com.acme.ExtraConfig
.
默认情况下,来自不同来源的属性将添加到Spring中Environment
按规定的顺序(见“第24章,外化配置“在‘SpringBoot特性’一节中得到确切的顺序)。
增加和修改此顺序的一个很好的方法是添加@PropertySource
对应用程序源的注释。类传递给SpringApplication
静态方便方法和使用setSources()
检查他们是否有@PropertySources
。如果有,则将这些属性添加到Environment
的所有阶段都可以使用。ApplicationContext
生命周期。以这种方式添加的属性比通过使用默认位置添加的属性具有更低的优先级(如application.properties
)、系统属性、环境变量或命令行。
还可以提供以下系统属性(或环境变量)来更改行为:
spring.config.name
(SPRING_CONFIG_NAME
):默认为application
作为文件名的根目录。spring.config.location
(SPRING_CONFIG_LOCATION
):要加载的文件(例如类路径资源或URL)。单独的Environment
属性源是为该文档设置的,它可以被系统属性、环境变量或命令行覆盖。无论您在环境中设置了什么,SpringBoot总是加载application.properties
如上文所述。默认情况下,如果使用YAML,那么扩展名为“.yml”的文件也会添加到列表中。
SpringBoot记录加载在DEBUG
级别和它没有找到的候选人TRACE
水平。
看见ConfigFileApplicationListener
更多细节。
有些人喜欢使用(例如)--port=9000
而不是--server.port=9000
若要在命令行上设置配置属性,请执行以下操作。中的占位符可以启用此行为。application.properties
,如以下示例所示:
server.port=${port:8080}
![]() |
如果您从 |
![]() |
在这种特殊情况下,端口绑定在PaaS环境(如Heroku或CloudFoundry)中工作。在这两个平台中, |
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文件解析为JavaMap<String,Object>
(就像一个JSON对象),SpringBoot将地图平放,这样它就像许多人习惯的那样,具有一个层次深和周期分隔的键。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
见“第24.6节,“使用YAML而不是属性”“有关YAML的更多信息,请参见‘SpringBoot功能’部分。
春天Environment
有一个API,但是您通常会设置一个系统属性(spring.profiles.active
)或OS环境变量(SPRING_PROFILES_ACTIVE
)此外,您还可以使用-D
参数(请记住将其放在主类或JAR存档之前),如下所示:
$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar
在SpringBoot中,还可以在application.properties
,如以下示例所示:
spring.profiles.active=production
以这种方式将值集替换为系统属性或环境变量设置,而不是由SpringApplicationBuilder.profiles()
方法。因此,后一种JavaAPI可以用于在不更改默认值的情况下增强概要文件。
见“第25章,剖面图在“SpringBoot功能”一节中获得更多信息。
YAML文件实际上是一系列由---
行,每个文档分别解析成一个扁平的地图。
如果YAML文档包含spring.profiles
键,则配置文件值(以逗号分隔的配置文件列表)输入Spring。Environment.acceptsProfiles()
方法。如果其中任何一个配置文件是活动的,则该文档将包含在最后的合并中(否则,它不会),如下面的示例所示:
- server:
- port: 9000
- ---
-
- spring:
- profiles: development
- server:
- port: 9001
-
- ---
-
- spring:
- profiles: production
- server:
- port: 0
在前面的示例中,默认端口是9000。但是,如果名为“Development”的Spring配置文件是活动的,那么端口是9001。如果“Production”处于活动状态,则端口为0。
![]() |
YAML文档按遇到它们的顺序合并。后面的值覆盖先前的值。 |
要对属性文件执行相同的操作,可以使用application-${profile}.properties
若要指定特定于配置文件的值,请执行以下操作。
Spring Boot绑定外部属性application.properties
(或.yml
文件和其他位置)在运行时进入应用程序。在单个位置上没有(技术上也不可能)列出所有受支持的属性,因为贡献可以来自类路径上的其他JAR文件。
具有Actuator特性的正在运行的应用程序具有configprops
显示所有绑定和绑定属性的终结点。@ConfigurationProperties
.
附录包括application.properties
示例包含SpringBoot支持的最常见属性的列表。最终列表来自于搜索源代码@ConfigurationProperties
和@Value
注释以及偶尔使用Binder
。有关加载属性的确切顺序的更多信息,请参见“第24章,外化配置".
每个SpringBootWeb应用程序都包括一个嵌入式Web服务器。这个特性带来了许多如何解决的问题,包括如何更改嵌入式服务器和如何配置嵌入式服务器。本节回答这些问题。
许多SpringBootStarter包括默认的嵌入式容器。
spring-boot-starter-web
包括Tomcatspring-boot-starter-tomcat
,但你可以用spring-boot-starter-jetty
或spring-boot-starter-undertow
相反。spring-boot-starter-webflux
包括反应堆Nettyspring-boot-starter-reactor-netty
,但你可以用spring-boot-starter-tomcat
, spring-boot-starter-jetty
,或spring-boot-starter-undertow
相反。切换到不同的HTTP服务器时,除了包含所需的依赖项外,还需要排除默认的依赖项。SpringBoot为HTTP服务器提供了单独的启动程序,以帮助尽可能简化此过程。
下面的Maven示例展示了如何排除Tomcat并包含SpringMVC的JettyforSpringMVC:
- <properties>
- <servlet-api.version>3.1.0</servlet-api.version>
- </properties>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <!-- Exclude the Tomcat dependency -->
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <!-- Use Jetty instead -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jetty</artifactId>
- </dependency>

![]() |
The version of the Servlet API has been overridden as, unlike Tomcat 9 and Undertow 2.0, Jetty 9.4 does not support Servlet 4.0. |
下面的Gradle示例演示了如何排除Netty,并包括SpringWebFlux的UndertoforSpringWebFlux:
- configurations {
- // exclude Reactor Netty
- compile.exclude module: 'spring-boot-starter-reactor-netty'
- }
-
- dependencies {
- compile 'org.springframework.boot:spring-boot-starter-webflux'
- // Use Undertow instead
- compile 'org.springframework.boot:spring-boot-starter-undertow'
- // ...
- }
![]() |
|
如果类路径包含启动Web服务器所需的比特,SpringBoot将自动启动它。若要禁用此行为,请配置WebApplicationType
在你的application.properties
,如以下示例所示:
spring.main.web-application-type=none
在独立应用程序中,主HTTP端口默认为8080
但是可以用server.port
(例如,在application.properties
或作为系统属性)。由于放宽了对.的约束Environment
值,也可以使用SERVER_PORT
(例如,作为OS环境变量)。
若要完全关闭HTTP端点,但仍要创建一个WebApplicationContext
,使用server.port=-1
。(这样做有时对测试很有用。)
有关详细信息,请参阅“第27.4.4节,“定制嵌入式servlet容器”“在‘SpringBoot特性’部分,或ServerProperties
源代码。
若要扫描自由端口(使用OS本机防止冲突),请使用server.port=0
.
您可以从日志输出或从ServletWebServerApplicationContext
通过它WebServer
。获得该值并确保它已初始化的最佳方法是添加@Bean
类型ApplicationListener<ServletWebServerInitializedEvent>
并在事件发布时将容器从事件中取出。
使用的测试@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
还可以通过使用@LocalServerPort
注释,如以下示例所示:
- @RunWith(SpringJUnit4ClassRunner.class)
- @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
- public class MyWebIntegrationTests {
-
- @Autowired
- ServletWebServerApplicationContext server;
-
- @LocalServerPort
- int port;
-
- // ...
-
- }
![]() |
|
Http响应压缩由Jetty、Tomcat和安德托支持。可以在application.properties
,如下:
server.compression.enabled=true
默认情况下,要执行压缩,响应长度必须至少为2048字节。可以通过设置server.compression.min-response-size
财产。
默认情况下,只有当响应的内容类型为下列之一时,才会压缩其响应:
text/html
text/xml
text/plain
text/css
text/javascript
application/javascript
application/json
application/xml
可以通过设置server.compression.mime-types
财产。
可以通过设置各种server.ssl.*
属性,通常在application.properties
或application.yml
。下面的示例显示如何在application.properties
:
- server.port=8443
- server.ssl.key-store=classpath:keystore.jks
- server.ssl.key-store-password=secret
- server.ssl.key-password=another-secret
看见Ssl
有关所有受支持属性的详细信息。
使用前面示例中的配置意味着应用程序不再支持端口8080处的普通HTTP连接器。Spring Boot不支持通过以下方式配置HTTP连接器和HTTPS连接器application.properties
。如果希望两者兼得,则需要以编程方式配置其中之一。我们建议使用application.properties
要配置HTTPS,HTTP连接器更容易以编程方式进行配置。见spring-boot-sample-tomcat-multi-connectors
示例项目示例。
可以在SpringBoot应用程序中启用HTTP/2支持,server.http2.enabled
配置属性。这种支持取决于所选择的Web服务器和应用程序环境,因为JDK 8不支持该协议。
![]() |
春靴不支持 |
对于Ruby1.4.0+,支持HTTP/2,而不需要对JDK 8进行任何额外的要求。
在Jetty9.4.8中,HTTP/2也被氪库。要启用这种支持,应用程序需要有两个额外的依赖项:org.eclipse.jetty:jetty-alpn-conscrypt-server
和org.eclipse.jetty.http2:http2-server
.
SpringBoot默认附带Tomcat9.0.x,它在使用JDK 9或更高版本时支持HTTP/2。或者,可以在JDK 8上使用HTTP/2,如果libtcnative
库及其依赖项安装在主机操作系统上。
库文件夹必须可用(如果还没有)到JVM库路径。您可以使用jvm参数(如-Djava.library.path=/usr/local/opt/tomcat-native/lib
。关于这一点的更多信息官方Tomcat文件.
在JDK 8上启动Tomcat 9.0.x,如果没有本机支持,将记录以下错误:
ERROR 8787 --- [ main] o.a.coyote.http11.Http11NioProtocol : The upgrade handler [org.apache.coyote.http2.Http2Protocol] for [h2] only supports upgrade via ALPN but has been configured for the ["https-jsse-nio-8443"] connector that does not support ALPN.
此错误并不致命,应用程序仍然以HTTP/1.1SSL支持启动。
这,这个,那,那个spring-boot-webflux-starter
默认情况下使用反应堆Netty作为服务器。使用JDK 9或更高版本的JDK支持,可以为HTTP/2配置ResiveNetty。对于JDK 8环境或最佳运行时性能,此服务器还支持带有本机库的HTTP/2。为此,应用程序需要有额外的依赖项。
Spring Boot管理io.netty:netty-tcnative-boringssl-static
“uber jar”,包含所有平台的本机库。开发人员可以选择仅使用分类器导入所需的依赖项(请参阅Netty官方文件).
通常,您应该首先考虑使用许多可用的配置键之一,并通过在application.properties
(或application.yml
,或环境等见“第76.8节,“发现外部属性的内置选项”“)这,这个,那,那个server.*
命名空间在这里非常有用,它包括了如下所示的名称空间server.tomcat.*
, server.jetty.*
而其他的则是针对特定于服务器的特性。见附录A,通用应用特性.
前面的部分已经介绍了许多常见的用例,例如压缩、SSL或HTTP/2。但是,如果用例中不存在配置密钥,则应该查看WebServerFactoryCustomizer
。您可以声明这样的组件并访问与您的选择相关的服务器工厂:您应该为所选的服务器(Tomcat、Jetty、ReactiveNetty、Under拖车)和所选的Web堆栈(servlet或反应性)选择变量。
下面的示例用于Tomcatspring-boot-starter-web
(servlet堆栈):
- @Component
- public class MyTomcatWebServerCustomizer
- implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
-
- @Override
- public void customize(TomcatServletWebServerFactory factory) {
- // customize the factory here
- }
- }
此外,SpringBoot还提供:
服务器 | Servlet堆栈 | 反应堆栈 |
---|---|---|
猫猫 |
|
|
码头 |
|
|
下引 |
|
|
反应器 | N/A |
|
一旦您可以访问WebServerFactory
,您通常可以向其添加自定义器,以配置特定的部件,如连接器、服务器资源或服务器本身-所有这些都使用特定于服务器的API。
作为最后的手段,你也可以宣布你自己的WebServerFactory
组件,它将覆盖SpringBoot提供的组件。在本例中,不能依赖server
命名空间了。
在servlet堆栈应用程序中,即使用spring-boot-starter-web
,有两种方法可以添加Servlet
, Filter
, ServletContextListener
,以及ServletAPI对应用程序支持的其他侦听器:
若要添加Servlet
, Filter
,或Servlet*Listener
通过使用Springbean,您必须提供一个@Bean
它的定义。当您想注入配置或依赖项时,这样做非常有用。但是,您必须非常小心,以免它们导致太多其他bean的急切初始化,因为它们必须在应用程序生命周期的早期就安装在容器中。(例如,让它们依赖于您的DataSource
或JPA配置)您可以通过在第一次使用时而不是在初始化时延迟初始化bean来绕过这些限制。
如属Filters
和Servlets
,还可以添加映射和init参数。FilterRegistrationBean
或者是ServletRegistrationBean
代替或补充基础组件。
![]() |
如果没有 |
与任何其他Springbean一样,您可以定义servlet过滤器bean的顺序;请确保检查“这一节名为“将servlet、过滤器和侦听器注册为Springbean”“分段。
禁用servlet或过滤器的注册
如前文描述,任何Servlet
或Filter
bean自动在servlet容器中注册。若要禁用特定的注册,请执行以下操作Filter
或Servlet
bean,为它创建一个注册bean并将其标记为禁用,如下面的示例所示:
- @Bean
- public FilterRegistrationBean registration(MyFilter filter) {
- FilterRegistrationBean registration = new FilterRegistrationBean(filter);
- registration.setEnabled(false);
- return registration;
- }
@WebServlet
, @WebFilter
,和@WebListener
带注释的类可以自动在嵌入式servlet容器中注册。@Configuration
类@ServletComponentScan
并指定包含要注册的组件的包。默认情况下,@ServletComponentScan
从带注释的类的包中进行扫描。
访问日志可以通过各自的名称空间为Tomcat、Under拖车和Jetty配置。
例如,在Tomcat上使用定制模式.
- server.tomcat.basedir=my-tomcat
- server.tomcat.accesslog.enabled=true
- server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms)
![]() |
日志的默认位置是 |
下面的访问日志可以类似的方式配置,如下面的示例所示:
- server.undertow.accesslog.enabled=true
- server.undertow.accesslog.pattern=%t %a "%r" %s (%D ms)
日志存储在logs
相对于应用程序的工作目录。可以通过设置server.undertow.accesslog.directory
财产。
最后,Jetty的访问日志也可以配置如下:
- server.jetty.accesslog.enabled=true
- server.jetty.accesslog.filename=/var/log/jetty-access.log
默认情况下,日志重定向到System.err
。有关详细信息,请参阅码头文件.
您的应用程序可能需要发送302
用绝对链接重定向或呈现内容。在代理后面运行时,调用方需要一个指向代理的链接,而不是指向承载应用程序的机器的物理地址的链接。通常,这样的情况是通过与代理的契约来处理的,代理会添加标题来告诉后端如何构造指向自己的链接。
如果代理添加常规X-Forwarded-For
和X-Forwarded-Proto
头(大多数代理服务器都这样做),应该正确地呈现绝对链接,前提是server.use-forward-headers
设置为true
在你的application.properties
.
![]() |
如果应用程序在CloudFoundry或Heroku中运行,则 |
如果使用Tomcat,则还可以配置用于携带“转发”信息的标头的名称,如下面的示例所示:
- server.tomcat.remote-ip-header=x-your-remote-ip-header
- server.tomcat.protocol-header=x-your-protocol-header
Tomcat还配置了一个与要信任的内部代理匹配的默认正则表达式。默认情况下,10/8
, 192.168/16
, 169.254/16
和127/8
是值得信任的。您可以自定义阀门的配置,方法是在application.properties
,如以下示例所示:
server.tomcat.internal-proxies=192\\.168\\.\\d{1,3}\\.\\d{1,3}
![]() |
只有在使用属性文件进行配置时才需要双反斜杠。如果使用YAML,则单反斜杠就足够了,与前面示例中所示的值相等的值将为 |
![]() |
通过设置 |
您可以完全控制Tomcat的配置RemoteIpValve
通过关闭自动开关(为此,设置server.use-forward-headers=false
)中添加了一个新的阀门实例。TomcatServletWebServerFactory
豆子
您可以添加一个org.apache.catalina.connector.Connector
到TomcatServletWebServerFactory
,它允许多个连接器,包括HTTP和HTTPS连接器,如以下示例所示:
@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); } }
默认情况下,SpringBoot使用的嵌入式Tomcat不支持Cookie格式的“Version 0”,因此您可能会看到以下错误:
java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value
如果可能的话,您应该考虑更新代码,使其只存储符合后续Cookie规范的值。但是,如果不能更改cookie的编写方式,则可以将Tomcat配置为使用LegacyCookieProcessor
。切换到LegacyCookieProcessor
,使用WebServerFactoryCustomizer
bean,它添加了一个TomcatContextCustomizer
,如以下示例所示:
- @Bean
- public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
- return (factory) -> factory.addContextCustomizers(
- (context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
- }
添加一个UndertowBuilderCustomizer
到UndertowServletWebServerFactory
并将侦听器添加到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;
- }
如果你想用@ServerEndpoint
在使用嵌入式容器的SpringBoot应用程序中,必须声明一个ServerEndpointExporter
@Bean
,如以下示例所示:
- @Bean
- public ServerEndpointExporter serverEndpointExporter() {
- return new ServerEndpointExporter();
- }
前面示例中显示的bean注册任何@ServerEndpoint
带有基础WebSocket容器的注释bean。当部署到独立servlet容器时,此角色由servlet容器初始化器执行,ServerEndpointExporter
bean不是必需的。
SpringBoot有许多启动程序,包括SpringMVC。请注意,有些初学者包括对SpringMVC的依赖,而不是直接包含它。本节回答关于SpringMVC和SpringBoot的常见问题。
任何春天@RestController
在SpringBoot应用程序中,只要Jackson 2在类路径上,默认情况下应该呈现JSON响应,如下面的示例所示:
- @RestController
- public class MyController {
-
- @RequestMapping("/thing")
- public MyThing thing() {
- return new MyThing();
- }
-
- }
只要MyThing
可以由Jackson 2(对于普通POJO或Groovy对象为true)序列化,然后localhost:8080/thing
默认情况下为它提供JSON表示。请注意,在浏览器中,有时可能会看到XML响应,因为浏览器倾向于发送更喜欢XML的接受标头。
如果您有Jackson XML扩展(jackson-dataformat-xml
)在类路径上,您可以使用它来呈现XML响应。我们用于JSON的前面的示例将起作用。若要使用Jackson XML呈现程序,请将以下依赖项添加到项目中:
- <dependency>
- <groupId>com.fasterxml.jackson.dataformat</groupId>
- <artifactId>jackson-dataformat-xml</artifactId>
- </dependency>
您还可能希望添加对Woodstox的依赖。它比JDK提供的默认StAX实现更快,还添加了漂亮的打印支持和改进的命名空间处理。下面的清单显示了如何将依赖项包含在伍德斯托克斯:
- <dependency>
- <groupId>org.codehaus.woodstox</groupId>
- <artifactId>woodstox-core-asl</artifactId>
- </dependency>
如果Jackson的XML扩展不可用,则使用JAXB(默认情况下在JDK中提供),另外还要求MyThing
注释为@XmlRootElement
,如以下示例所示:
- @XmlRootElement
- public class MyThing {
- private String name;
- // .. getters and setters
- }
要使服务器呈现XML而不是JSON,您可能需要发送一个Accept: text/xml
标题(或使用浏览器)。
SpringMVC(客户机和服务器端)使用HttpMessageConverters
若要协商HTTP交换中的内容转换,请执行以下操作。如果Jackson在类路径上,则您已经获得了由Jackson2ObjectMapperBuilder
的实例是为您自动配置的。
这,这个,那,那个ObjectMapper
(或XmlMapper
对于Jackson XML转换器)实例(默认情况下创建)具有以下自定义属性:
MapperFeature.DEFAULT_VIEW_INCLUSION
残废DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
残废SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
残废SpringBoot还提供了一些特性,使定制这种行为更加容易。
您可以配置ObjectMapper
和XmlMapper
通过使用环境执行实例。Jackson提供了一系列简单的ON/OFF功能,可用于配置处理的各个方面。在映射到环境中的属性的六个枚举(在Jackson中)中描述了这些特性:
Enum | 财产 | 价值 |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
例如,要启用漂亮的打印,请设置spring.jackson.serialization.indent_output=true
。请注意,由于使用了松弛结合,案件indent_output
不需要匹配对应的枚举常量的情况,即INDENT_OUTPUT
.
此基于环境的配置应用于自动配置。Jackson2ObjectMapperBuilder
并应用于通过使用构建器创建的任何映射器,包括自动配置的ObjectMapper
豆子
语境Jackson2ObjectMapperBuilder
可以由一个或多个自定义Jackson2ObjectMapperBuilderCustomizer
豆子这样的定制bean可以被订购(Boot自己的定制器的订单为0),允许在Boot自定义之前和之后应用额外的定制。
任何类型的豆类com.fasterxml.jackson.databind.Module
将自动注册到自动配置的Jackson2ObjectMapperBuilder
并适用于任何ObjectMapper
它创建的实例。这提供了在向应用程序添加新功能时提供自定义模块的全局机制。
如果要替换默认值ObjectMapper
完全,要么定义@Bean
并将其标记为@Primary
或者,如果您更喜欢基于构建器的方法,则定义Jackson2ObjectMapperBuilder
@Bean
。注意,在任何一种情况下,这样做都会禁用ObjectMapper
.
如果你提供任何@Beans
类型MappingJackson2HttpMessageConverter
,它们替换了MVC配置中的默认值。另外,一个类型的方便beanHttpMessageConverters
提供(如果使用默认的MVC配置,则始终可用)。它有一些有用的方法来访问默认的和用户增强的消息转换器。
见“第78.4节,“自定义@ResponseBody呈现”“分段和WebMvcAutoConfiguration
有关更多细节的源代码。
弹簧使用HttpMessageConverters
渲染@ResponseBody
(或来自@RestController
)您可以通过在SpringBoot上下文中添加适当类型的bean来贡献额外的转换器。如果您添加的bean是默认包含的类型(如MappingJackson2HttpMessageConverter
对于JSON转换),它将替换默认值。一种方便型豆类HttpMessageConverters
如果使用默认的MVC配置,则始终可用。它有一些有用的方法来访问默认的和用户增强的消息转换器(例如,如果您想手动将它们注入到自定义中,则可能很有用。)RestTemplate
).
与正常的mvc用法一样,任何WebMvcConfigurer
您提供的bean还可以通过覆盖configureMessageConverters
方法。但是,与普通的MVC不同,您只能提供所需的额外转换器(因为SpringBoot使用相同的机制来贡献其缺省值)。最后,如果您选择退出SpringBoot默认MVC配置,提供您自己的@EnableWebMvc
配置,您可以完全控制并手动执行所有操作。getMessageConverters
从…WebMvcConfigurationSupport
.
见WebMvcAutoConfiguration
有关更多细节的源代码。
Spring Boot包含Servlet 3javax.servlet.http.Part
API支持上传文件。默认情况下,SpringBoot在单个请求中配置SpringMVC,最大大小为每个文件1MB,文件数据最多为10 MB。您可以重写这些值,即存储中间数据的位置(例如,到/tmp
目录),以及通过使用公开的属性将数据刷新到磁盘的阈值。MultipartProperties
班级,等级例如,如果要指定文件是无限的,请将spring.servlet.multipart.max-file-size
财产-1
.
当您希望将多部分编码的文件数据作为@RequestParam
-带注释的类型参数MultipartFile
在SpringMVC控制器处理程序方法中。
见MultipartAutoConfiguration
有关更多细节的消息来源。
默认情况下,所有内容都来自应用程序的根(/
)如果您希望映射到另一条路径,则可以按以下方式配置路径:
spring.mvc.servlet.path=/acme
如果有其他servlet,则可以声明@Bean
类型Servlet
或ServletRegistrationBean
对于每个和SpringBoot,它们将透明地注册到容器中。因为servlet是以这种方式注册的,所以可以将它们映射到DispatcherServlet
而不调用它。
配置DispatcherServlet
你自己是不寻常的,但如果你真的需要这样做,@Bean
类型DispatcherServletPath
还必须提供自定义路径的方法。DispatcherServlet
.
要完全控制mvc配置,最简单的方法是提供您自己的@Configuration
带着@EnableWebMvc
注释这样做的话,所有的MVC配置都将掌握在您的手中。
A ViewResolver
是SpringMVC的核心组件,在@Controller
到实际View
实现。请注意ViewResolvers
主要用于ui应用程序,而不是REST样式的服务(View
不用于呈现@ResponseBody
)的实现有很多种。ViewResolver
选择和Spring本身并不是关于您应该使用哪一种选择的意见。另一方面,Spring Boot为您安装一个或两个,这取决于它在类路径和应用程序上下文中找到了什么。这,这个,那,那个DispatcherServlet
使用它在应用程序上下文中找到的所有解析器,依次尝试每个解析器,直到得到结果为止,因此,如果添加自己的解析器,则必须知道顺序和添加解析器的位置。
WebMvcAutoConfiguration
添加以下内容ViewResolvers
关于你的背景:
InternalResourceViewResolver
名为“defaultViewResolver”。此方法定位可以通过使用DefaultServlet
(如果使用静态资源和JSP页面,则包括这些页面)。它将前缀和后缀应用于视图名称,然后在servlet上下文中查找具有该路径的物理资源(默认值均为空,但可通过以下方式进行外部配置)spring.mvc.view.prefix
和spring.mvc.view.suffix
)您可以通过提供相同类型的bean来覆盖它。BeanNameViewResolver
名为“beanNameViewResolver”。这是视图解析器链的有用成员,并获取与View
被解决了。不应该有必要重写或替换它。ContentNegotiatingViewResolver
名为“viewResolver”的是实际上是豆类View
现在时这是一个“主”解析器,它将委托给所有其他解析器,并试图找到与客户端发送的“接受”HTTP头匹配的内容。有一个有用的博客ContentNegotiatingViewResolver
您可能希望学习更多,也可以查看源代码以获得详细信息。您可以关闭自动配置的ContentNegotiatingViewResolver
通过定义一个名为“viewResolver”的bean。ThymeleafViewResolver
名为“hymeleafViewResolver”。它通过用前缀和后缀包围视图名称来查找资源。前缀是spring.thymeleaf.prefix
,后缀是spring.thymeleaf.suffix
。前缀和后缀的值分别默认为“classpath:/模板/”和“.html”。你可以覆盖ThymeleafViewResolver
通过提供同名的bean。FreeMarkerViewResolver
名为“FreeMarkerViewResolver”。它在加载程序路径中查找资源(外部化为spring.freemarker.templateLoaderPath
并以前缀和后缀包围视图名称,其默认值为“classpath:/Template/”。前缀外部化为spring.freemarker.prefix
,并且后缀被外部化为spring.freemarker.suffix
。前缀和后缀的默认值分别为空和.ftl。你可以覆盖FreeMarkerViewResolver
通过提供同名的bean。groovy-templates
在您的类路径上),您也有一个GroovyMarkupViewResolver
名为“groovyMarkupViewResolver”。它在加载程序路径中查找资源,方法是在视图名称周围加上前缀和后缀(外部化为spring.groovy.template.prefix
和spring.groovy.template.suffix
)前缀和后缀的默认值分别为“classpath:/模板/”和“.tpl”。你可以覆盖GroovyMarkupViewResolver
通过提供同名的bean。有关更多细节,请参见以下各节:
WebMvcAutoConfiguration
ThymeleafAutoConfiguration
FreeMarkerAutoConfiguration
GroovyTemplateAutoConfiguration
SpringSecurity支持以特定用户的身份运行测试。例如,下面的代码段中的测试将与具有ADMIN
角色。
- @Test
- @WithMockUser(roles="ADMIN")
- public void requestProtectedUrlWithUser() throws Exception {
- mvc
- .perform(get("/"))
- ...
- }
SpringSecurity提供了与SpringMVC测试的全面集成,这也可以用于使用@WebMvcTest
切片和MockMvc
.
有关SpringSecurity的测试支持的详细信息,请参阅SpringSecurity的参考文献).
SpringSecurity可以用于保护基于泽西岛的Web应用程序,其方式与用于保护基于SpringMVC的Web应用程序的方式非常相似。但是,如果您想在泽西使用SpringSecurity的方法级安全性,则必须将泽西配置为使用setStatus(int)
相反sendError(int)
。这使泽西无法在SpringSecurity有机会向客户端报告身份验证或授权失败之前提交响应。
这,这个,那,那个jersey.config.server.response.setStatusOverSendError
属性必须设置为true
关于申请ResourceConfig
bean,如以下示例所示:
- @Component
- public class JerseyConfig extends ResourceConfig {
-
- public JerseyConfig() {
- register(Endpoint.class);
- setProperties(Collections.singletonMap(
- "jersey.config.server.response.setStatusOverSendError", true));
- }
-
- }
SpringBoot提供了许多与HTTP客户端一起工作的启动程序。本节回答与使用它们有关的问题。
如上文所述第33.1节,“餐厅模板定制”,您可以使用RestTemplateCustomizer
带着RestTemplateBuilder
要构建自定义的RestTemplate
。这是创建RestTemplate
配置为使用代理。
代理配置的确切细节取决于正在使用的底层客户端请求工厂。下面的示例配置HttpComponentsClientRequestFactory
带着HttpClient
,它对所有主机都使用一个代理,除了192.168.0.5
:
static class ProxyCustomizer implements RestTemplateCustomizer { @Override public void customize(RestTemplate restTemplate) { HttpHost proxy = new HttpHost("proxy.example.com"); HttpClient httpClient = HttpClientBuilder.create() .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { @Override public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (target.getHostName().equals("192.168.0.5")) { return null; } return super.determineProxy(target, request, context); } }).build(); restTemplate.setRequestFactory( new HttpComponentsClientHttpRequestFactory(httpClient)); } }
SpringBoot没有强制的日志记录依赖项,但CommonsLoggingAPI除外,它通常由Spring框架的spring-jcl
模块。使用Logback,你需要把它包括进去spring-jcl
在类路径上。做到这一点的最简单的方法是通过启动程序,这都依赖于spring-boot-starter-logging
。对于web应用程序,只需spring-boot-starter-web
,因为它依赖于日志记录启动程序。如果使用Maven,下面的依赖项将为您添加日志记录:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
春靴LoggingSystem
试图根据类路径的内容配置日志记录的抽象。如果登录是可用的,这是第一选择。
如果您需要对日志记录所做的唯一更改是设置各种记录器的级别,则可以在application.properties
通过使用“logging.level”前缀,如下面的示例所示:
- logging.level.org.springframework.web=DEBUG
- logging.level.org.hibernate=ERROR
还可以使用“logging.file”设置要写入日志的文件的位置(除了控制台)。
若要配置日志系统的更细粒度设置,需要使用LoggingSystem
有疑问。默认情况下,SpringBoot从系统的默认位置获取本机配置(如classpath:logback.xml
,但是可以使用“logging.config”属性设置配置文件的位置。
如果你把logback.xml
在您的类路径的根,它是从那里(或从logback-spring.xml
,以利用Boot提供的模板功能)。SpringBoot提供了一个默认的基本配置,如果您想设置级别,可以包括它,如下面的示例所示:
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration>
- <include resource="org/springframework/boot/logging/logback/base.xml"/>
- <logger name="org.springframework.web" level="DEBUG"/>
- </configuration>
如果你看看base.xml
在Spring-boot jar中,您可以看到它使用了一些有用的系统属性,LoggingSystem
负责为您创建:
${PID}
*当前进程ID。${LOG_FILE}
*是否logging.file
设置在Boot的外部配置中。${LOG_PATH}
*是否logging.path
(表示日志文件驻留的目录)在Boot的外部配置中设置。${LOG_EXCEPTION_CONVERSION_WORD}
*是否logging.exception-conversion-word
设置在Boot的外部配置中。SpringBoot还通过使用自定义的Logback转换器在控制台(但不是在日志文件中)提供一些很好的ANSI彩色终端输出。参见默认值base.xml
详细配置。
如果Groovy在类路径上,您应该能够用logback.groovy
也是如果存在,则优先考虑此设置。
如果要禁用控制台日志记录并只将输出写入文件,则需要自定义logback-spring.xml
进口file-appender.xml
但不是console-appender.xml
,如以下示例所示:
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration>
- <include resource="org/springframework/boot/logging/logback/defaults.xml" />
- <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
- <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
- <root level="INFO">
- <appender-ref ref="FILE" />
- </root>
- </configuration>
您还需要添加logging.file
敬你的application.properties
,如以下示例所示:
logging.file=myapplication.log
弹簧启动支架Log4j 2如果它位于类路径上,则用于日志配置。如果将启动程序用于组装依赖项,则必须排除Logback,然后包含log4j2。如果不使用启动程序,则需要提供(至少)spring-jcl
除了Log4j 2。
最简单的路径可能是通过启动,尽管它需要一些与排除。下面的示例演示如何在Maven中设置Starter:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-log4j2</artifactId>
- </dependency>

下面的示例展示了在Gradle中设置Starter的一种方法:
- dependencies {
- compile 'org.springframework.boot:spring-boot-starter-web'
- compile 'org.springframework.boot:spring-boot-starter-log4j2'
- }
-
- configurations {
- all {
- exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
- }
- }
![]() |
Log4j启动程序将常见日志记录需求的依赖项集合在一起(例如让Tomcat使用)。 |
![]() |
以确保使用 |
除了默认的XML配置格式之外,Log4j 2还支持YAML和JSON配置文件。若要将Log4j 2配置为使用替代配置文件格式,请将适当的依赖项添加到类路径中,并将配置文件命名为与所选文件格式匹配的配置文件,如下面的示例所示:
格式 | 相依性 | 文件名 |
---|---|---|
YAML |
|
|
杰森 |
|
|
SpringBoot包括许多用于处理数据源的启动程序。本节回答与此相关的问题。
配置自己的DataSource
,定义@Bean
在你的配置中。Spring Boot重用您的DataSource
任何需要的地方,包括数据库初始化。如果需要将某些设置外部化,则可以绑定DataSource
对环境的影响(见“第24.7.1节,“第三方配置””).
下面的示例演示如何在bean中定义数据源:
- @Bean
- @ConfigurationProperties(prefix="app.datasource")
- public DataSource dataSource() {
- return new FancyDataSource();
- }
下面的示例演示如何通过设置属性来定义数据源:
- app.datasource.url=jdbc:h2:mem:mydb
- app.datasource.username=sa
- app.datasource.pool-size=30
假设你FancyDataSource
具有URL、用户名和池大小的常规JavaBean属性,这些设置在DataSource
提供给其他组件。常客数据库初始化也会发生(所以相关的子集spring.datasource.*
仍然可以与您的自定义配置一起使用)。
如果配置自定义JNDI,则可以应用相同的原则。DataSource
,如以下示例所示:
- @Bean(destroyMethod="")
- @ConfigurationProperties(prefix="app.datasource")
- public DataSource dataSource() throws Exception {
- JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
- return dataSourceLookup.getDataSource("java:comp/env/jdbc/YourDS");
- }
SpringBoot还提供了一个实用程序生成器类,称为DataSourceBuilder
,它可以用于创建标准数据源之一(如果它位于类路径上)。构建器可以根据类路径上可用的内容来检测要使用的对象。它还可以根据JDBCURL自动检测驱动程序。
下面的示例演示如何使用DataSourceBuilder
:
- @Bean
- @ConfigurationProperties("app.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().build();
- }
用它运行一个应用程序DataSource
,您所需要的只是连接信息。还可以提供特定于池的设置。有关更多细节,请检查将在运行时使用的实现。
下面的示例演示如何通过设置属性来定义JDBC数据源:
- app.datasource.url=jdbc:mysql://localhost/test
- app.datasource.username=dbuser
- app.datasource.password=dbpass
- app.datasource.pool-size=30
然而,有一个陷阱。由于未公开连接池的实际类型,因此在您的自定义元数据中不会生成任何键。DataSource
而且您的IDE中没有可用的完成(因为DataSource
接口不公开属性)。此外,如果您碰巧在类路径上有Hikari,则此基本设置不起作用,因为Hikari没有url
属性(但确实有jdbcUrl
财产)。在这种情况下,您必须按照以下方式重写您的配置:
- app.datasource.jdbc-url=jdbc:mysql://localhost/test
- app.datasource.username=dbuser
- app.datasource.password=dbpass
- app.datasource.maximum-pool-size=30
您可以通过强制连接池使用并返回专用实现来解决这个问题,而不是DataSource
。不能在运行时更改实现,但选项列表将是显式的。
下面的示例演示如何创建HikariDataSource
带着DataSourceBuilder
:
- @Bean
- @ConfigurationProperties("app.datasource")
- public HikariDataSource dataSource() {
- return DataSourceBuilder.create().type(HikariDataSource.class).build();
- }
你甚至可以通过利用DataSourceProperties
为您做-也就是说,提供一个默认的嵌入式数据库与一个合理的用户名和密码,如果没有提供URL。您可以很容易地初始化DataSourceBuilder
从任何DataSourceProperties
对象,因此您还可以注入SpringBoot自动创建的DataSource。但是,这将您的配置分为两个名称空间:url
, username
, password
, type
,和driver
在……上面spring.datasource
其余的在您的自定义命名空间上(app.datasource
)为了避免这种情况,您可以重新定义一个自定义。DataSourceProperties
在您的自定义命名空间上,如下面的示例所示:
- @Bean
- @Primary
- @ConfigurationProperties("app.datasource")
- public DataSourceProperties dataSourceProperties() {
- return new DataSourceProperties();
- }
-
- @Bean
- @ConfigurationProperties("app.datasource")
- public HikariDataSource dataSource(DataSourceProperties properties) {
- return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
- .build();
- }
这个设置让你同步默认情况下,SpringBoot为您做了什么,只是选择了一个专用连接池(在代码中),并且在同一个命名空间中公开了它的设置。因为DataSourceProperties
是照顾url
/jdbcUrl
为您翻译,您可以按以下方式配置它:
- app.datasource.url=jdbc:mysql://localhost/test
- app.datasource.username=dbuser
- app.datasource.password=dbpass
- app.datasource.maximum-pool-size=30
![]() |
因为您的自定义配置选择了Hikari, |
见“第29.1节,“配置数据源”“在”SpringBoot特性“部分和DataSourceAutoConfiguration
获取更多详细信息。
如果需要配置多个数据源,则可以应用上一节中描述的相同技巧。但是,您必须标记其中一个DataSource
实例@Primary
,因为道路上的各种自动配置都希望能够按类型获得一个。
如果你自己创造DataSource
,自动配置退出。在下面的示例中,我们提供了精确性与自动配置在主数据源上提供的特性集相同:
@Bean @Primary @ConfigurationProperties("app.datasource.first") public DataSourceProperties firstDataSourceProperties() { return new DataSourceProperties(); } @Bean @Primary @ConfigurationProperties("app.datasource.first") public DataSource firstDataSource() { return firstDataSourceProperties().initializeDataSourceBuilder().build(); } @Bean @ConfigurationProperties("app.datasource.second") public BasicDataSource secondDataSource() { return DataSourceBuilder.create().type(BasicDataSource.class).build(); }
![]() |
|
这两个数据源也为高级自定义绑定。例如,您可以按照以下方式配置它们:
- app.datasource.first.type=com.zaxxer.hikari.HikariDataSource
- app.datasource.first.maximum-pool-size=30
-
- app.datasource.second.url=jdbc:mysql://localhost/test
- app.datasource.second.username=dbuser
- app.datasource.second.password=dbpass
- app.datasource.second.max-total=30
您可以将相同的概念应用于二级DataSource
同样,如以下示例所示:
@Bean @Primary @ConfigurationProperties("app.datasource.first") public DataSourceProperties firstDataSourceProperties() { return new DataSourceProperties(); } @Bean @Primary @ConfigurationProperties("app.datasource.first") public DataSource firstDataSource() { return firstDataSourceProperties().initializeDataSourceBuilder().build(); } @Bean @ConfigurationProperties("app.datasource.second") public DataSourceProperties secondDataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("app.datasource.second") public DataSource secondDataSource() { return secondDataSourceProperties().initializeDataSourceBuilder().build(); }
前面的示例使用SpringBoot在自动配置中使用的相同逻辑在自定义命名空间上配置两个数据源。
Spring数据可以创建@Repository
各种口味的界面。Spring Boot为您处理所有这些,只要那些@Repositories
的包(或子包)中包含。@EnableAutoConfiguration
班级,等级
对于许多应用程序,只需在类路径上放置正确的Spring数据依赖项(有一个spring-boot-starter-data-jpa
对于JPA和一个spring-boot-starter-data-mongodb
(对于MongoDB),并创建一些存储库接口来处理@Entity
物品。示例在JPA样品而MongoDB样本.
Spring Boot试图猜测您@Repository
定义,根据@EnableAutoConfiguration
它找到了。若要获得更多控制,请使用@EnableJpaRepositories
注释(来自SpringDataJPA)。
有关Spring数据的更多信息,请参见春季数据项目页面.
Spring Boot试图猜测您@Entity
定义,根据@EnableAutoConfiguration
它找到了。要获得更多的控制,可以使用@EntityScan
注释,如以下示例所示:
- @Configuration
- @EnableAutoConfiguration
- @EntityScan(basePackageClasses=City.class)
- public class Application {
-
- //...
-
- }
SpringDataJPA已经提供了一些与供应商无关的配置选项(例如用于SQL日志记录的配置选项),SpringBoot将这些选项以及Hibernate的一些选项公开为外部配置属性。其中一些是根据上下文自动检测到的,因此您不需要设置它们。
这,这个,那,那个spring.jpa.hibernate.ddl-auto
是一个特例,因为根据运行时条件,它有不同的默认值。如果使用嵌入式数据库,并且没有架构管理器(如Liquibase或Flyway)处理DataSource
,默认为create-drop
。在所有其他情况下,它默认为none
.
要使用的方言也会根据当前的DataSource
,但你可以spring.jpa.database
如果你想要显式的,并且绕过启动时的检查,那就是你自己。
![]() |
指定 |
下面的示例显示了最常用的设置选项:
- spring.jpa.hibernate.naming.physical-strategy=com.example.MyPhysicalNamingStrategy
- spring.jpa.show-sql=true
此外,spring.jpa.properties.*
作为普通的jpa属性传递(前缀去掉了前缀)。EntityManagerFactory
是被创造出来的。
![]() |
如果需要将高级自定义应用于Hibernate属性,请考虑注册 |
Hibernate使用两种不同的命名策略若要将名称从对象模型映射到相应的数据库名称,请执行以下操作。物理和隐式策略实现的完全限定类名可以通过设置spring.jpa.hibernate.naming.physical-strategy
和spring.jpa.hibernate.naming.implicit-strategy
分别属性。或者,如果ImplicitNamingStrategy
或PhysicalNamingStrategy
bean在应用程序上下文中可用,Hibernate将被自动配置为使用它们。
默认情况下,SpringBoot使用SpringPhysicalNamingStrategy
。此实现提供了与Hibernate 4相同的表结构:所有点都被下划线替换,camel大小写也被下划线替换。默认情况下,所有表名都以小写形式生成,但如果架构需要该标志,则可以重写该标志。
例如,TelephoneNumber
实体映射到telephone_number
桌子
如果您更喜欢使用Hibernate 5的默认设置,请设置以下属性:
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
或者,您可以配置以下bean:
- @Bean
- public PhysicalNamingStrategy physicalNamingStrategy() {
- return new PhysicalNamingStrategyStandardImpl();
- }
看见HibernateJpaAutoConfiguration
和JpaBaseConfiguration
更多细节。
控件的配置完全控制EntityManagerFactory
,您需要添加一个@Bean
名为“实体经理工厂”。Spring Boot自动配置在存在该类型bean的情况下关闭其实体管理器。
即使默认EntityManagerFactory
很好,你需要定义一个新的。否则,该类型的第二个bean的存在将关闭默认值。为了便于操作,您可以使用方便。EntityManagerBuilder
由SpringBoot提供。或者,您可以只在LocalContainerEntityManagerFactoryBean
直接来自SpringORM,如下面的示例所示:
// add two data sources configured as above @Bean public LocalContainerEntityManagerFactoryBean customerEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(customerDataSource()) .packages(Customer.class) .persistenceUnit("customers") .build(); } @Bean public LocalContainerEntityManagerFactoryBean orderEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(orderDataSource()) .packages(Order.class) .persistenceUnit("orders") .build(); }
上面的配置几乎是独立工作的。要完成图片,您需要配置TransactionManagers
对于这两个人EntityManagers
也是如果你把其中一个标记为@Primary
,它可以在默认情况下被捡起。JpaTransactionManager
春靴。另一个必须显式地注入到一个新实例中。或者,您可以使用跨两者的JTA事务管理器。
如果使用Spring数据,则需要配置@EnableJpaRepositories
因此,如以下示例所示:
- @Configuration
- @EnableJpaRepositories(basePackageClasses = Customer.class,
- entityManagerFactoryRef = "customerEntityManagerFactory")
- public class CustomerConfiguration {
- ...
- }
-
- @Configuration
- @EnableJpaRepositories(basePackageClasses = Order.class,
- entityManagerFactoryRef = "orderEntityManagerFactory")
- public class OrderConfiguration {
- ...
- }
persistence.xml
档案Spring Boot将不会搜索或使用META-INF/persistence.xml
默认情况下。如果你喜欢使用传统的persistence.xml
,您需要定义自己的@Bean
类型LocalEntityManagerFactoryBean
(ID为‘ghtyManagerFactory’)并在那里设置持久性单元名。
看见JpaBaseConfiguration
用于默认设置。
Spring数据JPA和Spring Data MONGO都可以自动创建Repository
为您实现。如果它们都存在于类路径中,那么您可能需要做一些额外的配置来告诉SpringBoot要创建哪个存储库。最明确的方法是使用标准的Spring数据@EnableJpaRepositories
和@EnableMongoRepositories
注释,并提供Repository
接口。
还有旗子(spring.data.*.repositories.enabled
和spring.data.*.repositories.type
),可以用来在外部配置中打开或关闭自动配置的存储库。这样做是有用的,例如,如果您想关闭MONGO存储库,但仍然使用自动配置。MongoTemplate
.
对于其他自动配置的Spring数据存储库类型(Elasticearch、Solr和其他类型),存在相同的障碍和相同的特性。要使用它们,请相应地更改注释和标志的名称。
Spring数据REST可以公开Repository
为您提供REST端点的实现,前提是为应用程序启用了SpringMVC。
Spring Boot公开了一组有用的属性(来自spring.data.rest
命名空间),自定义RepositoryRestConfiguration
。如果需要提供其他自定义,则应使用RepositoryRestConfigurer
豆子
![]() |
如果您没有在您的自定义中指定任何订单 |
如果要配置JPA使用的组件,则需要确保在JPA之前初始化该组件。当组件自动配置时,SpringBoot会为您处理这个问题。例如,当Flyway自动配置时,Hibernate被配置为依赖于Flyway,这样Flyway就有机会在Hibernate尝试使用之前初始化数据库。
如果您自己正在配置组件,则可以使用EntityManagerFactoryDependsOnPostProcessor
子类作为设置所需依赖项的方便方法。例如,如果将Hibernate搜索与Elasticearch一起用作索引管理器,则任何EntityManagerFactory
bean必须配置为依赖于elasticsearchClient
bean,如以下示例所示:
- /**
- * {@link EntityManagerFactoryDependsOnPostProcessor} that ensures that
- * {@link EntityManagerFactory} beans depend on the {@code elasticsearchClient} bean.
- */
- @Configuration
- static class ElasticsearchJpaDependencyConfiguration
- extends EntityManagerFactoryDependsOnPostProcessor {
-
- ElasticsearchJpaDependencyConfiguration() {
- super("elasticsearchClient");
- }
-
- }
如果需要对多个数据源使用jOOQ,则应创建自己的DSLContext
每个人。请参阅JooqAutoConfiguration更多细节。
![]() |
特别是, |
根据堆栈的不同,可以不同的方式初始化SQL数据库。当然,如果数据库是一个单独的进程,您也可以手动完成。
JPA具有生成DDL的功能,这些特性可以设置为在数据库启动时运行。这是通过两个外部属性控制的:
spring.jpa.generate-ddl
(Boole)打开和关闭功能,并且与供应商无关。spring.jpa.hibernate.ddl-auto
(Enum)是一个Hibernate特性,它以更细粒度的方式控制行为。本指南后面将对此特性进行更详细的描述。你可以spring.jpa.hibernate.ddl-auto
显式和标准Hibernate属性值为none
, validate
, update
, create
,和create-drop
。SpringBoot根据它是否认为您的数据库是嵌入式的,为您选择一个默认值。默认为create-drop
如果没有检测到架构管理器,则为none
在所有其他情况下。通过查看Connection
类型。hsqldb
, h2
,和derby
是嵌入的,而其他的则不是。在从内存中切换到“真实”数据库时,要小心,不要对新平台中的表和数据的存在做出假设。你要么必须设置ddl-auto
显式或使用其他机制之一初始化数据库。
![]() |
可以通过启用 |
此外,一个名为import.sql
在类路径的根中,如果Hibernate从头创建模式(也就是说,如果ddl-auto
属性设置为create
或create-drop
)这对于演示和测试(如果您很小心的话)都是有用的,但是您可能不希望在生产中的类路径上出现这种情况。它是Hibernate特性(与Spring无关)。
Spring Boot可以自动创建您的架构(DDL脚本)。DataSource
并初始化它(DML脚本)。它从标准根类路径位置加载SQL:schema.sql
和data.sql
分别。此外,SpringBoot还处理schema-${platform}.sql
和data-${platform}.sql
文件(如果存在),其中platform
的价值spring.datasource.platform
。这允许您在必要时切换到特定于数据库的脚本。例如,您可以选择将其设置为数据库的供应商名称(hsqldb
, h2
, oracle
, mysql
, postgresql
等等)。
![]() |
Spring Boot自动创建嵌入式系统的架构。 |
默认情况下,SpringBoot启用SpringJDBC初始化程序的故障快速特性。这意味着,如果脚本导致异常,应用程序将无法启动。您可以通过设置spring.datasource.continue-on-error
.
![]() |
在基于jpa的应用程序中,您可以选择让Hibernate创建模式或使用 |
如果您使用SpringBatch,则它附带了用于大多数流行数据库平台的SQL初始化脚本。SpringBoot可以检测数据库类型,并在启动时执行这些脚本。如果使用嵌入式数据库,默认情况下会发生这种情况。您还可以为任何数据库类型启用它,如以下示例所示:
spring.batch.initialize-schema=always
还可以通过设置spring.batch.initialize-schema=never
.
SpringBoot支持两个更高级的迁移工具:立交桥和液基.
若要在启动时自动运行Flyway数据库迁移,请添加org.flywaydb:flyway-core
到你的类路径。
迁移是表单中的脚本。V<VERSION>__<NAME>.sql
(与<VERSION>
以下划线分隔的版本,如“1”或“2_1”)。默认情况下,它们位于一个名为classpath:db/migration
,但是您可以通过设置spring.flyway.locations
。这是由一个或多个逗号分隔的列表。classpath:
或filesystem:
地点。例如,下面的配置将在默认类路径位置和/opt/migration
目录:
spring.flyway.locations=classpath:db/migration,filesystem:/opt/migration
您还可以添加一个特殊的{vendor}
占位符使用特定于供应商的脚本。假设如下:
spring.flyway.locations=classpath:db/migration/{vendor}
而不是使用db/migration
,上面的配置根据数据库的类型设置要使用的文件夹(如db/migration/mysql
(用于MySQL)。支持的数据库列表可在DatabaseDriver
.
有关可用设置(如架构和其他设置)的详细信息,请参见天桥核心中的Flyway类。此外,SpringBoot还提供了一组小的属性(在FlywayProperties
),可用于禁用迁移或关闭位置检查。弹簧启动呼叫Flyway.migrate()
若要执行数据库迁移,请执行以下操作。如果您想要更多的控制,请提供一个@Bean
实现FlywayMigrationStrategy
.
Fidway支持SQL和Java回调。若要使用基于sql的回调,请将回调脚本放在classpath:db/migration
文件夹。若要使用基于Java的回调,请创建一个或多个实现Callback
。任何这样的bean都会自动注册到Flyway
。它们可以通过使用@Order
或通过实施Ordered
。实现不推荐的bean。FlywayCallback
接口也可以被检测到,但是它们不能与Callback
豆子
在默认情况下,Flyway自动完成以下操作:@Primary
) DataSource
在您的上下文中,并将其用于迁移。如果你想用不同的DataSource
,您可以创建一个并标记其@Bean
如@FlywayDataSource
。如果您这样做并想要两个数据源,请记住创建另一个数据源并将其标记为@Primary
。或者,您也可以使用Flyway的本地DataSource
通过设置spring.flyway.[url,user,password]
在外部属性中。设置任一个spring.flyway.url
或spring.flyway.user
就足以使天桥使用它自己的DataSource
。如果没有设置这三个属性中的任何一个,则表示其等效值。spring.datasource
财产将被使用。
有一个飞道样本这样你就能看到如何安排好一切。
您还可以使用Flyway为特定方案提供数据。例如,可以将特定于测试的迁移放在src/test/resources
只有当应用程序开始进行测试时,它们才会运行。此外,您还可以使用特定于配置文件的配置来自定义。spring.flyway.locations
因此,某些迁移仅在特定配置文件处于活动状态时才运行。例如,在application-dev.properties
,可以指定以下设置:
spring.flyway.locations=classpath:/db/migration,classpath:/dev/db/migration
使用该设置,迁移到dev/db/migration
只在dev
侧写是活动的。
若要在启动时自动运行Liquibase数据库迁移,请添加org.liquibase:liquibase-core
到你的类路径。
默认情况下,主更改日志是从db/changelog/db.changelog-master.yaml
,但是您可以通过设置spring.liquibase.change-log
。除了YAML之外,Liquibase还支持JSON、XML和SQL更改日志格式。
在默认情况下,Liquibase提供了以下内容:@Primary
) DataSource
在您的上下文中,并将其用于迁移。如果您需要使用不同的DataSource
,您可以创建一个并标记其@Bean
如@LiquibaseDataSource
。如果您这样做并且需要两个数据源,请记住创建另一个数据源并将其标记为@Primary
。或者,您也可以使用Liquibase的本机DataSource
通过设置spring.liquibase.[url,user,password]
在外部属性中。设置任一个spring.liquibase.url
或spring.liquibase.user
足以使Liquibase使用它自己的DataSource
。如果没有设置这三个属性中的任何一个,则表示其等效值。spring.datasource
财产将被使用。
看见LiquibaseProperties
有关可用设置(如上下文、默认架构和其他设置)的详细信息。
有一个液相样品这样你就能看到如何安排好一切。
SpringBoot提供了许多启动程序,包括消息传递。本节回答了在SpringBoot中使用消息传递时出现的问题。
如果JMS代理不支持事务处理会话,则必须完全禁用对事务的支持。如果你自己创造JmsListenerContainerFactory
,没有什么可做的,因为在默认情况下,它不能被处理。如果您想使用DefaultJmsListenerContainerFactoryConfigurer
要重用SpringBoot的默认设置,可以禁用事务会话,如下所示:
- @Bean
- public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(
- ConnectionFactory connectionFactory,
- DefaultJmsListenerContainerFactoryConfigurer configurer) {
- DefaultJmsListenerContainerFactory listenerFactory =
- new DefaultJmsListenerContainerFactory();
- configurer.configure(listenerFactory, connectionFactory);
- listenerFactory.setTransactionManager(null);
- listenerFactory.setSessionTransacted(false);
- return listenerFactory;
- }
前面的示例覆盖默认工厂,并且它应该应用于应用程序定义的任何其他工厂(如果有的话)。
本节回答了在SpringBoot中使用SpringBatch时出现的问题。
![]() |
默认情况下,批处理应用程序需要 |
有关SpringBatch的更多信息,请参见春季批处理项目页面.
通过添加@EnableBatchProcessing
(从SpringBatch)上下文中的某个地方。
默认情况下,它执行全 Jobs
在启动时的应用程序上下文中(请参见JobLauncherCommandLineRunner详细情况)。您可以通过指定spring.batch.job.names
(这需要一个以逗号分隔的作业名称模式列表)。
如果应用程序上下文包括JobRegistry
,工作spring.batch.job.names
在注册表中查找,而不是从上下文中自动查找。这是更复杂系统的常见模式,在子上下文中定义多个作业并集中注册。
看见BatchAutoConfiguration和@EnableBatchProcessing更多细节。
弹簧启动包括弹簧启动执行器。本节回答使用它时经常出现的问题。
在独立应用程序中,Actuator HTTP端口默认为与主HTTP端口相同。若要使应用程序侦听其他端口,请设置外部属性:management.server.port
。若要侦听完全不同的网络地址(例如,当您有用于管理的内部网络和用于用户应用程序的外部网络时),您还可以设置management.server.address
到服务器能够绑定到的有效IP地址。
有关更多细节,请参见ManagementServerProperties
源代码和“第53.2节,“自定义管理服务器端口”在“生产准备功能”部分。
当您遇到服务器错误时,SpringBoot会安装一个‘Whitelabel’错误页面,当您在浏览器客户机中看到该页面时(使用JSON和其他媒体类型的机器客户端应该会看到正确的错误代码的合理响应)。
![]() |
集 |
使用自己的模板技术覆盖错误页取决于您使用的模板技术。例如,如果使用Thymeleaf,可以添加error.html
模板。如果使用FreeMarker,则可以添加error.ftl
模板。一般来说,你需要一个View
名称为error
或者是@Controller
处理/error
路径。除非您替换了一些默认配置,否则您应该找到BeanNameViewResolver
在你的ApplicationContext
,所以@Bean
命名error
是一种简单的方法。看见ErrorMvcAutoConfiguration
寻找更多的选择。
另见关于“错误处理“有关如何在servlet容器中注册处理程序的详细信息。
返回的信息env
和configprops
端点可能有些敏感,因此匹配特定模式的键在默认情况下会被清除(即它们的值被替换为).
Spring Boot对这些键使用合理的缺省值:例如,以“密码”、“秘密”、“键”或“令牌”结尾的任何键都会被净化。也可以使用正则表达式,例如credentials.
对任何保存单词的键进行消毒credentials
作为钥匙的一部分。
可以使用management.endpoint.env.keys-to-sanitize
和management.endpoint.configprops.keys-to-sanitize
分别。
本节讨论使用SpringBoot时的安全性问题,包括在SpringBoot中使用SpringSecurity时出现的问题。
有关Spring安全性的更多信息,请参见Spring安全项目页面.
如果定义@Configuration
带着WebSecurityConfigurerAdapter
在您的应用程序中,它关闭了SpringBoot中默认的Webapp安全设置。
如果你提供一个@Bean
类型AuthenticationManager
, AuthenticationProvider
,或UserDetailsService
,默认@Bean
为InMemoryUserDetailsManager
未创建,因此可以使用完整的SpringSecurity功能集(如各种身份验证选项).
添加用户帐户的最简单方法是提供您自己的帐户。UserDetailsService
豆子
确保所有主要端点只能在HTTPS上使用是任何应用程序的一项重要工作。如果使用Tomcat作为servlet容器,那么SpringBoot添加了Tomcat自己的RemoteIpValve
如果它检测到某些环境设置,则会自动执行,并且您应该能够依赖于HttpServletRequest
报告它是否安全(即使是处理实际SSL终端的代理服务器的下游)。标准行为取决于是否存在某些请求头(x-forwarded-for
和x-forwarded-proto
),其名称是传统的,因此它应该适用于大多数前端代理。您可以通过添加一些条目来打开阀门。application.properties
,如以下示例所示:
- server.tomcat.remote-ip-header=x-forwarded-for
- server.tomcat.protocol-header=x-forwarded-proto
(上述任何一项属性的存在均会在阀门上开关。或者,您可以添加RemoteIpValve
通过添加TomcatServletWebServerFactory
)
若要配置Spring安全性以要求为所有(或部分)请求提供安全通道,请考虑添加自己的WebSecurityConfigurerAdapter
这将添加以下内容HttpSecurity
配置:
- @Configuration
- public class SslWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- // Customize the application security
- http.requiresChannel().anyRequest().requiresSecure();
- }
-
- }
弹簧启动支持热交换。本节回答有关它如何工作的问题。
热重装有几种选择。推荐的方法是使用spring-boot-devtools
,因为它提供了额外的开发时特性,例如支持快速应用程序重新启动和LiveReload以及合理的开发时配置(例如模板缓存)。DevTools通过监视更改的类路径来工作。这意味着必须“构建”静态资源更改才能使更改生效。默认情况下,在Eclipse中保存更改时会自动发生这种情况。在IntelliJIDEA中,makeProject命令触发必要的构建。由于默认重新启动排除,对静态资源的更改不会触发应用程序的重新启动。然而,他们确实触发了一个活的重装。
或者,在IDE中运行(特别是在调试上)是一种很好的开发方法(所有现代IDE都允许重新加载静态资源,并且通常还允许Java类更改的热交换)。
最后,Maven和Gradle插件可以配置(请参阅addResources
属性),以支持从命令行直接从源重新加载静态文件。如果您使用更高级别的工具编写该代码,则可以在外部css/js编译器过程中使用该代码。
SpringBoot支持的大多数模板技术包括一个禁用缓存的配置选项(本文档后面将介绍)。如果您使用spring-boot-devtools
模块,这些属性是自动配置在开发的时候。
如果您使用Thymeleaf,设置spring.thymeleaf.cache
到false
。看见ThymeleafAutoConfiguration
用于其他Thymeleaf自定义选项。
如果使用FreeMarker,则设置spring.freemarker.cache
到false
。看见FreeMarkerAutoConfiguration
用于其他FreeMarker自定义选项。
如果使用Groovy模板,则设置spring.groovy.template.cache
到false
。看见GroovyTemplateAutoConfiguration
用于其他Groovy自定义选项。
这,这个,那,那个spring-boot-devtools
模块包括对自动应用程序重新启动的支持。虽然速度不如诸如贾贝尔它通常比“冷启动”要快得多。在研究本文档后面讨论的一些更复杂的重新加载选项之前,您可能应该尝试一下。
有关详细信息,请参阅第20章,开发工具部分。
许多现代IDE(Eclipse、IDEA等)支持字节码的热交换。因此,如果您所做的更改不影响类或方法签名,那么它应该在没有副作用的情况下干净地重新加载。
SpringBoot包括Maven和Gradle的构建插件。本节回答有关这些插件的常见问题。
Maven插件和Gradle插件都允许生成包含项目坐标、名称和版本的构建信息。插件还可以配置为通过配置添加附加属性。如果存在这样的文件,SpringBoot将自动配置BuildProperties
豆子
若要使用Maven生成信息,请为build-info
目标,如以下示例所示:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>2.1.0.BUILD-SNAPSHOT</version>
- <executions>
- <execution>
- <goals>
- <goal>build-info</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>

![]() |
见Spring Boot Maven插件文档更多细节。 |
下面的示例对Gradle也是这样做的:
- springBoot {
- buildInfo()
- }
![]() |
见Spring Boot Gradle插件文档更多细节。 |
Maven和Gradle都允许生成git.properties
文件中包含有关git
构建项目时的源代码存储库。
对于Maven用户,spring-boot-starter-parent
pom包括预先配置的插件,以生成git.properties
档案。要使用它,请将以下声明添加到POM中:
- <build>
- <plugins>
- <plugin>
- <groupId>pl.project13.maven</groupId>
- <artifactId>git-commit-id-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
通过使用gradle-git-properties
插件,如以下示例所示:
- plugins {
- id "com.gorylenko.gradle-git-properties" version "1.5.1"
- }
![]() |
提交时间 |
如果使用直接或间接从spring-boot-dependencies
(例如,spring-boot-starter-parent
)但是,如果要覆盖特定的第三方依赖项,则可以添加适当的<properties>
元素。浏览spring-boot-dependencies
获取完整属性列表的pom。例如,选择不同的slf4j
版本,您将添加以下属性:
- <properties>
- <slf4j.version>1.7.5<slf4j.version>
- </properties>
![]() |
只有当您的Maven项目继承(直接或间接)从 |
![]() |
每个SpringBoot发行版都根据这组特定的第三方依赖项进行设计和测试。覆盖版本可能会导致兼容性问题。 |
若要重写Gradle中的依赖项版本,请参见本节Gradle插件的文档。
这,这个,那,那个spring-boot-maven-plugin
可以用来创建一个可执行的“FAT”JAR。如果您使用spring-boot-starter-parent
POM,您可以声明插件,您的JAR被重新打包如下:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
如果不使用父POM,则仍然可以使用该插件。但是,还必须添加一个<executions>
一节如下:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>2.1.0.BUILD-SNAPSHOT</version>
- <executions>
- <execution>
- <goals>
- <goal>repackage</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>

见插件文档完整的使用细节。
与WAR文件一样,SpringBoot应用程序不打算用作依赖项。如果应用程序包含要与其他项目共享的类,建议的方法是将代码移动到单独的模块中。然后,应用程序和其他项目可以依赖独立的模块。
如果不能按照上面的建议重新排列代码,则必须配置SpringBoot的Maven和Gradle插件,以生成适合作为依赖项使用的单独工件。可执行存档不能用作依赖项,因为可执行JAR格式中的包应用程序类。BOOT-INF/classes
。这意味着当可执行JAR作为依赖项使用时,无法找到它们。
要生成这两个工件,一个可以用作依赖项,另一个是可执行的,必须指定一个分类器。此分类器应用于可执行存档的名称,保留默认存档作为依赖项使用。
若要配置分类器,请执行以下操作exec
在Maven中,可以使用以下配置:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <classifier>exec</classifier>
- </configuration>
- </plugin>
- </plugins>
- </build>
可执行JAR中的大多数嵌套库不需要解压缩才能运行。然而,某些图书馆可能会有问题。例如,JRuby包含自己的嵌套JAR支持,它假定jruby-complete.jar
始终可以直接作为文件使用。
为了处理任何有问题的库,您可以在可执行JAR第一次运行时将特定的嵌套JAR解压到“temp文件夹”。
例如,为了指示应该通过使用Maven插件将JRuby标记为解打包,您可以添加以下配置:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <requiresUnpack>
- <dependency>
- <groupId>org.jruby</groupId>
- <artifactId>jruby-complete</artifactId>
- </dependency>
- </requiresUnpack>
- </configuration>
- </plugin>
- </plugins>
- </build>

通常,如果将可执行文件和不可执行的JAR作为两个单独的构建产品,则可执行版本具有库JAR中不需要的附加配置文件。例如,application.yml
配置文件可能被排除在不可执行的JAR中。
在Maven中,可执行的JAR必须是主要工件,您可以为库添加一个分类JAR,如下所示:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <id>lib</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>lib</classifier>
- <excludes>
- <exclude>application.yml</exclude>
- </excludes>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>

若要将远程调试器附加到用Maven启动的SpringBoot应用程序,可以使用jvmArguments
的属性Maven插件.
看见这个例子更多细节。
spring-boot-antlib
要使用Ant进行构建,您需要获取依赖项,编译,然后创建一个JAR或WAR存档。若要使其可执行,可以使用spring-boot-antlib
模块或您可以按照以下说明操作:
BOOT-INF/classes
目录。如果您正在构建WAR,请将应用程序的类打包到嵌套的WEB-INF/classes
和往常一样。BOOT-INF/lib
用于JAR或WEB-INF/lib
为了一场战争。记住不若要压缩存档中的条目,请执行以下操作。provided
(嵌入式容器)嵌套中的依赖项BOOT-INF/lib
用于JAR或WEB-INF/lib-provided
为了一场战争。记住不若要压缩存档中的条目,请执行以下操作。spring-boot-loader
类位于存档的根目录下(以便Main-Class
(可供使用)。JarLauncher
(对于JAR文件)作为Main-Class
属性,并将它需要的其他属性指定为清单项-主要是通过设置Start-Class
财产。下面的示例演示如何使用Ant构建可执行存档:
- <target name="build" depends="compile">
- <jar destfile="target/${ant.project.name}-${spring-boot.version}.jar" compress="false">
- <mappedresources>
- <fileset dir="target/classes" />
- <globmapper from="*" to="BOOT-INF/classes/*"/>
- </mappedresources>
- <mappedresources>
- <fileset dir="src/main/resources" erroronmissingdir="false"/>
- <globmapper from="*" to="BOOT-INF/classes/*"/>
- </mappedresources>
- <mappedresources>
- <fileset dir="${lib.dir}/runtime" />
- <globmapper from="*" to="BOOT-INF/lib/*"/>
- </mappedresources>
- <zipfileset src="${lib.dir}/loader/spring-boot-loader-jar-${spring-boot.version}.jar" />
- <manifest>
- <attribute name="Main-Class" value="org.springframework.boot.loader.JarLauncher" />
- <attribute name="Start-Class" value="${start-class}" />
- </manifest>
- </jar>
- </target>

这,这个,那,那个蚂蚁样本有一个build.xml
文件中带有manual
如果使用以下命令运行该任务,则该任务将工作:
$ ant -lib <folder containing ivy-2.2.jar> clean manual
然后可以使用以下命令运行应用程序:
$ java -jar target/*.jar
SpringBoot支持传统的部署以及更现代的部署形式。本节回答有关传统部署的常见问题。
![]() |
由于SpringWebFlux并不严格依赖ServletAPI,而且应用程序默认部署在嵌入式反应堆Netty服务器上,因此WebFlux应用程序不支持WAR部署。 |
生成可部署的WAR文件的第一步是提供SpringBootServletInitializer
类并重写其configure
方法。这样做可以利用SpringFramework的Servlet3.0支持,并允许您在servlet容器启动应用程序时配置它。通常,您应该更新应用程序的主类以扩展SpringBootServletInitializer
,如以下示例所示:
- @SpringBootApplication
- public class Application extends SpringBootServletInitializer {
-
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- return application.sources(Application.class);
- }
-
- public static void main(String[] args) throws Exception {
- SpringApplication.run(Application.class, args);
- }
-
- }
下一步是更新构建配置,以便项目生成一个WAR文件,而不是JAR文件。如果你用Maven和spring-boot-starter-parent
(为您配置Maven的WAR插件),您所需要做的就是修改pom.xml
若要将包装更改为WAR,请执行以下操作:
<packaging>war</packaging>
如果使用Gradle,则需要修改build.gradle
要将WAR插件应用于该项目,如下所示:
apply plugin: 'war'
该过程的最后一步是确保嵌入的servlet容器不干扰部署WAR文件的servlet容器。要做到这一点,您需要将嵌入的servlet容器依赖标记为提供。
如果使用Maven,下面的示例将servlet容器(在本例中为Tomcat)标记为提供:
- <dependencies>
- <!-- … -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- <scope>provided</scope>
- </dependency>
- <!-- … -->
- </dependencies>
如果使用Gradle,下面的示例将servlet容器(在本例中为Tomcat)标记为提供:
- dependencies {
- // …
- providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
- // …
- }
![]() |
|
如果您使用弹簧启动构建工具,将所提供的嵌入式servlet容器依赖项标记为可执行的WAR文件,所提供的依赖项打包在lib-provided
目录。这意味着,除了部署到servlet容器之外,还可以使用java -jar
在命令行上。
![]() |
查看SpringBoot的示例应用程序基于maven的示例之前描述的配置。 |
对于非Web应用程序,应该很容易将现有的Spring应用程序转换为SpringBoot应用程序。要做到这一点,请丢弃创建ApplicationContext
并将其替换为调用SpringApplication
或SpringApplicationBuilder
。SpringMVC Web应用程序通常可以首先创建可部署的WAR应用程序,然后再将其迁移到可执行的WAR或JAR中。见关于将罐子转换为战争的入门指南.
通过扩展SpringBootServletInitializer
(例如,在一个名为Application
)和添加SpringBoot@SpringBootApplication
注释,使用类似于下面示例中所示的代码:
- @SpringBootApplication
- public class Application extends SpringBootServletInitializer {
-
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- // Customize the application or call application.sources(...) to add sources
- // Since our example is itself a @Configuration class (via @SpringBootApplication)
- // we actually don't need to override this method.
- return application;
- }
-
- }
记住,不管你在sources
只是一个春天ApplicationContext
。正常情况下,任何已经起作用的东西都应该在这里起作用。以后可能会有一些bean可以删除,让SpringBoot为它们提供自己的缺省值,但是在您需要这样做之前,应该可以使用一些bean。
静态资源可以移动到/public
(或/static
或/resources
或/META-INF/resources
)在类路径根中。同样适用于messages.properties
(Spring Boot在类路径的根中自动检测到的)。
香草春的使用DispatcherServlet
Spring安全性不需要进一步的更改。如果应用程序中有其他特性(例如,使用其他servlet或过滤器),则可能需要向您的Application
上下文中替换web.xml
,如下:
@Bean
类型Servlet
或ServletRegistrationBean
将该bean安装在容器中,就好像它是<servlet/>
和<servlet-mapping/>
在……里面web.xml
.@Bean
类型Filter
或FilterRegistrationBean
行为类似(作为<filter/>
和<filter-mapping/>
).ApplicationContext
在xml文件中,可以通过@ImportResource
在你的Application
。或者,已经大量使用注释配置的简单情况可以在以下几行中重新创建:@Bean
定义。WAR文件工作后,可以通过添加main
方法对您的Application
,如以下示例所示:
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
![]() |
如果您打算以WAR或可执行应用程序的形式启动应用程序,则需要在两个都可用的方法中共享构建器的自定义。 |
应用程序可以分为多个类别:
web.xml
.web.xml
.所有这些都应该适合翻译,但每一种都可能需要稍微不同的技术。
Servlet3.0+应用程序如果已经使用SpringServlet3.0+初始化器支持类,可能会很容易地进行转换。通常,现有代码中的所有代码WebApplicationInitializer
可以移动到SpringBootServletInitializer
。如果现有应用程序有多个ApplicationContext
(例如,如果它使用AbstractDispatcherServletInitializer
)然后您就可以将所有上下文源组合成一个SpringApplication
。您可能遇到的主要复杂问题是,如果组合不起作用,并且需要维护上下文层次结构。见关于构建层次结构的条目举个例子。包含web特定功能的现有父上下文通常需要拆分,以便所有ServletContextAware
组件位于子上下文中。
还不是Spring应用程序的应用程序可以转换为SpringBoot应用程序,前面提到的指导可能会有所帮助。但是,您可能还会遇到问题。在这种情况下,我们建议使用spring-boot
.
要将SpringBoot应用程序部署到WebLogic,必须确保servlet初始化程序直接实施器WebApplicationInitializer
(即使从已经实现它的基类扩展)。
WebLogic的典型初始化程序应该类似于以下示例:
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
- import org.springframework.web.WebApplicationInitializer;
-
- @SpringBootApplication
- public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
-
- }
如果使用Logback,还需要告诉WebLogic更喜欢打包版本,而不是与服务器一起预装的版本。可以通过添加WEB-INF/weblogic.xml
文件的内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <wls:weblogic-web-app
- xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
- http://xmlns.oracle.com/weblogic/weblogic-web-app
- http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
- <wls:container-descriptor>
- <wls:prefer-application-packages>
- <wls:package-name>org.slf4j</wls:package-name>
- </wls:prefer-application-packages>
- </wls:container-descriptor>
- </wls:weblogic-web-app>
默认情况下,SpringBootStart(spring-boot-starter-data-redis
)使用生菜。您需要排除该依赖项,并包括吉迪斯取而代之的是一个。SpringBoot管理这些依赖项,以帮助尽可能简化这个过程。
下面的示例演示如何在Maven中这样做:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- <exclusions>
- <exclusion>
- <groupId>io.lettuce</groupId>
- <artifactId>lettuce-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- </dependency>
下面的示例演示如何在Gradle中这样做:
- configurations {
- compile.exclude module: "lettuce"
- }
-
- dependencies {
- compile("redis.clients:jedis")
- // ...
- }
可以在您的application.properties
文件,在你的application.yml
文件,或作为命令行开关。本附录提供了常用SpringBoot属性的列表,以及对使用这些属性的底层类的引用。
![]() |
属性贡献可以来自类路径上的其他JAR文件,因此您不应该认为这是一个详尽的列表。此外,您还可以定义自己的属性。 |
![]() |
此示例文件仅作为指南。做不复制并粘贴整个内容到应用程序中。相反,只需选择所需的属性。 |
# =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =================================================================== # ---------------------------------------- # CORE PROPERTIES # ---------------------------------------- debug=false # Enable debug logs. trace=false # Enable trace logs. # LOGGING logging.config= # Location of the logging configuration file. For instance, `classpath:logback.xml` for Logback. logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions. logging.file= # Log file name (for instance, `myapp.log`). Names can be an exact location or relative to the current directory. logging.file.max-history=0 # Maximum of archive log files to keep. Only supported with the default logback setup. logging.file.max-size=10MB # Maximum log file size. Only supported with the default logback setup. logging.group.*= # Log groups to quickly change multiple loggers at the same time. For instance, `logging.level.db=org.hibernate,org.springframework.jdbc`. logging.level.*= # Log levels severity mapping. For instance, `logging.level.org.springframework=DEBUG`. logging.path= # Location of the log file. For instance, `/var/log`. logging.pattern.console= # Appender pattern for output to the console. Supported only with the default Logback setup. logging.pattern.dateformat=yyyy-MM-dd HH:mm:ss.SSS # Appender pattern for log date format. Supported only with the default Logback setup. logging.pattern.file= # Appender pattern for output to a file. Supported only with the default Logback setup. logging.pattern.level=%5p # Appender pattern for log level. Supported only with the default Logback setup. logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized. # AOP spring.aop.auto=true # Add @EnableAspectJAutoProxy. spring.aop.proxy-target-class=true # Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false). # IDENTITY (ContextIdApplicationContextInitializer) spring.application.name= # Application name. # ADMIN (SpringApplicationAdminJmxAutoConfiguration) spring.application.admin.enabled=false # Whether to enable admin features for the application. spring.application.admin.jmx-name=org.springframework.boot:type=Admin,name=SpringApplication # JMX name of the application admin MBean. # AUTO-CONFIGURATION spring.autoconfigure.exclude= # Auto-configuration classes to exclude. # BANNER spring.banner.charset=UTF-8 # Banner file encoding. spring.banner.location=classpath:banner.txt # Banner text resource location. spring.banner.image.location=classpath:banner.gif # Banner image file location (jpg or png can also be used). spring.banner.image.width=76 # Width of the banner image in chars. spring.banner.image.height= # Height of the banner image in chars (default based on image height). spring.banner.image.margin=2 # Left hand image margin in chars. spring.banner.image.invert=false # Whether images should be inverted for dark terminal themes. # SPRING CORE spring.beaninfo.ignore=true # Whether to skip search of BeanInfo classes. # SPRING CACHE (CacheProperties) spring.cache.cache-names= # Comma-separated list of cache names to create if supported by the underlying cache manager. spring.cache.caffeine.spec= # The spec to use to create caches. See CaffeineSpec for more details on the spec format. spring.cache.couchbase.expiration= # Entry expiration. By default the entries never expire. Note that this value is ultimately converted to seconds. spring.cache.ehcache.config= # The location of the configuration file to use to initialize EhCache. spring.cache.infinispan.config= # The location of the configuration file to use to initialize Infinispan. spring.cache.jcache.config= # The location of the configuration file to use to initialize the cache manager. spring.cache.jcache.provider= # Fully qualified name of the CachingProvider implementation to use to retrieve the JSR-107 compliant cache manager. Needed only if more than one JSR-107 implementation is available on the classpath. spring.cache.redis.cache-null-values=true # Allow caching null values. spring.cache.redis.key-prefix= # Key prefix. spring.cache.redis.time-to-live= # Entry expiration. By default the entries never expire. spring.cache.redis.use-key-prefix=true # Whether to use the key prefix when writing to Redis. spring.cache.type= # Cache type. By default, auto-detected according to the environment. # SPRING CONFIG - using environment property only (ConfigFileApplicationListener) spring.config.additional-location= # Config file locations used in addition to the defaults. spring.config.location= # Config file locations that replace the defaults. spring.config.name=application # Config file name. # HAZELCAST (HazelcastProperties) spring.hazelcast.config= # The location of the configuration file to use to initialize Hazelcast. # PROJECT INFORMATION (ProjectInfoProperties) spring.info.build.location=classpath:META-INF/build-info.properties # Location of the generated build-info.properties file. spring.info.git.location=classpath:git.properties # Location of the generated git.properties file. # JMX spring.jmx.default-domain= # JMX domain name. spring.jmx.enabled=true # Expose management beans to the JMX domain. spring.jmx.server=mbeanServer # MBeanServer bean name. spring.jmx.unique-names=false # Whether unique runtime object names should be ensured. # Email (MailProperties) spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding. spring.mail.host= # SMTP server host. For instance, `smtp.example.com`. spring.mail.jndi-name= # Session JNDI name. When set, takes precedence over other Session settings. spring.mail.password= # Login password of the SMTP server. spring.mail.port= # SMTP server port. spring.mail.properties.*= # Additional JavaMail Session properties. spring.mail.protocol=smtp # Protocol used by the SMTP server. spring.mail.test-connection=false # Whether to test that the mail server is available on startup. spring.mail.username= # Login user of the SMTP server. # APPLICATION SETTINGS (SpringApplication) spring.main.allow-bean-definition-overriding=false # Whether bean definition overriding, by registering a definition with the same name as an existing definition, is allowed. spring.main.banner-mode=console # Mode used to display the banner when the application runs. spring.main.sources= # Sources (class names, package names, or XML resource locations) to include in the ApplicationContext. spring.main.web-application-type= # Flag to explicitly request a specific type of web application. If not set, auto-detected based on the classpath. # FILE ENCODING (FileEncodingApplicationListener) spring.mandatory-file-encoding= # Expected character encoding the application must use. # INTERNATIONALIZATION (MessageSourceProperties) spring.messages.always-use-message-format=false # Whether to always apply the MessageFormat rules, parsing even messages without arguments. spring.messages.basename=messages # Comma-separated list of basenames (essentially a fully-qualified classpath location), each following the ResourceBundle convention with relaxed support for slash based locations. spring.messages.cache-duration= # Loaded resource bundle files cache duration. When not set, bundles are cached forever. If a duration suffix is not specified, seconds will be used. spring.messages.encoding=UTF-8 # Message bundles encoding. spring.messages.fallback-to-system-locale=true # Whether to fall back to the system Locale if no files for a specific Locale have been found. spring.messages.use-code-as-default-message=false # Whether to use the message code as the default message instead of throwing a "NoSuchMessageException". Recommended during development only. # OUTPUT spring.output.ansi.enabled=detect # Configures the ANSI output. # PID FILE (ApplicationPidFileWriter) spring.pid.fail-on-write-error= # Fails if ApplicationPidFileWriter is used but it cannot write the PID file. spring.pid.file= # Location of the PID file to write (if ApplicationPidFileWriter is used). # PROFILES spring.profiles.active= # Comma-separated list of active profiles. Can be overridden by a command line switch. spring.profiles.include= # Unconditionally activate the specified comma-separated list of profiles (or list of profiles if using YAML). # QUARTZ SCHEDULER (QuartzProperties) spring.quartz.auto-startup=true # Whether to automatically start the scheduler after initialization. spring.quartz.jdbc.comment-prefix=-- # Prefix for single-line comments in SQL initialization scripts. spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema. spring.quartz.job-store-type=memory # Quartz job store type. spring.quartz.overwrite-existing-jobs=false # Whether configured jobs should overwrite existing job definitions. spring.quartz.properties.*= # Additional Quartz Scheduler properties. spring.quartz.scheduler-name=quartzScheduler # Name of the scheduler. spring.quartz.startup-delay=0s # Delay after which the scheduler is started once initialization completes. spring.quartz.wait-for-jobs-to-complete-on-shutdown=false # Whether to wait for running jobs to complete on shutdown. # REACTOR (ReactorCoreProperties) spring.reactor.stacktrace-mode.enabled=false # Whether Reactor should collect stacktrace information at runtime. # SENDGRID (SendGridAutoConfiguration) spring.sendgrid.api-key= # SendGrid API key. spring.sendgrid.proxy.host= # SendGrid proxy host. spring.sendgrid.proxy.port= # SendGrid proxy port. # TASK EXECUTION (TaskExecutionProperties) spring.task.execution.pool.allow-core-thread-timeout=true # Whether core threads are allowed to time out. This enables dynamic growing and shrinking of the pool. spring.task.execution.pool.core-size=8 # Core number of threads. spring.task.execution.pool.keep-alive=60s # Time limit for which threads may remain idle before being terminated. spring.task.execution.pool.max-size= # Maximum allowed number of threads. If tasks are filling up the queue, the pool can expand up to that size to accommodate the load. Ignored if the queue is unbounded. spring.task.execution.pool.queue-capacity= # Queue capacity. An unbounded capacity does not increase the pool and therefore ignores the "max-size" property. spring.task.execution.thread-name-prefix=task- # Prefix to use for the names of newly created threads. # TASK SCHEDULING (TaskSchedulingProperties) spring.task.scheduling.pool.size=1 # Maximum allowed number of threads. spring.task.scheduling.thread-name-prefix=scheduling- # Prefix to use for the names of newly created threads. # ---------------------------------------- # WEB PROPERTIES # ---------------------------------------- # EMBEDDED SERVER CONFIGURATION (ServerProperties) server.address= # Network address to which the server should bind. server.compression.enabled=false # Whether response compression is enabled. server.compression.excluded-user-agents= # List of user-agents to exclude from compression. server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json,application/xml # Comma-separated list of MIME types that should be compressed. server.compression.min-response-size=2KB # Minimum "Content-Length" value that is required for compression to be performed. server.connection-timeout= # Time that connectors wait for another HTTP request before closing the connection. When not set, the connector's container-specific default is used. Use a value of -1 to indicate no (that is, an infinite) timeout. server.error.include-exception=false # Include the "exception" attribute. server.error.include-stacktrace=never # When to include a "stacktrace" attribute. server.error.path=/error # Path of the error controller. server.error.whitelabel.enabled=true # Whether to enable the default error page displayed in browsers in case of a server error. server.http2.enabled=false # Whether to enable HTTP/2 support, if the current environment supports it. server.jetty.acceptors=-1 # Number of acceptor threads to use. When the value is -1, the default, the number of acceptors is derived from the operating environment. server.jetty.accesslog.append=false # Append to log. server.jetty.accesslog.date-format=dd/MMM/yyyy:HH:mm:ss Z # Timestamp format of the request log. server.jetty.accesslog.enabled=false # Enable access log. server.jetty.accesslog.extended-format=false # Enable extended NCSA format. server.jetty.accesslog.file-date-format= # Date format to place in log file name. server.jetty.accesslog.filename= # Log filename. If not specified, logs redirect to "System.err". server.jetty.accesslog.locale= # Locale of the request log. server.jetty.accesslog.log-cookies=false # Enable logging of the request cookies. server.jetty.accesslog.log-latency=false # Enable logging of request processing time. server.jetty.accesslog.log-server=false # Enable logging of the request hostname. server.jetty.accesslog.retention-period=31 # Number of days before rotated log files are deleted. server.jetty.accesslog.time-zone=GMT # Timezone of the request log. server.jetty.max-http-post-size=200000B # Maximum size of the HTTP post or put content. server.jetty.selectors=-1 # Number of selector threads to use. When the value is -1, the default, the number of selectors is derived from the operating environment. server.max-http-header-size=8KB # Maximum size of the HTTP message header. server.port=8080 # Server HTTP port. server.server-header= # Value to use for the Server response header (if empty, no header is sent). server.use-forward-headers= # Whether X-Forwarded-* headers should be applied to the HttpRequest. server.servlet.context-parameters.*= # Servlet context init parameters. server.servlet.context-path= # Context path of the application. server.servlet.application-display-name=application # Display name of the application. server.servlet.jsp.class-name=org.apache.jasper.servlet.JspServlet # The class name of the JSP servlet. server.servlet.jsp.init-parameters.*= # Init parameters used to configure the JSP servlet. server.servlet.jsp.registered=true # Whether the JSP servlet is registered. server.servlet.session.cookie.comment= # Comment for the session cookie. server.servlet.session.cookie.domain= # Domain for the session cookie. server.servlet.session.cookie.http-only= # "HttpOnly" flag for the session cookie. server.servlet.session.cookie.max-age= # Maximum age of the session cookie. If a duration suffix is not specified, seconds will be used. server.servlet.session.cookie.name= # Session cookie name. server.servlet.session.cookie.path= # Path of the session cookie. server.servlet.session.cookie.secure= # "Secure" flag for the session cookie. server.servlet.session.persistent=false # Whether to persist session data between restarts. server.servlet.session.store-dir= # Directory used to store session data. server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds will be used. server.servlet.session.tracking-modes= # Session tracking modes (one or more of the following: "cookie", "url", "ssl"). server.ssl.ciphers= # Supported SSL ciphers. server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. server.ssl.enabled= # Enable SSL support. server.ssl.enabled-protocols= # Enabled SSL protocols. server.ssl.key-alias= # Alias that identifies the key in the key store. server.ssl.key-password= # Password used to access the key in the key store. server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file). server.ssl.key-store-password= # Password used to access the key store. server.ssl.key-store-provider= # Provider for the key store. server.ssl.key-store-type= # Type of the key store. server.ssl.protocol=TLS # SSL protocol to use. server.ssl.trust-store= # Trust store that holds SSL certificates. server.ssl.trust-store-password= # Password used to access the trust store. server.ssl.trust-store-provider= # Provider for the trust store. server.ssl.trust-store-type= # Type of the trust store. server.tomcat.accept-count=100 # Maximum queue length for incoming connection requests when all possible request processing threads are in use. server.tomcat.accesslog.buffered=true # Whether to buffer output such that it is flushed only periodically. server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be absolute or relative to the Tomcat base dir. server.tomcat.accesslog.enabled=false # Enable access log. server.tomcat.accesslog.file-date-format=.yyyy-MM-dd # Date format to place in the log file name. server.tomcat.accesslog.pattern=common # Format pattern for access logs. server.tomcat.accesslog.prefix=access_log # Log file name prefix. server.tomcat.accesslog.rename-on-rotate=false # Whether to defer inclusion of the date stamp in the file name until rotate time. server.tomcat.accesslog.request-attributes-enabled=false # Set request attributes for the IP address, Hostname, protocol, and port used for the request. server.tomcat.accesslog.rotate=true # Whether to enable access log rotation. server.tomcat.accesslog.suffix=.log # Log file name suffix. server.tomcat.additional-tld-skip-patterns= # Comma-separated list of additional patterns that match jars to ignore for TLD scanning. server.tomcat.background-processor-delay=10s # Delay between the invocation of backgroundProcess methods. If a duration suffix is not specified, seconds will be used. server.tomcat.basedir= # Tomcat base directory. If not specified, a temporary directory is used. server.tomcat.internal-proxies=10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\ 192\\.168\\.\\d{1,3}\\.\\d{1,3}|\\ 169\\.254\\.\\d{1,3}\\.\\d{1,3}|\\ 127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\ 172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\ 172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\ 172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}\\ 0:0:0:0:0:0:0:1\\ ::1 # Regular expression that matches proxies that are to be trusted. server.tomcat.max-connections=10000 # Maximum number of connections that the server accepts and processes at any given time. server.tomcat.max-http-post-size=2MB # Maximum size of the HTTP post content. server.tomcat.max-swallow-size=2MB # Maximum amount of request body to swallow. server.tomcat.max-threads=200 # Maximum amount of worker threads. server.tomcat.min-spare-threads=10 # Minimum amount of worker threads. server.tomcat.port-header=X-Forwarded-Port # Name of the HTTP header used to override the original port value. server.tomcat.protocol-header= # Header that holds the incoming protocol, usually named "X-Forwarded-Proto". server.tomcat.protocol-header-https-value=https # Value of the protocol header indicating whether the incoming request uses SSL. server.tomcat.redirect-context-root=true # Whether requests to the context root should be redirected by appending a / to the path. server.tomcat.remote-ip-header= # Name of the HTTP header from which the remote IP is extracted. For instance, `X-FORWARDED-FOR`. server.tomcat.resource.allow-caching=true # Whether static resource caching is permitted for this web application. server.tomcat.resource.cache-ttl= # Time-to-live of the static resource cache. server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI. server.tomcat.use-relative-redirects= # Whether HTTP 1.1 and later location headers generated by a call to sendRedirect will use relative or absolute redirects. server.undertow.accesslog.dir= # Undertow access log directory. server.undertow.accesslog.enabled=false # Whether to enable the access log. server.undertow.accesslog.pattern=common # Format pattern for access logs. server.undertow.accesslog.prefix=access_log. # Log file name prefix. server.undertow.accesslog.rotate=true # Whether to enable access log rotation. server.undertow.accesslog.suffix=log # Log file name suffix. server.undertow.buffer-size= # Size of each buffer. server.undertow.direct-buffers= # Whether to allocate buffers outside the Java heap. The default is derived from the maximum amount of memory that is available to the JVM. server.undertow.eager-filter-init=true # Whether servlet filters should be initialized on startup. server.undertow.io-threads= # Number of I/O threads to create for the worker. The default is derived from the number of available processors. server.undertow.max-http-post-size=-1B # Maximum size of the HTTP post content. When the value is -1, the default, the size is unlimited. server.undertow.worker-threads= # Number of worker threads. The default is 8 times the number of I/O threads. # FREEMARKER (FreeMarkerProperties) spring.freemarker.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. spring.freemarker.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. spring.freemarker.cache=false # Whether to enable template caching. spring.freemarker.charset=UTF-8 # Template encoding. spring.freemarker.check-template-location=true # Whether to check that the templates location exists. spring.freemarker.content-type=text/html # Content-Type value. spring.freemarker.enabled=true # Whether to enable MVC view resolution for this technology. spring.freemarker.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template. spring.freemarker.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template. spring.freemarker.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". spring.freemarker.prefer-file-system-access=true # Whether to prefer file system access for template loading. File system access enables hot detection of template changes. spring.freemarker.prefix= # Prefix that gets prepended to view names when building a URL. spring.freemarker.request-context-attribute= # Name of the RequestContext attribute for all views. spring.freemarker.settings.*= # Well-known FreeMarker keys which are passed to FreeMarker's Configuration. spring.freemarker.suffix=.ftl # Suffix that gets appended to view names when building a URL. spring.freemarker.template-loader-path=classpath:/templates/ # Comma-separated list of template paths. spring.freemarker.view-names= # White list of view names that can be resolved. # GROOVY TEMPLATES (GroovyTemplateProperties) spring.groovy.template.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. spring.groovy.template.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. spring.groovy.template.cache=false # Whether to enable template caching. spring.groovy.template.charset=UTF-8 # Template encoding. spring.groovy.template.check-template-location=true # Whether to check that the templates location exists. spring.groovy.template.configuration.*= # See GroovyMarkupConfigurer spring.groovy.template.content-type=text/html # Content-Type value. spring.groovy.template.enabled=true # Whether to enable MVC view resolution for this technology. spring.groovy.template.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template. spring.groovy.template.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template. spring.groovy.template.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". spring.groovy.template.prefix= # Prefix that gets prepended to view names when building a URL. spring.groovy.template.request-context-attribute= # Name of the RequestContext attribute for all views. spring.groovy.template.resource-loader-path=classpath:/templates/ # Template path. spring.groovy.template.suffix=.tpl # Suffix that gets appended to view names when building a URL. spring.groovy.template.view-names= # White list of view names that can be resolved. # SPRING HATEOAS (HateoasProperties) spring.hateoas.use-hal-as-default-json-media-type=true # Whether application/hal+json responses should be sent to requests that accept application/json. # HTTP (HttpProperties) spring.http.converters.preferred-json-mapper= # Preferred JSON mapper to use for HTTP message conversion. By default, auto-detected according to the environment. spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly. spring.http.encoding.enabled=true # Whether to enable http encoding support. spring.http.encoding.force= # Whether to force the encoding to the configured charset on HTTP requests and responses. spring.http.encoding.force-request= # Whether to force the encoding to the configured charset on HTTP requests. Defaults to true when "force" has not been specified. spring.http.encoding.force-response= # Whether to force the encoding to the configured charset on HTTP responses. spring.http.encoding.mapping= # Locale in which to encode mapping. spring.http.log-request-details=false # Whether logging of (potentially sensitive) request details at DEBUG and TRACE level is allowed. # MULTIPART (MultipartProperties) spring.servlet.multipart.enabled=true # Whether to enable support of multipart uploads. spring.servlet.multipart.file-size-threshold=0B # Threshold after which files are written to disk. spring.servlet.multipart.location= # Intermediate location of uploaded files. spring.servlet.multipart.max-file-size=1MB # Max file size. spring.servlet.multipart.max-request-size=10MB # Max request size. spring.servlet.multipart.resolve-lazily=false # Whether to resolve the multipart request lazily at the time of file or parameter access. # JACKSON (JacksonProperties) spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`. spring.jackson.default-property-inclusion= # Controls the inclusion of properties during serialization. Configured with one of the values in Jackson's JsonInclude.Include enumeration. spring.jackson.deserialization.*= # Jackson on/off features that affect the way Java objects are deserialized. spring.jackson.generator.*= # Jackson on/off features for generators. spring.jackson.joda-date-time-format= # Joda date time format string. If not configured, "date-format" is used as a fallback if it is configured with a format string. spring.jackson.locale= # Locale used for formatting. spring.jackson.mapper.*= # Jackson general purpose on/off features. spring.jackson.parser.*= # Jackson on/off features for parsers. spring.jackson.property-naming-strategy= # One of the constants on Jackson's PropertyNamingStrategy. Can also be a fully-qualified class name of a PropertyNamingStrategy subclass. spring.jackson.serialization.*= # Jackson on/off features that affect the way Java objects are serialized. spring.jackson.time-zone= # Time zone used when formatting dates. For instance, "America/Los_Angeles" or "GMT+10". spring.jackson.visibility.*= # Jackson visibility thresholds that can be used to limit which methods (and fields) are auto-detected. # GSON (GsonProperties) spring.gson.date-format= # Format to use when serializing Date objects. spring.gson.disable-html-escaping= # Whether to disable the escaping of HTML characters such as '<', '>', etc. spring.gson.disable-inner-class-serialization= # Whether to exclude inner classes during serialization. spring.gson.enable-complex-map-key-serialization= # Whether to enable serialization of complex map keys (i.e. non-primitives). spring.gson.exclude-fields-without-expose-annotation= # Whether to exclude all fields from consideration for serialization or deserialization that do not have the "Expose" annotation. spring.gson.field-naming-policy= # Naming policy that should be applied to an object's field during serialization and deserialization. spring.gson.generate-non-executable-json= # Whether to generate non executable JSON by prefixing the output with some special text. spring.gson.lenient= # Whether to be lenient about parsing JSON that doesn't conform to RFC 4627. spring.gson.long-serialization-policy= # Serialization policy for Long and long types. spring.gson.pretty-printing= # Whether to output serialized JSON that fits in a page for pretty printing. spring.gson.serialize-nulls= # Whether to serialize null fields. # JERSEY (JerseyProperties) spring.jersey.application-path= # Path that serves as the base URI for the application. If specified, overrides the value of "@ApplicationPath". spring.jersey.filter.order=0 # Jersey filter chain order. spring.jersey.init.*= # Init parameters to pass to Jersey through the servlet or filter. spring.jersey.servlet.load-on-startup=-1 # Load on startup priority of the Jersey servlet. spring.jersey.type=servlet # Jersey integration type. # SPRING LDAP (LdapProperties) spring.ldap.anonymous-read-only=false # Whether read-only operations should use an anonymous environment. spring.ldap.base= # Base suffix from which all operations should originate. spring.ldap.base-environment.*= # LDAP specification settings. spring.ldap.password= # Login password of the server. spring.ldap.urls= # LDAP URLs of the server. spring.ldap.username= # Login username of the server. # EMBEDDED LDAP (EmbeddedLdapProperties) spring.ldap.embedded.base-dn= # List of base DNs. spring.ldap.embedded.credential.username= # Embedded LDAP username. spring.ldap.embedded.credential.password= # Embedded LDAP password. spring.ldap.embedded.ldif=classpath:schema.ldif # Schema (LDIF) script resource reference. spring.ldap.embedded.port=0 # Embedded LDAP port. spring.ldap.embedded.validation.enabled=true # Whether to enable LDAP schema validation. spring.ldap.embedded.validation.schema= # Path to the custom schema. # MUSTACHE TEMPLATES (MustacheAutoConfiguration) spring.mustache.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. spring.mustache.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. spring.mustache.cache=false # Whether to enable template caching. spring.mustache.charset=UTF-8 # Template encoding. spring.mustache.check-template-location=true # Whether to check that the templates location exists. spring.mustache.content-type=text/html # Content-Type value. spring.mustache.enabled=true # Whether to enable MVC view resolution for this technology. spring.mustache.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template. spring.mustache.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template. spring.mustache.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". spring.mustache.prefix=classpath:/templates/ # Prefix to apply to template names. spring.mustache.request-context-attribute= # Name of the RequestContext attribute for all views. spring.mustache.suffix=.mustache # Suffix to apply to template names. spring.mustache.view-names= # White list of view names that can be resolved. # SPRING MVC (WebMvcProperties) spring.mvc.async.request-timeout= # Amount of time before asynchronous request handling times out. spring.mvc.contentnegotiation.favor-parameter=false # Whether a request parameter ("format" by default) should be used to determine the requested media type. spring.mvc.contentnegotiation.favor-path-extension=false # Whether the path extension in the URL path should be used to determine the requested media type. spring.mvc.contentnegotiation.media-types.*= # Map file extensions to media types for content negotiation. For instance, yml to text/yaml. spring.mvc.contentnegotiation.parameter-name= # Query parameter name to use when "favor-parameter" is enabled. spring.mvc.date-format= # Date format to use. For instance, `dd/MM/yyyy`. spring.mvc.dispatch-trace-request=false # Whether to dispatch TRACE requests to the FrameworkServlet doService method. spring.mvc.dispatch-options-request=true # Whether to dispatch OPTIONS requests to the FrameworkServlet doService method. spring.mvc.favicon.enabled=true # Whether to enable resolution of favicon.ico. spring.mvc.formcontent.filter.enabled=true # Whether to enable Spring's FormContentFilter. spring.mvc.hiddenmethod.filter.enabled=true # Whether to enable Spring's HiddenHttpMethodFilter. spring.mvc.ignore-default-model-on-redirect=true # Whether the content of the "default" model should be ignored during redirect scenarios. spring.mvc.locale= # Locale to use. By default, this locale is overridden by the "Accept-Language" header. spring.mvc.locale-resolver=accept-header # Define how the locale should be resolved. spring.mvc.log-resolved-exception=false # Whether to enable warn logging of exceptions resolved by a "HandlerExceptionResolver". spring.mvc.message-codes-resolver-format= # Formatting strategy for message codes. For instance, `PREFIX_ERROR_CODE`. spring.mvc.pathmatch.use-registered-suffix-pattern=false # Whether suffix pattern matching should work only against extensions registered with "spring.mvc.contentnegotiation.media-types.*". spring.mvc.pathmatch.use-suffix-pattern=false # Whether to use suffix pattern match (".*") when matching patterns to requests. spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet. spring.mvc.servlet.path=/ # Path of the dispatcher servlet. spring.mvc.static-path-pattern=/** # Path pattern used for static resources. spring.mvc.throw-exception-if-no-handler-found=false # Whether a "NoHandlerFoundException" should be thrown if no Handler was found to process a request. spring.mvc.view.prefix= # Spring MVC view prefix. spring.mvc.view.suffix= # Spring MVC view suffix. # SPRING RESOURCES HANDLING (ResourceProperties) spring.resources.add-mappings=true # Whether to enable default resource handling. spring.resources.cache.cachecontrol.cache-private= # Indicate that the response message is intended for a single user and must not be stored by a shared cache. spring.resources.cache.cachecontrol.cache-public= # Indicate that any cache may store the response. spring.resources.cache.cachecontrol.max-age= # Maximum time the response should be cached, in seconds if no duration suffix is not specified. spring.resources.cache.cachecontrol.must-revalidate= # Indicate that once it has become stale, a cache must not use the response without re-validating it with the server. spring.resources.cache.cachecontrol.no-cache= # Indicate that the cached response can be reused only if re-validated with the server. spring.resources.cache.cachecontrol.no-store= # Indicate to not cache the response in any case. spring.resources.cache.cachecontrol.no-transform= # Indicate intermediaries (caches and others) that they should not transform the response content. spring.resources.cache.cachecontrol.proxy-revalidate= # Same meaning as the "must-revalidate" directive, except that it does not apply to private caches. spring.resources.cache.cachecontrol.s-max-age= # Maximum time the response should be cached by shared caches, in seconds if no duration suffix is not specified. spring.resources.cache.cachecontrol.stale-if-error= # Maximum time the response may be used when errors are encountered, in seconds if no duration suffix is not specified. spring.resources.cache.cachecontrol.stale-while-revalidate= # Maximum time the response can be served after it becomes stale, in seconds if no duration suffix is not specified. spring.resources.cache.period= # Cache period for the resources served by the resource handler. If a duration suffix is not specified, seconds will be used. spring.resources.chain.cache=true # Whether to enable caching in the Resource chain. spring.resources.chain.compressed=false # Whether to enable resolution of already compressed resources (gzip, brotli). spring.resources.chain.enabled= # Whether to enable the Spring Resource Handling chain. By default, disabled unless at least one strategy has been enabled. spring.resources.chain.html-application-cache=false # Whether to enable HTML5 application cache manifest rewriting. spring.resources.chain.strategy.content.enabled=false # Whether to enable the content Version Strategy. spring.resources.chain.strategy.content.paths=/** # Comma-separated list of patterns to apply to the content Version Strategy. spring.resources.chain.strategy.fixed.enabled=false # Whether to enable the fixed Version Strategy. spring.resources.chain.strategy.fixed.paths=/** # Comma-separated list of patterns to apply to the fixed Version Strategy. spring.resources.chain.strategy.fixed.version= # Version string to use for the fixed Version Strategy. spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ # Locations of static resources. # SPRING SESSION (SessionProperties) spring.session.store-type= # Session store type. spring.session.timeout= # Session timeout. If a duration suffix is not specified, seconds will be used. spring.session.servlet.filter-order=-2147483598 # Session repository filter order. spring.session.servlet.filter-dispatcher-types=async,error,request # Session repository filter dispatcher types. # SPRING SESSION HAZELCAST (HazelcastSessionProperties) spring.session.hazelcast.flush-mode=on-save # Sessions flush mode. spring.session.hazelcast.map-name=spring:session:sessions # Name of the map used to store sessions. # SPRING SESSION JDBC (JdbcSessionProperties) spring.session.jdbc.cleanup-cron=0 * * * * * # Cron expression for expired session cleanup job. spring.session.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. spring.session.jdbc.table-name=SPRING_SESSION # Name of the database table used to store sessions. # SPRING SESSION MONGODB (MongoSessionProperties) spring.session.mongodb.collection-name=sessions # Collection name used to store sessions. # SPRING SESSION REDIS (RedisSessionProperties) spring.session.redis.cleanup-cron=0 * * * * * # Cron expression for expired session cleanup job. spring.session.redis.flush-mode=on-save # Sessions flush mode. spring.session.redis.namespace=spring:session # Namespace for keys used to store sessions. # THYMELEAF (ThymeleafAutoConfiguration) spring.thymeleaf.cache=true # Whether to enable template caching. spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it. spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists. spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks. spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions. spring.thymeleaf.encoding=UTF-8 # Template files encoding. spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution. spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum. spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL. spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set. spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set. spring.thymeleaf.reactive.max-chunk-size=0B # Maximum size of data buffers used for writing to the response. spring.thymeleaf.reactive.media-types= # Media types supported by the view technology. spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses. spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL. spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved. # SPRING WEBFLUX (WebFluxProperties) spring.webflux.date-format= # Date format to use. For instance, `dd/MM/yyyy`. spring.webflux.static-path-pattern=/** # Path pattern used for static resources. # SPRING WEB SERVICES (WebServicesProperties) spring.webservices.path=/services # Path that serves as the base URI for the services. spring.webservices.servlet.init= # Servlet init parameters to pass to Spring Web Services. spring.webservices.servlet.load-on-startup=-1 # Load on startup priority of the Spring Web Services servlet. spring.webservices.wsdl-locations= # Comma-separated list of locations of WSDLs and accompanying XSDs to be exposed as beans. # ---------------------------------------- # SECURITY PROPERTIES # ---------------------------------------- # SECURITY (SecurityProperties) spring.security.filter.order=-100 # Security filter chain order. spring.security.filter.dispatcher-types=async,error,request # Security filter chain dispatcher types. spring.security.user.name=user # Default user name. spring.security.user.password= # Password for the default user name. spring.security.user.roles= # Granted roles for the default user name. # SECURITY OAUTH2 CLIENT (OAuth2ClientProperties) spring.security.oauth2.client.provider.*= # OAuth provider details. spring.security.oauth2.client.registration.authorization-code.*= # OAuth2 authorization_code client registrations. spring.security.oauth2.client.registration.login.*= # OpenID Connect client registrations. # SECURITY OAUTH2 RESOURCE SERVER (OAuth2ResourceServerProperties) spring.security.oauth2.resourceserver.jwt.jwk-set-uri= # JSON Web Key URI to use to verify the JWT token. spring.security.oauth2.resourceserver.jwt.issuer-uri= # URI that an OpenID Connect Provider asserts as its Issuer Identifier. # ---------------------------------------- # DATA PROPERTIES # ---------------------------------------- # FLYWAY (FlywayProperties) spring.flyway.baseline-description= # spring.flyway.baseline-on-migrate= # spring.flyway.baseline-version=1 # Version to start migration spring.flyway.batch= # spring.flyway.check-location=true # Whether to check that migration scripts location exists. spring.flyway.clean-disabled= # spring.flyway.clean-on-validation-error= # spring.flyway.dry-run-output= # spring.flyway.enabled=true # Whether to enable flyway. spring.flyway.error-handlers= # spring.flyway.error-overrides= # spring.flyway.group= # spring.flyway.ignore-ignored-migrations= # spring.flyway.ignore-future-migrations= # spring.flyway.ignore-missing-migrations= # spring.flyway.init-sqls= # SQL statements to execute to initialize a connection immediately after obtaining it. spring.flyway.installed-by= # spring.flyway.locations=classpath:db/migration # The locations of migrations scripts. spring.flyway.mixed= # spring.flyway.oracle-sqlplus= # spring.flyway.out-of-order= # spring.flyway.password= # JDBC password to use if you want Flyway to create its own DataSource. spring.flyway.placeholder-prefix= # spring.flyway.placeholder-replacement= # spring.flyway.placeholder-suffix= # spring.flyway.placeholders.*= # spring.flyway.repeatable-sql-migration-prefix= # spring.flyway.schemas= # Schemas to update. spring.flyway.skip-default-callbacks= # spring.flyway.skip-default-resolvers= # spring.flyway.sql-migration-prefix=V # spring.flyway.sql-migration-separator= # spring.flyway.sql-migration-suffix=.sql # spring.flyway.sql-migration-suffixes= # spring.flyway.stream= # spring.flyway.table= # spring.flyway.target= # spring.flyway.undo-sql-migration-prefix= # spring.flyway.url= # JDBC url of the database to migrate. If not set, the primary configured data source is used. spring.flyway.user= # Login user of the database to migrate. spring.flyway.validate-on-migrate= # # LIQUIBASE (LiquibaseProperties) spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml # Change log configuration path. spring.liquibase.check-change-log-location=true # Whether to check that the change log location exists. spring.liquibase.contexts= # Comma-separated list of runtime contexts to use. spring.liquibase.database-change-log-lock-table=DATABASECHANGELOGLOCK # Name of table to use for tracking concurrent Liquibase usage. spring.liquibase.database-change-log-table=DATABASECHANGELOG # Name of table to use for tracking change history. spring.liquibase.default-schema= # Default database schema. spring.liquibase.drop-first=false # Whether to first drop the database schema. spring.liquibase.enabled=true # Whether to enable Liquibase support. spring.liquibase.labels= # Comma-separated list of runtime labels to use. spring.liquibase.liquibase-schema= # Schema to use for Liquibase objects. spring.liquibase.liquibase-tablespace= # Tablespace to use for Liquibase objects. spring.liquibase.parameters.*= # Change log parameters. spring.liquibase.password= # Login password of the database to migrate. spring.liquibase.rollback-file= # File to which rollback SQL is written when an update is performed. spring.liquibase.test-rollback-on-update=false # Whether rollback should be tested before update is performed. spring.liquibase.url= # JDBC URL of the database to migrate. If not set, the primary configured data source is used. spring.liquibase.user= # Login user of the database to migrate. # COUCHBASE (CouchbaseProperties) spring.couchbase.bootstrap-hosts= # Couchbase nodes (host or IP address) to bootstrap from. spring.couchbase.bucket.name=default # Name of the bucket to connect to. spring.couchbase.bucket.password= # Password of the bucket. spring.couchbase.env.endpoints.key-value=1 # Number of sockets per node against the key/value service. spring.couchbase.env.endpoints.queryservice.min-endpoints=1 # Minimum number of sockets per node. spring.couchbase.env.endpoints.queryservice.max-endpoints=1 # Maximum number of sockets per node. spring.couchbase.env.endpoints.viewservice.min-endpoints=1 # Minimum number of sockets per node. spring.couchbase.env.endpoints.viewservice.max-endpoints=1 # Maximum number of sockets per node. spring.couchbase.env.ssl.enabled= # Whether to enable SSL support. Enabled automatically if a "keyStore" is provided unless specified otherwise. spring.couchbase.env.ssl.key-store= # Path to the JVM key store that holds the certificates. spring.couchbase.env.ssl.key-store-password= # Password used to access the key store. spring.couchbase.env.timeouts.connect=5000ms # Bucket connections timeouts. spring.couchbase.env.timeouts.key-value=2500ms # Blocking operations performed on a specific key timeout. spring.couchbase.env.timeouts.query=7500ms # N1QL query operations timeout. spring.couchbase.env.timeouts.socket-connect=1000ms # Socket connect connections timeout. spring.couchbase.env.timeouts.view=7500ms # Regular and geospatial view operations timeout. # DAO (PersistenceExceptionTranslationAutoConfiguration) spring.dao.exceptiontranslation.enabled=true # Whether to enable the PersistenceExceptionTranslationPostProcessor. # CASSANDRA (CassandraProperties) spring.data.cassandra.cluster-name= # Name of the Cassandra cluster. spring.data.cassandra.compression=none # Compression supported by the Cassandra binary protocol. spring.data.cassandra.connect-timeout= # Socket option: connection time out. spring.data.cassandra.consistency-level= # Queries consistency level. spring.data.cassandra.contact-points=localhost # Cluster node addresses. spring.data.cassandra.fetch-size= # Queries default fetch size. spring.data.cassandra.keyspace-name= # Keyspace name to use. spring.data.cassandra.load-balancing-policy= # Class name of the load balancing policy. The class must have a default constructor. spring.data.cassandra.port= # Port of the Cassandra server. spring.data.cassandra.password= # Login password of the server. spring.data.cassandra.pool.heartbeat-interval=30s # Heartbeat interval after which a message is sent on an idle connection to make sure it's still alive. If a duration suffix is not specified, seconds will be used. spring.data.cassandra.pool.idle-timeout=120s # Idle timeout before an idle connection is removed. If a duration suffix is not specified, seconds will be used. spring.data.cassandra.pool.max-queue-size=256 # Maximum number of requests that get queued if no connection is available. spring.data.cassandra.pool.pool-timeout=5000ms # Pool timeout when trying to acquire a connection from a host's pool. spring.data.cassandra.read-timeout= # Socket option: read time out. spring.data.cassandra.reconnection-policy= # Class name of the reconnection policy. The class must have a default constructor. spring.data.cassandra.repositories.type=auto # Type of Cassandra repositories to enable. spring.data.cassandra.retry-policy= # Class name of the retry policy. The class must have a default constructor. spring.data.cassandra.serial-consistency-level= # Queries serial consistency level. spring.data.cassandra.schema-action=none # Schema action to take at startup. spring.data.cassandra.ssl=false # Enable SSL support. spring.data.cassandra.username= # Login user of the server. # DATA COUCHBASE (CouchbaseDataProperties) spring.data.couchbase.auto-index=false # Automatically create views and indexes. spring.data.couchbase.consistency=read-your-own-writes # Consistency to apply by default on generated queries. spring.data.couchbase.repositories.type=auto # Type of Couchbase repositories to enable. # ELASTICSEARCH (ElasticsearchProperties) spring.data.elasticsearch.cluster-name=elasticsearch # Elasticsearch cluster name. spring.data.elasticsearch.cluster-nodes= # Comma-separated list of cluster node addresses. spring.data.elasticsearch.properties.*= # Additional properties used to configure the client. spring.data.elasticsearch.repositories.enabled=true # Whether to enable Elasticsearch repositories. # DATA JDBC spring.data.jdbc.repositories.enabled=true # Whether to enable JDBC repositories. # DATA LDAP spring.data.ldap.repositories.enabled=true # Whether to enable LDAP repositories. # MONGODB (MongoProperties) spring.data.mongodb.authentication-database= # Authentication database name. spring.data.mongodb.database= # Database name. spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use. spring.data.mongodb.grid-fs-database= # GridFS database name. spring.data.mongodb.host= # Mongo server host. Cannot be set with URI. spring.data.mongodb.password= # Login password of the mongo server. Cannot be set with URI. spring.data.mongodb.port= # Mongo server port. Cannot be set with URI. spring.data.mongodb.repositories.type=auto # Type of Mongo repositories to enable. spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. Cannot be set with host, port and credentials. spring.data.mongodb.username= # Login user of the mongo server. Cannot be set with URI. # DATA REDIS spring.data.redis.repositories.enabled=true # Whether to enable Redis repositories. # NEO4J (Neo4jProperties) spring.data.neo4j.auto-index=none # Auto index mode. spring.data.neo4j.embedded.enabled=true # Whether to enable embedded mode if the embedded driver is available. spring.data.neo4j.open-in-view=true # Register OpenSessionInViewInterceptor. Binds a Neo4j Session to the thread for the entire processing of the request. spring.data.neo4j.password= # Login password of the server. spring.data.neo4j.repositories.enabled=true # Whether to enable Neo4j repositories. spring.data.neo4j.uri= # URI used by the driver. Auto-detected by default. spring.data.neo4j.username= # Login user of the server. # DATA REST (RepositoryRestProperties) spring.data.rest.base-path= # Base path to be used by Spring Data REST to expose repository resources. spring.data.rest.default-media-type= # Content type to use as a default when none is specified. spring.data.rest.default-page-size= # Default size of pages. spring.data.rest.detection-strategy=default # Strategy to use to determine which repositories get exposed. spring.data.rest.enable-enum-translation= # Whether to enable enum value translation through the Spring Data REST default resource bundle. spring.data.rest.limit-param-name= # Name of the URL query string parameter that indicates how many results to return at once. spring.data.rest.max-page-size= # Maximum size of pages. spring.data.rest.page-param-name= # Name of the URL query string parameter that indicates what page to return. spring.data.rest.return-body-on-create= # Whether to return a response body after creating an entity. spring.data.rest.return-body-on-update= # Whether to return a response body after updating an entity. spring.data.rest.sort-param-name= # Name of the URL query string parameter that indicates what direction to sort results. # SOLR (SolrProperties) spring.data.solr.host=http://127.0.0.1:8983/solr # Solr host. Ignored if "zk-host" is set. spring.data.solr.repositories.enabled=true # Whether to enable Solr repositories. spring.data.solr.zk-host= # ZooKeeper host address in the form HOST:PORT. # DATA WEB (SpringDataWebProperties) spring.data.web.pageable.default-page-size=20 # Default page size. spring.data.web.pageable.max-page-size=2000 # Maximum page size to be accepted. spring.data.web.pageable.one-indexed-parameters=false # Whether to expose and assume 1-based page number indexes. spring.data.web.pageable.page-parameter=page # Page index parameter name. spring.data.web.pageable.prefix= # General prefix to be prepended to the page number and page size parameters. spring.data.web.pageable.qualifier-delimiter=_ # Delimiter to be used between the qualifier and the actual page number and size properties. spring.data.web.pageable.size-parameter=size # Page size parameter name. spring.data.web.sort.sort-parameter=sort # Sort parameter name. # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error=false # Whether to stop if an error occurs while initializing the database. spring.datasource.data= # Data (DML) script resource references. spring.datasource.data-username= # Username of the database to execute DML scripts (if different). spring.datasource.data-password= # Password of the database to execute DML scripts (if different). spring.datasource.dbcp2.*= # Commons DBCP2 specific settings spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. spring.datasource.generate-unique-name=false # Whether to generate a random datasource name. spring.datasource.hikari.*= # Hikari specific settings spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts. spring.datasource.jmx-enabled=false # Whether to enable JMX support (if provided by the underlying pool). spring.datasource.jndi-name= # JNDI location of the datasource. Class, url, username & password are ignored when set. spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database. spring.datasource.password= # Login password of the database. spring.datasource.platform=all # Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or data-${platform}.sql). spring.datasource.schema= # Schema (DDL) script resource references. spring.datasource.schema-username= # Username of the database to execute DDL scripts (if different). spring.datasource.schema-password= # Password of the database to execute DDL scripts (if different). spring.datasource.separator=; # Statement separator in SQL initialization scripts. spring.datasource.sql-script-encoding= # SQL scripts encoding. spring.datasource.tomcat.*= # Tomcat datasource specific settings spring.datasource.type= # Fully qualified name of the connection pool implementation to use. By default, it is auto-detected from the classpath. spring.datasource.url= # JDBC URL of the database. spring.datasource.username= # Login username of the database. spring.datasource.xa.data-source-class-name= # XA datasource fully qualified name. spring.datasource.xa.properties= # Properties to pass to the XA data source. # JEST (Elasticsearch HTTP client) (JestProperties) spring.elasticsearch.jest.connection-timeout=3s # Connection timeout. spring.elasticsearch.jest.multi-threaded=true # Whether to enable connection requests from multiple execution threads. spring.elasticsearch.jest.password= # Login password. spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use. spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use. spring.elasticsearch.jest.read-timeout=3s # Read timeout. spring.elasticsearch.jest.uris=http://localhost:9200 # Comma-separated list of the Elasticsearch instances to use. spring.elasticsearch.jest.username= # Login username. # Elasticsearch REST clients (RestClientProperties) spring.elasticsearch.rest.password= # Credentials password. spring.elasticsearch.rest.uris=http://localhost:9200 # Comma-separated list of the Elasticsearch instances to use. spring.elasticsearch.rest.username= # Credentials username. # H2 Web Console (H2ConsoleProperties) spring.h2.console.enabled=false # Whether to enable the console. spring.h2.console.path=/h2-console # Path at which the console is available. spring.h2.console.settings.trace=false # Whether to enable trace output. spring.h2.console.settings.web-allow-others=false # Whether to enable remote access. # InfluxDB (InfluxDbProperties) spring.influx.password= # Login password. spring.influx.url= # URL of the InfluxDB instance to which to connect. spring.influx.user= # Login user. # JOOQ (JooqProperties) spring.jooq.sql-dialect= # SQL dialect to use. Auto-detected by default. # JDBC (JdbcProperties) spring.jdbc.template.fetch-size=-1 # Number of rows that should be fetched from the database when more rows are needed. spring.jdbc.template.max-rows=-1 # Maximum number of rows. spring.jdbc.template.query-timeout= # Query timeout. Default is to use the JDBC driver's default configuration. If a duration suffix is not specified, seconds will be used. # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.data.jpa.repositories.bootstrap-mode=default # Bootstrap mode for JPA repositories. spring.data.jpa.repositories.enabled=true # Whether to enable JPA repositories. spring.jpa.database= # Target database to operate on, auto-detected by default. Can be alternatively set using the "databasePlatform" property. spring.jpa.database-platform= # Name of the target database to operate on, auto-detected by default. Can be alternatively set using the "Database" enum. spring.jpa.generate-ddl=false # Whether to initialize the schema on startup. spring.jpa.hibernate.ddl-auto= # DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none". spring.jpa.hibernate.naming.implicit-strategy= # Fully qualified name of the implicit naming strategy. spring.jpa.hibernate.naming.physical-strategy= # Fully qualified name of the physical naming strategy. spring.jpa.hibernate.use-new-id-generator-mappings= # Whether to use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE. spring.jpa.mapping-resources= # Mapping resources (equivalent to "mapping-file" entries in persistence.xml). spring.jpa.open-in-view=true # Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for the entire processing of the request. spring.jpa.properties.*= # Additional native properties to set on the JPA provider. spring.jpa.show-sql=false # Whether to enable logging of SQL statements. # JTA (JtaAutoConfiguration) spring.jta.enabled=true # Whether to enable JTA support. spring.jta.log-dir= # Transaction logs directory. spring.jta.transaction-manager-id= # Transaction manager unique identifier. # ATOMIKOS (AtomikosProperties) spring.jta.atomikos.connectionfactory.borrow-connection-timeout=30 # Timeout, in seconds, for borrowing connections from the pool. spring.jta.atomikos.connectionfactory.ignore-session-transacted-flag=true # Whether to ignore the transacted flag when creating session. spring.jta.atomikos.connectionfactory.local-transaction-mode=false # Whether local transactions are desired. spring.jta.atomikos.connectionfactory.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread. spring.jta.atomikos.connectionfactory.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. spring.jta.atomikos.connectionfactory.max-lifetime=0 # The time, in seconds, that a connection can be pooled for before being destroyed. 0 denotes no limit. spring.jta.atomikos.connectionfactory.max-pool-size=1 # The maximum size of the pool. spring.jta.atomikos.connectionfactory.min-pool-size=1 # The minimum size of the pool. spring.jta.atomikos.connectionfactory.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. spring.jta.atomikos.connectionfactory.unique-resource-name=jmsConnectionFactory # The unique name used to identify the resource during recovery. spring.jta.atomikos.connectionfactory.xa-connection-factory-class-name= # Vendor-specific implementation of XAConnectionFactory. spring.jta.atomikos.connectionfactory.xa-properties= # Vendor-specific XA properties. spring.jta.atomikos.datasource.borrow-connection-timeout=30 # Timeout, in seconds, for borrowing connections from the pool. spring.jta.atomikos.datasource.concurrent-connection-validation= # Whether to use concurrent connection validation. spring.jta.atomikos.datasource.default-isolation-level= # Default isolation level of connections provided by the pool. spring.jta.atomikos.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection. spring.jta.atomikos.datasource.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread. spring.jta.atomikos.datasource.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. spring.jta.atomikos.datasource.max-lifetime=0 # The time, in seconds, that a connection can be pooled for before being destroyed. 0 denotes no limit. spring.jta.atomikos.datasource.max-pool-size=1 # The maximum size of the pool. spring.jta.atomikos.datasource.min-pool-size=1 # The minimum size of the pool. spring.jta.atomikos.datasource.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. spring.jta.atomikos.datasource.test-query= # SQL query or statement used to validate a connection before returning it. spring.jta.atomikos.datasource.unique-resource-name=dataSource # The unique name used to identify the resource during recovery. spring.jta.atomikos.datasource.xa-data-source-class-name= # Vendor-specific implementation of XAConnectionFactory. spring.jta.atomikos.datasource.xa-properties= # Vendor-specific XA properties. spring.jta.atomikos.properties.allow-sub-transactions=true # Specify whether sub-transactions are allowed. spring.jta.atomikos.properties.checkpoint-interval=500 # Interval between checkpoints, expressed as the number of log writes between two checkpoints. spring.jta.atomikos.properties.default-jta-timeout=10000ms # Default timeout for JTA transactions. spring.jta.atomikos.properties.default-max-wait-time-on-shutdown=9223372036854775807 # How long should normal shutdown (no-force) wait for transactions to complete. spring.jta.atomikos.properties.enable-logging=true # Whether to enable disk logging. spring.jta.atomikos.properties.force-shutdown-on-vm-exit=false # Whether a VM shutdown should trigger forced shutdown of the transaction core. spring.jta.atomikos.properties.log-base-dir= # Directory in which the log files should be stored. spring.jta.atomikos.properties.log-base-name=tmlog # Transactions log file base name. spring.jta.atomikos.properties.max-actives=50 # Maximum number of active transactions. spring.jta.atomikos.properties.max-timeout=300000ms # Maximum timeout that can be allowed for transactions. spring.jta.atomikos.properties.recovery.delay=10000ms # Delay between two recovery scans. spring.jta.atomikos.properties.recovery.forget-orphaned-log-entries-delay=86400000ms # Delay after which recovery can cleanup pending ('orphaned') log entries. spring.jta.atomikos.properties.recovery.max-retries=5 # Number of retry attempts to commit the transaction before throwing an exception. spring.jta.atomikos.properties.recovery.retry-interval=10000ms # Delay between retry attempts. spring.jta.atomikos.properties.serial-jta-transactions=true # Whether sub-transactions should be joined when possible. spring.jta.atomikos.properties.service= # Transaction manager implementation that should be started. spring.jta.atomikos.properties.threaded-two-phase-commit=false # Whether to use different (and concurrent) threads for two-phase commit on the participating resources. spring.jta.atomikos.properties.transaction-manager-unique-name= # The transaction manager's unique name. # BITRONIX spring.jta.bitronix.connectionfactory.acquire-increment=1 # Number of connections to create when growing the pool. spring.jta.bitronix.connectionfactory.acquisition-interval=1 # Time, in seconds, to wait before trying to acquire a connection again after an invalid connection was acquired. spring.jta.bitronix.connectionfactory.acquisition-timeout=30 # Timeout, in seconds, for acquiring connections from the pool. spring.jta.bitronix.connectionfactory.allow-local-transactions=true # Whether the transaction manager should allow mixing XA and non-XA transactions. spring.jta.bitronix.connectionfactory.apply-transaction-timeout=false # Whether the transaction timeout should be set on the XAResource when it is enlisted. spring.jta.bitronix.connectionfactory.automatic-enlisting-enabled=true # Whether resources should be enlisted and delisted automatically. spring.jta.bitronix.connectionfactory.cache-producers-consumers=true # Whether producers and consumers should be cached. spring.jta.bitronix.connectionfactory.class-name= # Underlying implementation class name of the XA resource. spring.jta.bitronix.connectionfactory.defer-connection-release=true # Whether the provider can run many transactions on the same connection and supports transaction interleaving. spring.jta.bitronix.connectionfactory.disabled= # Whether this resource is disabled, meaning it's temporarily forbidden to acquire a connection from its pool. spring.jta.bitronix.connectionfactory.driver-properties= # Properties that should be set on the underlying implementation. spring.jta.bitronix.connectionfactory.failed= # Mark this resource producer as failed. spring.jta.bitronix.connectionfactory.ignore-recovery-failures=false # Whether recovery failures should be ignored. spring.jta.bitronix.connectionfactory.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. spring.jta.bitronix.connectionfactory.max-pool-size=10 # The maximum size of the pool. 0 denotes no limit. spring.jta.bitronix.connectionfactory.min-pool-size=0 # The minimum size of the pool. spring.jta.bitronix.connectionfactory.password= # The password to use to connect to the JMS provider. spring.jta.bitronix.connectionfactory.share-transaction-connections=false # Whether connections in the ACCESSIBLE state can be shared within the context of a transaction. spring.jta.bitronix.connectionfactory.test-connections=true # Whether connections should be tested when acquired from the pool. spring.jta.bitronix.connectionfactory.two-pc-ordering-position=1 # The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE). spring.jta.bitronix.connectionfactory.unique-name=jmsConnectionFactory # The unique name used to identify the resource during recovery. spring.jta.bitronix.connectionfactory.use-tm-join=true # Whether TMJOIN should be used when starting XAResources. spring.jta.bitronix.connectionfactory.user= # The user to use to connect to the JMS provider. spring.jta.bitronix.datasource.acquire-increment=1 # Number of connections to create when growing the pool. spring.jta.bitronix.datasource.acquisition-interval=1 # Time, in seconds, to wait before trying to acquire a connection again after an invalid connection was acquired. spring.jta.bitronix.datasource.acquisition-timeout=30 # Timeout, in seconds, for acquiring connections from the pool. spring.jta.bitronix.datasource.allow-local-transactions=true # Whether the transaction manager should allow mixing XA and non-XA transactions. spring.jta.bitronix.datasource.apply-transaction-timeout=false # Whether the transaction timeout should be set on the XAResource when it is enlisted. spring.jta.bitronix.datasource.automatic-enlisting-enabled=true # Whether resources should be enlisted and delisted automatically. spring.jta.bitronix.datasource.class-name= # Underlying implementation class name of the XA resource. spring.jta.bitronix.datasource.cursor-holdability= # The default cursor holdability for connections. spring.jta.bitronix.datasource.defer-connection-release=true # Whether the database can run many transactions on the same connection and supports transaction interleaving. spring.jta.bitronix.datasource.disabled= # Whether this resource is disabled, meaning it's temporarily forbidden to acquire a connection from its pool. spring.jta.bitronix.datasource.driver-properties= # Properties that should be set on the underlying implementation. spring.jta.bitronix.datasource.enable-jdbc4-connection-test= # Whether Connection.isValid() is called when acquiring a connection from the pool. spring.jta.bitronix.datasource.failed= # Mark this resource producer as failed. spring.jta.bitronix.datasource.ignore-recovery-failures=false # Whether recovery failures should be ignored. spring.jta.bitronix.datasource.isolation-level= # The default isolation level for connections. spring.jta.bitronix.datasource.local-auto-commit= # The default auto-commit mode for local transactions. spring.jta.bitronix.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection. spring.jta.bitronix.datasource.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. spring.jta.bitronix.datasource.max-pool-size=10 # The maximum size of the pool. 0 denotes no limit. spring.jta.bitronix.datasource.min-pool-size=0 # The minimum size of the pool. spring.jta.bitronix.datasource.prepared-statement-cache-size=0 # The target size of the prepared statement cache. 0 disables the cache. spring.jta.bitronix.datasource.share-transaction-connections=false # Whether connections in the ACCESSIBLE state can be shared within the context of a transaction. spring.jta.bitronix.datasource.test-query= # SQL query or statement used to validate a connection before returning it. spring.jta.bitronix.datasource.two-pc-ordering-position=1 # The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, and always last is Integer.MAX_VALUE). spring.jta.bitronix.datasource.unique-name=dataSource # The unique name used to identify the resource during recovery. spring.jta.bitronix.datasource.use-tm-join=true # Whether TMJOIN should be used when starting XAResources. spring.jta.bitronix.properties.allow-multiple-lrc=false # Whether to allow multiple LRC resources to be enlisted into the same transaction. spring.jta.bitronix.properties.asynchronous2-pc=false # Whether to enable asynchronously execution of two phase commit. spring.jta.bitronix.properties.background-recovery-interval-seconds=60 # Interval in seconds at which to run the recovery process in the background. spring.jta.bitronix.properties.current-node-only-recovery=true # Whether to recover only the current node. spring.jta.bitronix.properties.debug-zero-resource-transaction=false # Whether to log the creation and commit call stacks of transactions executed without a single enlisted resource. spring.jta.bitronix.properties.default-transaction-timeout=60 # Default transaction timeout, in seconds. spring.jta.bitronix.properties.disable-jmx=false # Whether to enable JMX support. spring.jta.bitronix.properties.exception-analyzer= # Set the fully qualified name of the exception analyzer implementation to use. spring.jta.bitronix.properties.filter-log-status=false # Whether to enable filtering of logs so that only mandatory logs are written. spring.jta.bitronix.properties.force-batching-enabled=true # Whether disk forces are batched. spring.jta.bitronix.properties.forced-write-enabled=true # Whether logs are forced to disk. spring.jta.bitronix.properties.graceful-shutdown-interval=60 # Maximum amount of seconds the TM waits for transactions to get done before aborting them at shutdown time. spring.jta.bitronix.properties.jndi-transaction-synchronization-registry-name= # JNDI name of the TransactionSynchronizationRegistry. spring.jta.bitronix.properties.jndi-user-transaction-name= # JNDI name of the UserTransaction. spring.jta.bitronix.properties.journal=disk # Name of the journal. Can be 'disk', 'null', or a class name. spring.jta.bitronix.properties.log-part1-filename=btm1.tlog # Name of the first fragment of the journal. spring.jta.bitronix.properties.log-part2-filename=btm2.tlog # Name of the second fragment of the journal. spring.jta.bitronix.properties.max-log-size-in-mb=2 # Maximum size in megabytes of the journal fragments. spring.jta.bitronix.properties.resource-configuration-filename= # ResourceLoader configuration file name. spring.jta.bitronix.properties.server-id= # ASCII ID that must uniquely identify this TM instance. Defaults to the machine's IP address. spring.jta.bitronix.properties.skip-corrupted-logs=false # Skip corrupted transactions log entries. spring.jta.bitronix.properties.warn-about-zero-resource-transaction=true # Whether to log a warning for transactions executed without a single enlisted resource. # EMBEDDED MONGODB (EmbeddedMongoProperties) spring.mongodb.embedded.features=sync_delay # Comma-separated list of features to enable. spring.mongodb.embedded.storage.database-dir= # Directory used for data storage. spring.mongodb.embedded.storage.oplog-size= # Maximum size of the oplog. spring.mongodb.embedded.storage.repl-set-name= # Name of the replica set. spring.mongodb.embedded.version=3.2.2 # Version of Mongo to use. # REDIS (RedisProperties) spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster. spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from. spring.redis.database=0 # Database index used by the connection factory. spring.redis.url= # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379 spring.redis.host=localhost # Redis server host. spring.redis.jedis.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. spring.redis.jedis.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. spring.redis.jedis.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. spring.redis.jedis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive. spring.redis.lettuce.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. spring.redis.lettuce.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. spring.redis.lettuce.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. spring.redis.lettuce.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive. spring.redis.lettuce.shutdown-timeout=100ms # Shutdown timeout. spring.redis.password= # Login password of the redis server. spring.redis.port=6379 # Redis server port. spring.redis.sentinel.master= # Name of the Redis server. spring.redis.sentinel.nodes= # Comma-separated list of "host:port" pairs. spring.redis.ssl=false # Whether to enable SSL support. spring.redis.timeout= # Connection timeout. # TRANSACTION (TransactionProperties) spring.transaction.default-timeout= # Default transaction timeout. If a duration suffix is not specified, seconds will be used. spring.transaction.rollback-on-commit-failure= # Whether to roll back on commit failures. # ---------------------------------------- # INTEGRATION PROPERTIES # ---------------------------------------- # ACTIVEMQ (ActiveMQProperties) spring.activemq.broker-url= # URL of the ActiveMQ broker. Auto-generated by default. spring.activemq.close-timeout=15s # Time to wait before considering a close complete. spring.activemq.in-memory=true # Whether the default broker URL should be in memory. Ignored if an explicit broker has been specified. spring.activemq.non-blocking-redelivery=false # Whether to stop message delivery before re-delivering messages from a rolled back transaction. This implies that message order is not preserved when this is enabled. spring.activemq.password= # Login password of the broker. spring.activemq.send-timeout=0ms # Time to wait on message sends for a response. Set it to 0 to wait forever. spring.activemq.user= # Login user of the broker. spring.activemq.packages.trust-all= # Whether to trust all packages. spring.activemq.packages.trusted= # Comma-separated list of specific packages to trust (when not trusting all packages). spring.activemq.pool.block-if-full=true # Whether to block when a connection is requested and the pool is full. Set it to false to throw a "JMSException" instead. spring.activemq.pool.block-if-full-timeout=-1ms # Blocking period before throwing an exception if the pool is still full. spring.activemq.pool.enabled=false # Whether a JmsPoolConnectionFactory should be created, instead of a regular ConnectionFactory. spring.activemq.pool.idle-timeout=30s # Connection idle timeout. spring.activemq.pool.max-connections=1 # Maximum number of pooled connections. spring.activemq.pool.max-sessions-per-connection=500 # Maximum number of pooled sessions per connection in the pool. spring.activemq.pool.time-between-expiration-check=-1ms # Time to sleep between runs of the idle connection eviction thread. When negative, no idle connection eviction thread runs. spring.activemq.pool.use-anonymous-producers=true # Whether to use only one anonymous "MessageProducer" instance. Set it to false to create one "MessageProducer" every time one is required. # ARTEMIS (ArtemisProperties) spring.artemis.embedded.cluster-password= # Cluster password. Randomly generated on startup by default. spring.artemis.embedded.data-directory= # Journal file directory. Not necessary if persistence is turned off. spring.artemis.embedded.enabled=true # Whether to enable embedded mode if the Artemis server APIs are available. spring.artemis.embedded.persistent=false # Whether to enable persistent store. spring.artemis.embedded.queues= # Comma-separated list of queues to create on startup. spring.artemis.embedded.server-id= # Server ID. By default, an auto-incremented counter is used. spring.artemis.embedded.topics= # Comma-separated list of topics to create on startup. spring.artemis.host=localhost # Artemis broker host. spring.artemis.mode= # Artemis deployment mode, auto-detected by default. spring.artemis.password= # Login password of the broker. spring.artemis.pool.block-if-full=true # Whether to block when a connection is requested and the pool is full. Set it to false to throw a "JMSException" instead. spring.artemis.pool.block-if-full-timeout=-1ms # Blocking period before throwing an exception if the pool is still full. spring.artemis.pool.enabled=false # Whether a JmsPoolConnectionFactory should be created, instead of a regular ConnectionFactory. spring.artemis.pool.idle-timeout=30s # Connection idle timeout. spring.artemis.pool.max-connections=1 # Maximum number of pooled connections. spring.artemis.pool.max-sessions-per-connection=500 # Maximum number of pooled sessions per connection in the pool. spring.artemis.pool.time-between-expiration-check=-1ms # Time to sleep between runs of the idle connection eviction thread. When negative, no idle connection eviction thread runs. spring.artemis.pool.use-anonymous-producers=true # Whether to use only one anonymous "MessageProducer" instance. Set it to false to create one "MessageProducer" every time one is required. spring.artemis.port=61616 # Artemis broker port. spring.artemis.user= # Login user of the broker. # SPRING BATCH (BatchProperties) spring.batch.initialize-schema=embedded # Database schema initialization mode. spring.batch.job.enabled=true # Execute all Spring Batch jobs in the context on startup. spring.batch.job.names= # Comma-separated list of job names to execute on startup (for instance, `job1,job2`). By default, all Jobs found in the context are executed. spring.batch.schema=classpath:org/springframework/batch/core/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. spring.batch.table-prefix= # Table prefix for all the batch meta-data tables. # SPRING INTEGRATION (IntegrationProperties) spring.integration.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.integration.jdbc.schema=classpath:org/springframework/integration/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. # JMS (JmsProperties) spring.jms.cache.consumers=false # Whether to cache message consumers. spring.jms.cache.enabled=true # Whether to cache sessions. spring.jms.cache.producers=true # Whether to cache message producers. spring.jms.cache.session-cache-size=1 # Size of the session cache (per JMS Session type). spring.jms.jndi-name= # Connection factory JNDI name. When set, takes precedence to others connection factory auto-configurations. spring.jms.listener.acknowledge-mode= # Acknowledge mode of the container. By default, the listener is transacted with automatic acknowledgment. spring.jms.listener.auto-startup=true # Start the container automatically on startup. spring.jms.listener.concurrency= # Minimum number of concurrent consumers. spring.jms.listener.max-concurrency= # Maximum number of concurrent consumers. spring.jms.pub-sub-domain=false # Whether the default destination type is topic. spring.jms.template.default-destination= # Default destination to use on send and receive operations that do not have a destination parameter. spring.jms.template.delivery-delay= # Delivery delay to use for send calls. spring.jms.template.delivery-mode= # Delivery mode. Enables QoS (Quality of Service) when set. spring.jms.template.priority= # Priority of a message when sending. Enables QoS (Quality of Service) when set. spring.jms.template.qos-enabled= # Whether to enable explicit QoS (Quality of Service) when sending a message. spring.jms.template.receive-timeout= # Timeout to use for receive calls. spring.jms.template.time-to-live= # Time-to-live of a message when sending. Enables QoS (Quality of Service) when set. # APACHE KAFKA (KafkaProperties) spring.kafka.admin.client-id= # ID to pass to the server when making requests. Used for server-side logging. spring.kafka.admin.fail-fast=false # Whether to fail fast if the broker is not available on startup. spring.kafka.admin.properties.*= # Additional admin-specific properties used to configure the client. spring.kafka.admin.ssl.key-password= # Password of the private key in the key store file. spring.kafka.admin.ssl.key-store-location= # Location of the key store file. spring.kafka.admin.ssl.key-store-password= # Store password for the key store file. spring.kafka.admin.ssl.key-store-type= # Type of the key store. spring.kafka.admin.ssl.protocol= # SSL protocol to use. spring.kafka.admin.ssl.trust-store-location= # Location of the trust store file. spring.kafka.admin.ssl.trust-store-password= # Store password for the trust store file. spring.kafka.admin.ssl.trust-store-type= # Type of the trust store. spring.kafka.bootstrap-servers= # Comma-delimited list of host:port pairs to use for establishing the initial connections to the Kafka cluster. Applies to all components unless overridden. spring.kafka.client-id= # ID to pass to the server when making requests. Used for server-side logging. spring.kafka.consumer.auto-commit-interval= # Frequency with which the consumer offsets are auto-committed to Kafka if 'enable.auto.commit' is set to true. spring.kafka.consumer.auto-offset-reset= # What to do when there is no initial offset in Kafka or if the current offset no longer exists on the server. spring.kafka.consumer.bootstrap-servers= # Comma-delimited list of host:port pairs to use for establishing the initial connections to the Kafka cluster. Overrides the global property, for consumers. spring.kafka.consumer.client-id= # ID to pass to the server when making requests. Used for server-side logging. spring.kafka.consumer.enable-auto-commit= # Whether the consumer's offset is periodically committed in the background. spring.kafka.consumer.fetch-max-wait= # Maximum amount of time the server blocks before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by "fetch-min-size". spring.kafka.consumer.fetch-min-size= # Minimum amount of data the server should return for a fetch request. spring.kafka.consumer.group-id= # Unique string that identifies the consumer group to which this consumer belongs. spring.kafka.consumer.heartbeat-interval= # Expected time between heartbeats to the consumer coordinator. spring.kafka.consumer.key-deserializer= # Deserializer class for keys. spring.kafka.consumer.max-poll-records= # Maximum number of records returned in a single call to poll(). spring.kafka.consumer.properties.*= # Additional consumer-specific properties used to configure the client. spring.kafka.consumer.ssl.key-password= # Password of the private key in the key store file. spring.kafka.consumer.ssl.key-store-location= # Location of the key store file. spring.kafka.consumer.ssl.key-store-password= # Store password for the key store file. spring.kafka.consumer.ssl.key-store-type= # Type of the key store. spring.kafka.consumer.ssl.protocol= # SSL protocol to use. spring.kafka.consumer.ssl.trust-store-location= # Location of the trust store file. spring.kafka.consumer.ssl.trust-store-password= # Store password for the trust store file. spring.kafka.consumer.ssl.trust-store-type= # Type of the trust store. spring.kafka.consumer.value-deserializer= # Deserializer class for values. spring.kafka.jaas.control-flag=required # Control flag for login configuration. spring.kafka.jaas.enabled=false # Whether to enable JAAS configuration. spring.kafka.jaas.login-module=com.sun.security.auth.module.Krb5LoginModule # Login module. spring.kafka.jaas.options= # Additional JAAS options. spring.kafka.listener.ack-count= # Number of records between offset commits when ackMode is "COUNT" or "COUNT_TIME". spring.kafka.listener.ack-mode= # Listener AckMode. See the spring-kafka documentation. spring.kafka.listener.ack-time= # Time between offset commits when ackMode is "TIME" or "COUNT_TIME". spring.kafka.listener.client-id= # Prefix for the listener's consumer client.id property. spring.kafka.listener.concurrency= # Number of threads to run in the listener containers. spring.kafka.listener.idle-event-interval= # Time between publishing idle consumer events (no data received). spring.kafka.listener.log-container-config= # Whether to log the container configuration during initialization (INFO level). spring.kafka.listener.monitor-interval= # Time between checks for non-responsive consumers. If a duration suffix is not specified, seconds will be used. spring.kafka.listener.no-poll-threshold= # Multiplier applied to "pollTimeout" to determine if a consumer is non-responsive. spring.kafka.listener.poll-timeout= # Timeout to use when polling the consumer. spring.kafka.listener.type=single # Listener type. spring.kafka.producer.acks= # Number of acknowledgments the producer requires the leader to have received before considering a request complete. spring.kafka.producer.batch-size= # Default batch size. spring.kafka.producer.bootstrap-servers= # Comma-delimited list of host:port pairs to use for establishing the initial connections to the Kafka cluster. Overrides the global property, for producers. spring.kafka.producer.buffer-memory= # Total memory size the producer can use to buffer records waiting to be sent to the server. spring.kafka.producer.client-id= # ID to pass to the server when making requests. Used for server-side logging. spring.kafka.producer.compression-type= # Compression type for all data generated by the producer. spring.kafka.producer.key-serializer= # Serializer class for keys. spring.kafka.producer.properties.*= # Additional producer-specific properties used to configure the client. spring.kafka.producer.retries= # When greater than zero, enables retrying of failed sends. spring.kafka.producer.ssl.key-password= # Password of the private key in the key store file. spring.kafka.producer.ssl.key-store-location= # Location of the key store file. spring.kafka.producer.ssl.key-store-password= # Store password for the key store file. spring.kafka.producer.ssl.key-store-type= # Type of the key store. spring.kafka.producer.ssl.protocol= # SSL protocol to use. spring.kafka.producer.ssl.trust-store-location= # Location of the trust store file. spring.kafka.producer.ssl.trust-store-password= # Store password for the trust store file. spring.kafka.producer.ssl.trust-store-type= # Type of the trust store. spring.kafka.producer.transaction-id-prefix= # When non empty, enables transaction support for producer. spring.kafka.producer.value-serializer= # Serializer class for values. spring.kafka.properties.*= # Additional properties, common to producers and consumers, used to configure the client. spring.kafka.ssl.key-password= # Password of the private key in the key store file. spring.kafka.ssl.key-store-location= # Location of the key store file. spring.kafka.ssl.key-store-password= # Store password for the key store file. spring.kafka.ssl.key-store-type= # Type of the key store. spring.kafka.ssl.protocol= # SSL protocol to use. spring.kafka.ssl.trust-store-location= # Location of the trust store file. spring.kafka.ssl.trust-store-password= # Store password for the trust store file. spring.kafka.ssl.trust-store-type= # Type of the trust store. spring.kafka.streams.application-id= # Kafka streams application.id property; default spring.application.name. spring.kafka.streams.auto-startup=true # Whether or not to auto-start the streams factory bean. spring.kafka.streams.bootstrap-servers= # Comma-delimited list of host:port pairs to use for establishing the initial connections to the Kafka cluster. Overrides the global property, for streams. spring.kafka.streams.cache-max-size-buffering= # Maximum memory size to be used for buffering across all threads. spring.kafka.streams.client-id= # ID to pass to the server when making requests. Used for server-side logging. spring.kafka.streams.properties.*= # Additional Kafka properties used to configure the streams. spring.kafka.streams.replication-factor= # The replication factor for change log topics and repartition topics created by the stream processing application. spring.kafka.streams.ssl.key-password= # Password of the private key in the key store file. spring.kafka.streams.ssl.key-store-location= # Location of the key store file. spring.kafka.streams.ssl.key-store-password= # Store password for the key store file. spring.kafka.streams.ssl.key-store-type= # Type of the key store. spring.kafka.streams.ssl.protocol= # SSL protocol to use. spring.kafka.streams.ssl.trust-store-location= # Location of the trust store file. spring.kafka.streams.ssl.trust-store-password= # Store password for the trust store file. spring.kafka.streams.ssl.trust-store-type= # Type of the trust store. spring.kafka.streams.state-dir= # Directory location for the state store. spring.kafka.template.default-topic= # Default topic to which messages are sent. # RABBIT (RabbitProperties) spring.rabbitmq.addresses= # Comma-separated list of addresses to which the client should connect. spring.rabbitmq.cache.channel.checkout-timeout= # Duration to wait to obtain a channel if the cache size has been reached. spring.rabbitmq.cache.channel.size= # Number of channels to retain in the cache. spring.rabbitmq.cache.connection.mode=channel # Connection factory cache mode. spring.rabbitmq.cache.connection.size= # Number of connections to cache. spring.rabbitmq.connection-timeout= # Connection timeout. Set it to zero to wait forever. spring.rabbitmq.dynamic=true # Whether to create an AmqpAdmin bean. spring.rabbitmq.host=localhost # RabbitMQ host. spring.rabbitmq.listener.direct.acknowledge-mode= # Acknowledge mode of container. spring.rabbitmq.listener.direct.auto-startup=true # Whether to start the container automatically on startup. spring.rabbitmq.listener.direct.consumers-per-queue= # Number of consumers per queue. spring.rabbitmq.listener.direct.default-requeue-rejected= # Whether rejected deliveries are re-queued by default. spring.rabbitmq.listener.direct.idle-event-interval= # How often idle container events should be published. spring.rabbitmq.listener.direct.missing-queues-fatal=false # Whether to fail if the queues declared by the container are not available on the broker. spring.rabbitmq.listener.direct.prefetch= # Maximum number of unacknowledged messages that can be outstanding at each consumer. spring.rabbitmq.listener.direct.retry.enabled=false # Whether publishing retries are enabled. spring.rabbitmq.listener.direct.retry.initial-interval=1000ms # Duration between the first and second attempt to deliver a message. spring.rabbitmq.listener.direct.retry.max-attempts=3 # Maximum number of attempts to deliver a message. spring.rabbitmq.listener.direct.retry.max-interval=10000ms # Maximum duration between attempts. spring.rabbitmq.listener.direct.retry.multiplier=1 # Multiplier to apply to the previous retry interval. spring.rabbitmq.listener.direct.retry.stateless=true # Whether retries are stateless or stateful. spring.rabbitmq.listener.simple.acknowledge-mode= # Acknowledge mode of container. spring.rabbitmq.listener.simple.auto-startup=true # Whether to start the container automatically on startup. spring.rabbitmq.listener.simple.concurrency= # Minimum number of listener invoker threads. spring.rabbitmq.listener.simple.default-requeue-rejected= # Whether rejected deliveries are re-queued by default. spring.rabbitmq.listener.simple.idle-event-interval= # How often idle container events should be published. spring.rabbitmq.listener.simple.max-concurrency= # Maximum number of listener invoker threads. spring.rabbitmq.listener.simple.missing-queues-fatal=true # Whether to fail if the queues declared by the container are not available on the broker and/or whether to stop the container if one or more queues are deleted at runtime. spring.rabbitmq.listener.simple.prefetch= # Maximum number of unacknowledged messages that can be outstanding at each consumer. spring.rabbitmq.listener.simple.retry.enabled=false # Whether publishing retries are enabled. spring.rabbitmq.listener.simple.retry.initial-interval=1000ms # Duration between the first and second attempt to deliver a message. spring.rabbitmq.listener.simple.retry.max-attempts=3 # Maximum number of attempts to deliver a message. spring.rabbitmq.listener.simple.retry.max-interval=10000ms # Maximum duration between attempts. spring.rabbitmq.listener.simple.retry.multiplier=1 # Multiplier to apply to the previous retry interval. spring.rabbitmq.listener.simple.retry.stateless=true # Whether retries are stateless or stateful. spring.rabbitmq.listener.simple.transaction-size= # Number of messages to be processed between acks when the acknowledge mode is AUTO. If larger than prefetch, prefetch will be increased to this value. spring.rabbitmq.listener.type=simple # Listener container type. spring.rabbitmq.password=guest # Login to authenticate against the broker. spring.rabbitmq.port=5672 # RabbitMQ port. spring.rabbitmq.publisher-confirms=false # Whether to enable publisher confirms. spring.rabbitmq.publisher-returns=false # Whether to enable publisher returns. spring.rabbitmq.requested-heartbeat= # Requested heartbeat timeout; zero for none. If a duration suffix is not specified, seconds will be used. spring.rabbitmq.ssl.algorithm= # SSL algorithm to use. By default, configured by the Rabbit client library. spring.rabbitmq.ssl.enabled=false # Whether to enable SSL support. spring.rabbitmq.ssl.key-store= # Path to the key store that holds the SSL certificate. spring.rabbitmq.ssl.key-store-password= # Password used to access the key store. spring.rabbitmq.ssl.key-store-type=PKCS12 # Key store type. spring.rabbitmq.ssl.trust-store= # Trust store that holds SSL certificates. spring.rabbitmq.ssl.trust-store-password= # Password used to access the trust store. spring.rabbitmq.ssl.trust-store-type=JKS # Trust store type. spring.rabbitmq.ssl.validate-server-certificate=true # Whether to enable server side certificate validation. spring.rabbitmq.ssl.verify-hostname=true # Whether to enable hostname verification. spring.rabbitmq.template.exchange= # Name of the default exchange to use for send operations. spring.rabbitmq.template.mandatory= # Whether to enable mandatory messages. spring.rabbitmq.template.queue= # Name of the default queue to receive messages from when none is specified explicitly. spring.rabbitmq.template.receive-timeout= # Timeout for `receive()` operations. spring.rabbitmq.template.reply-timeout= # Timeout for `sendAndReceive()` operations. spring.rabbitmq.template.retry.enabled=false # Whether publishing retries are enabled. spring.rabbitmq.template.retry.initial-interval=1000ms # Duration between the first and second attempt to deliver a message. spring.rabbitmq.template.retry.max-attempts=3 # Maximum number of attempts to deliver a message. spring.rabbitmq.template.retry.max-interval=10000ms # Maximum duration between attempts. spring.rabbitmq.template.retry.multiplier=1 # Multiplier to apply to the previous retry interval. spring.rabbitmq.template.routing-key= # Value of a default routing key to use for send operations. spring.rabbitmq.username=guest # Login user to authenticate to the broker. spring.rabbitmq.virtual-host= # Virtual host to use when connecting to the broker. # ---------------------------------------- # ACTUATOR PROPERTIES # ---------------------------------------- # MANAGEMENT HTTP SERVER (ManagementServerProperties) management.server.add-application-context-header=false # Add the "X-Application-Context" HTTP header in each response. management.server.address= # Network address to which the management endpoints should bind. Requires a custom management.server.port. management.server.port= # Management endpoint HTTP port (uses the same port as the application by default). Configure a different port to use management-specific SSL. management.server.servlet.context-path= # Management endpoint context-path (for instance, `/management`). Requires a custom management.server.port. management.server.ssl.ciphers= # Supported SSL ciphers. Requires a custom management.port. management.server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. Requires a custom management.server.port. management.server.ssl.enabled= # Whether to enable SSL support. Requires a custom management.server.port. management.server.ssl.enabled-protocols= # Enabled SSL protocols. Requires a custom management.server.port. management.server.ssl.key-alias= # Alias that identifies the key in the key store. Requires a custom management.server.port. management.server.ssl.key-password= # Password used to access the key in the key store. Requires a custom management.server.port. management.server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file). Requires a custom management.server.port. management.server.ssl.key-store-password= # Password used to access the key store. Requires a custom management.server.port. management.server.ssl.key-store-provider= # Provider for the key store. Requires a custom management.server.port. management.server.ssl.key-store-type= # Type of the key store. Requires a custom management.server.port. management.server.ssl.protocol=TLS # SSL protocol to use. Requires a custom management.server.port. management.server.ssl.trust-store= # Trust store that holds SSL certificates. Requires a custom management.server.port. management.server.ssl.trust-store-password= # Password used to access the trust store. Requires a custom management.server.port. management.server.ssl.trust-store-provider= # Provider for the trust store. Requires a custom management.server.port. management.server.ssl.trust-store-type= # Type of the trust store. Requires a custom management.server.port. # CLOUDFOUNDRY management.cloudfoundry.enabled=true # Whether to enable extended Cloud Foundry actuator endpoints. management.cloudfoundry.skip-ssl-validation=false # Whether to skip SSL verification for Cloud Foundry actuator endpoint security calls. # ENDPOINTS GENERAL CONFIGURATION management.endpoints.enabled-by-default= # Whether to enable or disable all endpoints by default. # ENDPOINTS JMX CONFIGURATION (JmxEndpointProperties) management.endpoints.jmx.domain=org.springframework.boot # Endpoints JMX domain name. Fallback to 'spring.jmx.default-domain' if set. management.endpoints.jmx.exposure.include=* # Endpoint IDs that should be included or '*' for all. management.endpoints.jmx.exposure.exclude= # Endpoint IDs that should be excluded or '*' for all. management.endpoints.jmx.static-names= # Additional static properties to append to all ObjectNames of MBeans representing Endpoints. # ENDPOINTS WEB CONFIGURATION (WebEndpointProperties) management.endpoints.web.exposure.include=health,info # Endpoint IDs that should be included or '*' for all. management.endpoints.web.exposure.exclude= # Endpoint IDs that should be excluded or '*' for all. management.endpoints.web.base-path=/actuator # Base path for Web endpoints. Relative to server.servlet.context-path or management.server.servlet.context-path if management.server.port is configured. management.endpoints.web.path-mapping= # Mapping between endpoint IDs and the path that should expose them. # ENDPOINTS CORS CONFIGURATION (CorsEndpointProperties) management.endpoints.web.cors.allow-credentials= # Whether credentials are supported. When not set, credentials are not supported. management.endpoints.web.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers. management.endpoints.web.cors.allowed-methods= # Comma-separated list of methods to allow. '*' allows all methods. When not set, defaults to GET. management.endpoints.web.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled. management.endpoints.web.cors.exposed-headers= # Comma-separated list of headers to include in a response. management.endpoints.web.cors.max-age=1800s # How long the response from a pre-flight request can be cached by clients. If a duration suffix is not specified, seconds will be used. # AUDIT EVENTS ENDPOINT (AuditEventsEndpoint) management.endpoint.auditevents.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.auditevents.enabled=true # Whether to enable the auditevents endpoint. # BEANS ENDPOINT (BeansEndpoint) management.endpoint.beans.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.beans.enabled=true # Whether to enable the beans endpoint. # CACHES ENDPOINT (CachesEndpoint) management.endpoint.caches.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.caches.enabled=true # Whether to enable the caches endpoint. # CONDITIONS REPORT ENDPOINT (ConditionsReportEndpoint) management.endpoint.conditions.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.conditions.enabled=true # Whether to enable the conditions endpoint. # CONFIGURATION PROPERTIES REPORT ENDPOINT (ConfigurationPropertiesReportEndpoint, ConfigurationPropertiesReportEndpointProperties) management.endpoint.configprops.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.configprops.enabled=true # Whether to enable the configprops endpoint. management.endpoint.configprops.keys-to-sanitize=password,secret,key,token,.*credentials.*,vcap_services,sun.java.command # Keys that should be sanitized. Keys can be simple strings that the property ends with or regular expressions. # ENVIRONMENT ENDPOINT (EnvironmentEndpoint, EnvironmentEndpointProperties) management.endpoint.env.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.env.enabled=true # Whether to enable the env endpoint. management.endpoint.env.keys-to-sanitize=password,secret,key,token,.*credentials.*,vcap_services,sun.java.command # Keys that should be sanitized. Keys can be simple strings that the property ends with or regular expressions. # FLYWAY ENDPOINT (FlywayEndpoint) management.endpoint.flyway.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.flyway.enabled=true # Whether to enable the flyway endpoint. # HEALTH ENDPOINT (HealthEndpoint, HealthEndpointProperties) management.endpoint.health.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.health.enabled=true # Whether to enable the health endpoint. management.endpoint.health.roles= # Roles used to determine whether or not a user is authorized to be shown details. When empty, all authenticated users are authorized. management.endpoint.health.show-details=never # When to show full health details. # HEAP DUMP ENDPOINT (HeapDumpWebEndpoint) management.endpoint.heapdump.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.heapdump.enabled=true # Whether to enable the heapdump endpoint. # HTTP TRACE ENDPOINT (HttpTraceEndpoint) management.endpoint.httptrace.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.httptrace.enabled=true # Whether to enable the httptrace endpoint. # INFO ENDPOINT (InfoEndpoint) info= # Arbitrary properties to add to the info endpoint. management.endpoint.info.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.info.enabled=true # Whether to enable the info endpoint. # INTEGRATION GRAPH ENDPOINT (IntegrationGraphEndpoint) management.endpoint.integrationgraph.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.integrationgraph.enabled=true # Whether to enable the integrationgraph endpoint. # JOLOKIA ENDPOINT (JolokiaProperties) management.endpoint.jolokia.config.*= # Jolokia settings. Refer to the documentation of Jolokia for more details. management.endpoint.jolokia.enabled=true # Whether to enable the jolokia endpoint. # LIQUIBASE ENDPOINT (LiquibaseEndpoint) management.endpoint.liquibase.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.liquibase.enabled=true # Whether to enable the liquibase endpoint. # LOG FILE ENDPOINT (LogFileWebEndpoint, LogFileWebEndpointProperties) management.endpoint.logfile.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.logfile.enabled=true # Whether to enable the logfile endpoint. management.endpoint.logfile.external-file= # External Logfile to be accessed. Can be used if the logfile is written by output redirect and not by the logging system itself. # LOGGERS ENDPOINT (LoggersEndpoint) management.endpoint.loggers.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.loggers.enabled=true # Whether to enable the loggers endpoint. # REQUEST MAPPING ENDPOINT (MappingsEndpoint) management.endpoint.mappings.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.mappings.enabled=true # Whether to enable the mappings endpoint. # METRICS ENDPOINT (MetricsEndpoint) management.endpoint.metrics.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.metrics.enabled=true # Whether to enable the metrics endpoint. # PROMETHEUS ENDPOINT (PrometheusScrapeEndpoint) management.endpoint.prometheus.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.prometheus.enabled=true # Whether to enable the prometheus endpoint. # SCHEDULED TASKS ENDPOINT (ScheduledTasksEndpoint) management.endpoint.scheduledtasks.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.scheduledtasks.enabled=true # Whether to enable the scheduledtasks endpoint. # SESSIONS ENDPOINT (SessionsEndpoint) management.endpoint.sessions.enabled=true # Whether to enable the sessions endpoint. # SHUTDOWN ENDPOINT (ShutdownEndpoint) management.endpoint.shutdown.enabled=false # Whether to enable the shutdown endpoint. # THREAD DUMP ENDPOINT (ThreadDumpEndpoint) management.endpoint.threaddump.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.threaddump.enabled=true # Whether to enable the threaddump endpoint. # HEALTH INDICATORS management.health.db.enabled=true # Whether to enable database health check. management.health.cassandra.enabled=true # Whether to enable Cassandra health check. management.health.couchbase.enabled=true # Whether to enable Couchbase health check. management.health.couchbase.timeout=1000ms # Timeout for getting the Bucket information from the server. management.health.defaults.enabled=true # Whether to enable default health indicators. management.health.diskspace.enabled=true # Whether to enable disk space health check. management.health.diskspace.path= # Path used to compute the available disk space. management.health.diskspace.threshold=10MB # Minimum disk space that should be available. management.health.elasticsearch.enabled=true # Whether to enable Elasticsearch health check. management.health.elasticsearch.indices= # Comma-separated index names. management.health.elasticsearch.response-timeout=100ms # Time to wait for a response from the cluster. management.health.influxdb.enabled=true # Whether to enable InfluxDB health check. management.health.jms.enabled=true # Whether to enable JMS health check. management.health.ldap.enabled=true # Whether to enable LDAP health check. management.health.mail.enabled=true # Whether to enable Mail health check. management.health.mongo.enabled=true # Whether to enable MongoDB health check. management.health.neo4j.enabled=true # Whether to enable Neo4j health check. management.health.rabbit.enabled=true # Whether to enable RabbitMQ health check. management.health.redis.enabled=true # Whether to enable Redis health check. management.health.solr.enabled=true # Whether to enable Solr health check. management.health.status.http-mapping= # Mapping of health statuses to HTTP status codes. By default, registered health statuses map to sensible defaults (for example, UP maps to 200). management.health.status.order=DOWN,OUT_OF_SERVICE,UP,UNKNOWN # Comma-separated list of health statuses in order of severity. # HTTP TRACING (HttpTraceProperties) management.trace.http.enabled=true # Whether to enable HTTP request-response tracing. management.trace.http.include=request-headers,response-headers,cookies,errors # Items to be included in the trace. # INFO CONTRIBUTORS (InfoContributorProperties) management.info.build.enabled=true # Whether to enable build info. management.info.defaults.enabled=true # Whether to enable default info contributors. management.info.env.enabled=true # Whether to enable environment info. management.info.git.enabled=true # Whether to enable git info. management.info.git.mode=simple # Mode to use to expose git information. # METRICS management.metrics.distribution.percentiles-histogram.*= # Whether meter IDs starting with the specified name should publish percentile histograms. management.metrics.distribution.percentiles.*= # Specific computed non-aggregable percentiles to ship to the backend for meter IDs starting-with the specified name. management.metrics.distribution.sla.*= # Specific SLA boundaries for meter IDs starting-with the specified name. The longest match wins, the key `all` can also be used to configure all meters. management.metrics.enable.*= # Whether meter IDs starting-with the specified name should be enabled. The longest match wins, the key `all` can also be used to configure all meters. management.metrics.export.atlas.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.atlas.config-refresh-frequency=10s # Frequency for refreshing config settings from the LWC service. management.metrics.export.atlas.config-time-to-live=150s # Time to live for subscriptions from the LWC service. management.metrics.export.atlas.config-uri=http://localhost:7101/lwc/api/v1/expressions/local-dev # URI for the Atlas LWC endpoint to retrieve current subscriptions. management.metrics.export.atlas.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.atlas.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.atlas.eval-uri=http://localhost:7101/lwc/api/v1/evaluate # URI for the Atlas LWC endpoint to evaluate the data for a subscription. management.metrics.export.atlas.lwc-enabled=false # Whether to enable streaming to Atlas LWC. management.metrics.export.atlas.meter-time-to-live=15m # Time to live for meters that do not have any activity. After this period the meter will be considered expired and will not get reported. management.metrics.export.atlas.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.atlas.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.atlas.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.atlas.uri=http://localhost:7101/api/v1/publish # URI of the Atlas server. management.metrics.export.datadog.api-key= # Datadog API key. management.metrics.export.datadog.application-key= # Datadog application key. Not strictly required, but improves the Datadog experience by sending meter descriptions, types, and base units to Datadog. management.metrics.export.datadog.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.datadog.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.datadog.descriptions=true # Whether to publish descriptions metadata to Datadog. Turn this off to minimize the amount of metadata sent. management.metrics.export.datadog.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.datadog.host-tag=instance # Tag that will be mapped to "host" when shipping metrics to Datadog. management.metrics.export.datadog.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.datadog.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.datadog.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.datadog.uri=https://app.datadoghq.com # URI to ship metrics to. If you need to publish metrics to an internal proxy en-route to Datadog, you can define the location of the proxy with this. management.metrics.export.dynatrace.api-token= # Dynatrace authentication token. management.metrics.export.dynatrace.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.dynatrace.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.dynatrace.device-id= # ID of the custom device that is exporting metrics to Dynatrace. management.metrics.export.dynatrace.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.dynatrace.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.dynatrace.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.dynatrace.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.dynatrace.technology-type=java # Technology type for exported metrics. Used to group metrics under a logical technology name in the Dynatrace UI. management.metrics.export.dynatrace.uri= # URI to ship metrics to. Should be used for SaaS, self managed instances or to en-route through an internal proxy. management.metrics.export.elastic.auto-create-index=true # Whether to create the index automatically if it does not exist. management.metrics.export.elastic.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.elastic.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.elastic.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.elastic.hosts=http://localhost:9200 # Hosts to export metrics to. management.metrics.export.elastic.index=metrics # Index to export metrics to. management.metrics.export.elastic.index-date-format=yyyy-MM # Index date format used for rolling indices. Appended to the index name, preceded by a '-'. management.metrics.export.elastic.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.elastic.password= # Login password of the Elastic server. management.metrics.export.elastic.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.elastic.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.elastic.timestamp-field-name=@timestamp # Name of the timestamp field. management.metrics.export.elastic.user-name= # Login user of the Elastic server. management.metrics.export.ganglia.addressing-mode=multicast # UDP addressing mode, either unicast or multicast. management.metrics.export.ganglia.duration-units=milliseconds # Base time unit used to report durations. management.metrics.export.ganglia.enabled=true # Whether exporting of metrics to Ganglia is enabled. management.metrics.export.ganglia.host=localhost # Host of the Ganglia server to receive exported metrics. management.metrics.export.ganglia.port=8649 # Port of the Ganglia server to receive exported metrics. management.metrics.export.ganglia.protocol-version=3.1 # Ganglia protocol version. Must be either 3.1 or 3.0. management.metrics.export.ganglia.rate-units=seconds # Base time unit used to report rates. management.metrics.export.ganglia.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.ganglia.time-to-live=1 # Time to live for metrics on Ganglia. Set the multi-cast Time-To-Live to be one greater than the number of hops (routers) between the hosts. management.metrics.export.graphite.duration-units=milliseconds # Base time unit used to report durations. management.metrics.export.graphite.enabled=true # Whether exporting of metrics to Graphite is enabled. management.metrics.export.graphite.host=localhost # Host of the Graphite server to receive exported metrics. management.metrics.export.graphite.port=2004 # Port of the Graphite server to receive exported metrics. management.metrics.export.graphite.protocol=pickled # Protocol to use while shipping data to Graphite. management.metrics.export.graphite.rate-units=seconds # Base time unit used to report rates. management.metrics.export.graphite.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.graphite.tags-as-prefix= # For the default naming convention, turn the specified tag keys into part of the metric prefix. management.metrics.export.influx.auto-create-db=true # Whether to create the Influx database if it does not exist before attempting to publish metrics to it. management.metrics.export.influx.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.influx.compressed=true # Whether to enable GZIP compression of metrics batches published to Influx. management.metrics.export.influx.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.influx.consistency=one # Write consistency for each point. management.metrics.export.influx.db=mydb # Tag that will be mapped to "host" when shipping metrics to Influx. management.metrics.export.influx.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.influx.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.influx.password= # Login password of the Influx server. management.metrics.export.influx.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.influx.retention-duration= # Time period for which Influx should retain data in the current database. management.metrics.export.influx.retention-shard-duration= # Time range covered by a shard group. management.metrics.export.influx.retention-policy= # Retention policy to use (Influx writes to the DEFAULT retention policy if one is not specified). management.metrics.export.influx.retention-replication-factor= # How many copies of the data are stored in the cluster. management.metrics.export.influx.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.influx.uri=http://localhost:8086 # URI of the Influx server. management.metrics.export.influx.user-name= # Login user of the Influx server. management.metrics.export.jmx.domain=metrics # Metrics JMX domain name. management.metrics.export.jmx.enabled=true # Whether exporting of metrics to JMX is enabled. management.metrics.export.jmx.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.newrelic.account-id= # New Relic account ID. management.metrics.export.newrelic.api-key= # New Relic API key. management.metrics.export.newrelic.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.newrelic.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.newrelic.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.newrelic.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.newrelic.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.newrelic.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.newrelic.uri=https://insights-collector.newrelic.com # URI to ship metrics to. management.metrics.export.prometheus.descriptions=true # Whether to enable publishing descriptions as part of the scrape payload to Prometheus. Turn this off to minimize the amount of data sent on each scrape. management.metrics.export.prometheus.enabled=true # Whether exporting of metrics to Prometheus is enabled. management.metrics.export.prometheus.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.signalfx.access-token= # SignalFX access token. management.metrics.export.signalfx.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.signalfx.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.signalfx.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.signalfx.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.signalfx.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.signalfx.source= # Uniquely identifies the app instance that is publishing metrics to SignalFx. Defaults to the local host name. management.metrics.export.signalfx.step=10s # Step size (i.e. reporting frequency) to use. management.metrics.export.signalfx.uri=https://ingest.signalfx.com # URI to ship metrics to. management.metrics.export.simple.enabled=true # Whether, in the absence of any other exporter, exporting of metrics to an in-memory backend is enabled. management.metrics.export.simple.mode=cumulative # Counting mode. management.metrics.export.simple.step=1m # Step size (i.e. reporting frequency) to use. management.metrics.export.statsd.enabled=true # Whether exporting of metrics to StatsD is enabled. management.metrics.export.statsd.flavor=datadog # StatsD line protocol to use. management.metrics.export.statsd.host=localhost # Host of the StatsD server to receive exported metrics. management.metrics.export.statsd.max-packet-length=1400 # Total length of a single payload should be kept within your network's MTU. management.metrics.export.statsd.polling-frequency=10s # How often gauges will be polled. When a gauge is polled, its value is recalculated and if the value has changed (or publishUnchangedMeters is true), it is sent to the StatsD server. management.metrics.export.statsd.port=8125 # Port of the StatsD server to receive exported metrics. management.metrics.export.statsd.publish-unchanged-meters=true # Whether to send unchanged meters to the StatsD server. management.metrics.export.wavefront.api-token= # API token used when publishing metrics directly to the Wavefront API host. management.metrics.export.wavefront.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. management.metrics.export.wavefront.connect-timeout=1s # Connection timeout for requests to this backend. management.metrics.export.wavefront.enabled=true # Whether exporting of metrics to this backend is enabled. management.metrics.export.wavefront.global-prefix= # Global prefix to separate metrics originating from this app's white box instrumentation from those originating from other Wavefront integrations when viewed in the Wavefront UI. management.metrics.export.wavefront.num-threads=2 # Number of threads to use with the metrics publishing scheduler. management.metrics.export.wavefront.read-timeout=10s # Read timeout for requests to this backend. management.metrics.export.wavefront.source= # Unique identifier for the app instance that is the source of metrics being published to Wavefront. Defaults to the local host name. management.metrics.export.wavefront.step=10s # Step size (i.e. reporting frequency) to use. management.metrics.export.wavefront.uri=https://longboard.wavefront.com # URI to ship metrics to. management.metrics.use-global-registry=true # Whether auto-configured MeterRegistry implementations should be bound to the global static registry on Metrics. management.metrics.tags.*= # Common tags that are applied to every meter. management.metrics.web.client.max-uri-tags=100 # Maximum number of unique URI tag values allowed. After the max number of tag values is reached, metrics with additional tag values are denied by filter. management.metrics.web.client.requests-metric-name=http.client.requests # Name of the metric for sent requests. management.metrics.web.server.auto-time-requests=true # Whether requests handled by Spring MVC or WebFlux should be automatically timed. management.metrics.web.server.max-uri-tags=100 # Maximum number of unique URI tag values allowed. After the max number of tag values is reached, metrics with additional tag values are denied by filter. management.metrics.web.server.requests-metric-name=http.server.requests # Name of the metric for received requests. # ---------------------------------------- # DEVTOOLS PROPERTIES # ---------------------------------------- # DEVTOOLS (DevToolsProperties) spring.devtools.add-properties=true # Whether to enable development property defaults. spring.devtools.livereload.enabled=true # Whether to enable a livereload.com-compatible server. spring.devtools.livereload.port=35729 # Server port. spring.devtools.restart.additional-exclude= # Additional patterns that should be excluded from triggering a full restart. spring.devtools.restart.additional-paths= # Additional paths to watch for changes. spring.devtools.restart.enabled=true # Whether to enable automatic restart. spring.devtools.restart.exclude=META-INF/maven/**,META-INF/resources/**,resources/**,static/**,public/**,templates/**,**/*Test.class,**/*Tests.class,git.properties,META-INF/build-info.properties # Patterns that should be excluded from triggering a full restart. spring.devtools.restart.log-condition-evaluation-delta=true # Whether to log the condition evaluation delta upon restart. spring.devtools.restart.poll-interval=1s # Amount of time to wait between polling for classpath changes. spring.devtools.restart.quiet-period=400ms # Amount of quiet time required without any classpath changes before a restart is triggered. spring.devtools.restart.trigger-file= # Name of a specific file that, when changed, triggers the restart check. If not specified, any classpath file change triggers the restart. # REMOTE DEVTOOLS (RemoteDevToolsProperties) spring.devtools.remote.context-path=/.~~spring-boot!~ # Context path used to handle the remote connection. spring.devtools.remote.proxy.host= # The host of the proxy to use to connect to the remote application. spring.devtools.remote.proxy.port= # The port of the proxy to use to connect to the remote application. spring.devtools.remote.restart.enabled=true # Whether to enable remote restart. spring.devtools.remote.secret= # A shared secret required to establish a connection (required to enable remote support). spring.devtools.remote.secret-header-name=X-AUTH-TOKEN # HTTP header used to transfer the shared secret. # ---------------------------------------- # TESTING PROPERTIES # ---------------------------------------- spring.test.database.replace=any # Type of existing DataSource to replace. spring.test.mockmvc.print=default # MVC Print option.
SpringBootJAR包括元数据文件,这些元数据文件提供了所有支持的配置属性的详细信息。这些文件旨在让IDE开发人员在用户使用时提供上下文帮助和“代码完成”。application.properties
或application.yml
档案。
元数据文件的大部分是在编译时通过处理带注释的所有项自动生成的。@ConfigurationProperties
。然而,它是有可能的手动编写部分元数据用于角用例或更高级的用例。
配置元数据文件位于META-INF/spring-configuration-metadata.json
它们使用简单的JSON格式,在“组”或“属性”下分类项,在“提示”下分类附加值提示,如下面的示例所示:
{"groups": [ { "name": "server", "type": "org.springframework.boot.autoconfigure.web.ServerProperties", "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" }, { "name": "spring.jpa.hibernate", "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate", "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties", "sourceMethod": "getHibernate()" } ... ],"properties": [ { "name": "server.port", "type": "java.lang.Integer", "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" }, { "name": "server.address", "type": "java.net.InetAddress", "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" }, { "name": "spring.jpa.hibernate.ddl-auto", "type": "java.lang.String", "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.", "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate" } ... ],"hints": [ { "name": "spring.jpa.hibernate.ddl-auto", "values": [ { "value": "none", "description": "Disable DDL handling." }, { "value": "validate", "description": "Validate the schema, make no changes to the database." }, { "value": "update", "description": "Update the schema if necessary." }, { "value": "create", "description": "Create the schema and destroy previous data." }, { "value": "create-drop", "description": "Create and then destroy the schema at the end of the session." } ] } ]}
每个“属性”都是用户用给定值指定的配置项。例如server.port
和server.address
中指定的application.properties
,如下:
- server.port=9090
- server.address=127.0.0.1
“组”是较高级别的项,它们本身不指定值,而是为属性提供上下文分组。例如,server.port
和server.address
属性是server
小组。
![]() |
并不要求每个“财产”都有一个“组”。某些属性本身可能存在。 |
最后,“提示”是用于帮助用户配置给定属性的附加信息。例如,当开发人员正在配置spring.jpa.hibernate.ddl-auto
属性时,工具可以使用提示为none
, validate
, update
, create
,和create-drop
价值。
对象中包含的JSON对象。groups
数组可以包含下表所示的属性:
名字,姓名 | 类型 | 目的 |
---|---|---|
| 弦 | 组的全名。这个属性是强制性的。 |
| 弦 | 组的数据类型的类名。例如,如果组基于带注释的类 |
| 弦 | 可以向用户显示的组的简短说明。如果没有可用的描述,则可以省略。建议用简短的段落说明,第一行提供简明的摘要。描述中的最后一行应该以句点结尾( |
| 弦 | 提供此组的源的类名。例如,如果组基于 |
| 弦 | 生成此组的方法的全名(包括括号和参数类型)(例如, |
对象中包含的JSON对象。properties
数组可以包含下表中描述的属性:
名字,姓名 | 类型 | 目的 |
---|---|---|
| 弦 | 财产的全名。名称采用小写分隔形式(例如, |
| 弦 | 属性的数据类型的完全签名(例如, |
| 弦 | 可以向用户显示的组的简短说明。如果没有可用的描述,则可以省略。建议用简短的段落说明,第一行提供简明的摘要。描述中的最后一行应该以句点结尾( |
| 弦 | 提供此属性的源的类名。例如,如果属性来自带注释的类 |
| 对象 | 默认值,如果未指定属性,则使用该默认值。如果属性的类型是数组,则可以是值数组。如果默认值未知,则可以省略它。 |
| 弃用 | 指定是否不推荐该属性。如果不建议使用该字段,或者如果不知道该信息,则可以省略该字段。下一个表提供了关于 |
对象中包含的JSON对象。deprecation
每个属性properties
元素可以包含以下属性:
名字,姓名 | 类型 | 目的 |
---|---|---|
| 弦 | 表示反对的级别,可以是 |
| 弦 | 对不推荐该财产的原因的简短描述。如果没有可用的理由,则可以省略。建议用简短的段落说明,第一行提供简明的摘要。描述中的最后一行应该以句点结尾( |
| 弦 | 的属性的全名。取代这个废弃的财产。如果没有替换该属性,则可以省略该属性。 |
![]() |
在Spring Boot 1.3之前,一个 |
还可以在代码中通过添加@DeprecatedConfigurationProperty
暴露不推荐属性的getter的注释。例如,假设app.acme.target
属性混淆,并将其重命名为app.acme.name
。下面的示例演示如何处理这种情况:
@ConfigurationProperties("app.acme") public class AcmeProperties { private String name; public String getName() { ... } public void setName(String name) { ... } @DeprecatedConfigurationProperty(replacement = "app.acme.name") @Deprecated public String getTarget() { return getName(); } @Deprecated public void setTarget(String target) { setName(target); } }
![]() |
没有办法设置 |
上面的代码确保不推荐的属性仍然工作(委托给name
(幕后财产)。曾经getTarget
和setTarget
方法可以从公共API中删除,元数据中的自动弃用提示也会消失。如果要保留提示,请将手动元数据添加到error
弃用级别确保用户仍被告知该属性。这样做在下列情况下特别有用:replacement
提供。
对象中包含的JSON对象。hints
数组可以包含下表所示的属性:
名字,姓名 | 类型 | 目的 |
---|---|---|
| 弦 | 此提示所引用的属性的全名。名称以小写分隔形式(如 |
| ValueHint[] | 属性定义的有效值列表。 |
| 价值提供者[] | 属性定义的提供程序列表。 |
对象中包含的JSON对象。values
每个属性hint
元素可以包含下表中描述的属性:
名字,姓名 | 类型 | 目的 |
---|---|---|
| 对象 | 提示所引用的元素的有效值。如果属性的类型是数组,那么它也可以是值数组。这个属性是强制性的。 |
| 弦 | 可以向用户显示的值的简短说明。如果没有可用的描述,则可以省略。建议用简短的段落说明,第一行提供简明的摘要。描述中的最后一行应该以句点结尾( |
对象中包含的JSON对象。providers
每个属性hint
元素可以包含下表中描述的属性:
名字,姓名 | 类型 | 目的 |
---|---|---|
| 弦 | 提供程序的名称,用于为提示所引用的元素提供额外的内容帮助。 |
| JSON对象 | 提供程序支持的任何其他参数(有关详细信息,请参阅提供程序的文档)。 |
具有相同“属性”和“组”名称的对象可以在元数据文件中多次出现。例如,可以将两个单独的类绑定到同一个前缀,每个类都具有潜在的重叠属性名。虽然元数据中多次出现的相同名称不应该常见,但元数据的使用者应该注意确保他们支持它。
为了改善用户体验并进一步帮助用户配置给定的属性,您可以提供以下附加元数据:
这,这个,那,那个name
属性引用name
一种财产。在.。前面显示的初始示例,我们为spring.jpa.hibernate.ddl-auto
财产:none
, validate
, update
, create
,和create-drop
。每个值也可能有一个描述。
如果您的属性是类型的Map
,您可以为键和值提供提示(但不能为映射本身提供提示)。特辑.keys
和.values
后缀必须分别引用键和值。
假设sample.contexts
映射魔术String
值转换为整数,如以下示例所示:
- @ConfigurationProperties("sample")
- public class SampleProperties {
-
- private Map<String,Integer> contexts;
- // getters and setters
- }
神奇的值(在本例中)是sample1
和sample2
。为了为密钥提供额外的内容帮助,您可以将以下JSON添加到模块的手动元数据:
- {"hints": [
- {
- "name": "sample.contexts.keys",
- "values": [
- {
- "value": "sample1"
- },
- {
- "value": "sample2"
- }
- ]
- }
- ]}
![]() |
我们建议您使用 |
提供程序是将语义附加到属性的一种强大方法。在本节中,我们定义了可以用于您自己的提示的官方提供程序。但是,您最喜欢的IDE可能会实现其中的一些,或者根本不实现。而且,它最终可以提供自己的服务。
![]() |
由于这是一个新特性,IDE供应商必须赶上它的工作方式。收养时间自然不同。 |
下表汇总了支持的提供者列表:
名字,姓名 | 描述 |
---|---|
| 允许提供任何附加价值。 |
| 自动完成项目中可用的类。类指定的基类通常约束 |
| 处理属性,就好像它是由强制命令定义的类型定义的一样。 |
| 自动完成有效的记录器名称。通常,当前项目中可用的包和类名可以自动完成. |
| 自动完成当前项目中可用的bean名称。类指定的基类通常约束 |
| 自动完成项目中可用的Spring配置文件名称。 |
![]() |
对于给定的属性,只能有一个提供程序处于活动状态,但如果它们都可以管理属性,则可以指定多个提供程序。在某种程度上。确保将最强大的提供程序放在首位,因为IDE必须使用它能够处理的JSON部分中的第一个提供程序。如果不支持给定属性的提供程序,也不提供特殊的内容辅助。 |
任何
特辑任何提供程序值允许提供任何附加值。如果支持这种方法,则应该应用基于属性类型的常规值验证。
如果您有一个值列表,并且任何额外的值仍然应该被认为是有效的,则通常使用此提供程序。
下面的示例提供on
和off
的自动完成值system.state
:
{"hints": [ { "name": "system.state", "values": [ { "value": "on" }, { "value": "off" } ], "providers": [ { "name": "any" } ] } ]}
注意,在前面的示例中,也允许任何其他值。
类引用
这,这个,那,那个类引用提供程序自动完成项目中可用的类。此提供程序支持以下参数:
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
|
| 无 | 应该分配给所选值的类的完全限定名。通常用于筛选出-非候选类。请注意,类型本身可以通过公开具有适当上限的类来提供此信息。 |
|
| 千真万确 | 指定是否只将具体类视为有效候选人。 |
以下元数据片段对应于标准server.servlet.jsp.class-name
属性定义JspServlet
要使用的类名:
- {"hints": [
- {
- "name": "server.servlet.jsp.class-name",
- "providers": [
- {
- "name": "class-reference",
- "parameters": {
- "target": "javax.servlet.http.HttpServlet"
- }
- }
- ]
- }
- ]}
手柄
这,这个,那,那个手柄提供程序允许您将属性的类型替换为更高级别的类型。这通常发生在属性具有java.lang.String
类型,因为您不希望配置类依赖于可能不在类路径上的类。此提供程序支持以下参数:
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
|
| 无 | 要为属性考虑的类型的完全限定名称。此参数是强制性的。 |
可以使用下列类型:
java.lang.Enum
*列出属性的可能值。(我们建议使用Enum
类型,因为IDE不需要进一步提示就可以自动完成这些值。)java.nio.charset.Charset
支持字符集/编码值的自动完成(例如UTF-8
)java.util.Locale
*区域设置的自动完成(例如en_US
)org.springframework.util.MimeType
支持自动完成内容类型值(如text/plain
)org.springframework.core.io.Resource
支持自动完成Spring的资源抽象,以引用文件系统或类路径上的文件。(如classpath:/sample.properties
)![]() |
如果可以提供多个值,请使用 |
以下元数据片段对应于标准spring.liquibase.change-log
属性,该属性定义要使用的Changelog的路径。实际上,它在内部用作org.springframework.core.io.Resource
但不能以这种方式公开,因为我们需要保留原始字符串值才能将其传递给Liquibase API。
- {"hints": [
- {
- "name": "spring.liquibase.change-log",
- "providers": [
- {
- "name": "handle-as",
- "parameters": {
- "target": "org.springframework.core.io.Resource"
- }
- }
- ]
- }
- ]}
记录器名称
这,这个,那,那个记录器名称提供程序自动完成有效的记录器名称。通常,当前项目中可用的包和类名可以自动完成.特定的框架可能有额外的神奇记录器名称,也可以支持。
由于记录器名称可以是任意名称,因此提供程序应该允许任何值,但可以突出显示项目类路径中不可用的有效包和类名。
以下元数据片段对应于标准logging.level
财产。钥匙是记录器名称值对应于标准日志级别或任何自定义级别。
{"hints": [ { "name": "logging.level.keys", "values": [ { "value": "root", "description": "Root logger used to assign the default logging level." } ], "providers": [ { "name": "logger-name" } ] }, { "name": "logging.level.values", "values": [ { "value": "trace" }, { "value": "debug" }, { "value": "info" }, { "value": "warn" }, { "value": "error" }, { "value": "fatal" }, { "value": "off" } ], "providers": [ { "name": "any" } ] } ]}
春豆参考
这,这个,那,那个Springbean-引用提供者自动完成在当前项目的配置中定义的bean。此提供程序支持以下参数:
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
|
| 无 | 应该分配给候选对象的bean类的完全限定名。通常用于过滤掉非候选bean。 |
以下元数据片段对应于标准spring.jmx.server
属性定义MBeanServer
供使用的豆子:
- {"hints": [
- {
- "name": "spring.jmx.server",
- "providers": [
- {
- "name": "spring-bean-reference",
- "parameters": {
- "target": "javax.management.MBeanServer"
- }
- }
- ]
- }
- ]}
![]() |
绑定程序不知道元数据。如果提供该提示,则仍然需要将bean名称转换为实际的Bean引用。 |
弹簧配置文件名称
这,这个,那,那个弹簧-配置文件名称提供者自动完成在当前项目的配置中定义的Spring配置文件。
以下元数据片段对应于标准spring.profiles.active
属性,该属性定义Spring配置文件的名称以启用:
- {"hints": [
- {
- "name": "spring.profiles.active",
- "providers": [
- {
- "name": "spring-profile-name"
- }
- ]
- }
- ]}
可以轻松地从带注释的项生成自己的配置元数据文件。@ConfigurationProperties
通过使用spring-boot-configuration-processor
贾尔。JAR包含一个Java注释处理器,在编译项目时调用它。若要使用处理器,请在spring-boot-configuration-processor
.
对于Maven,依赖项应该声明为可选的,如下面的示例所示:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-configuration-processor</artifactId>
- <optional>true</optional>
- </dependency>
对于Gradle 4.5和更早版本,应该在compileOnly
配置,如以下示例所示:
- dependencies {
- compileOnly "org.springframework.boot:spring-boot-configuration-processor"
- }
对于Gradle 4.6及更高版本,应该在annotationProcessor
配置,如以下示例所示:
- dependencies {
- annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
- }
如果您使用的是additional-spring-configuration-metadata.json
文件,compileJava
任务应配置为依赖于processResources
任务,如以下示例所示:
compileJava.dependsOn(processResources)
此依赖关系确保在编译期间运行注释处理器时可以获得额外的元数据。
处理器会同时提取被注释的类和方法。@ConfigurationProperties
。配置类中字段值的Javadoc用于填充description
属性。
![]() |
您应该只使用简单的文本 |
属性是通过标准getter和setter的存在来发现的,它们对集合类型具有特殊的处理(即使只有getter存在,也会检测到)。注释处理器还支持使用@Data
, @Getter
,和@Setter
Lombok注解。
![]() |
如果在项目中使用AspectJ,则需要确保注释处理器只运行一次。有几种方法可以做到这一点。使用Maven,您可以配置 |
注释处理器自动将内部类视为嵌套属性。考虑以下课程:
@ConfigurationProperties(prefix="server") public class ServerProperties { private String name; private Host host; // ... getter and setters public static class Host { private String ip; private int port; // ... getter and setters } }
的元数据信息。server.name
, server.host.ip
,和server.host.port
财产。您可以使用@NestedConfigurationProperty
字段上的注释,以指示应该将常规(非内部)类视为嵌套类。
![]() |
这对集合和映射没有影响,因为这些类型是自动标识的,并且为每个类型生成一个元数据属性。 |
Spring Boot的配置文件处理非常灵活,而且常常存在不绑定到@ConfigurationProperties
豆子您还可能需要调优现有键的一些属性。为了支持这种情况并允许您提供自定义的“提示”,注释处理器会自动合并来自META-INF/additional-spring-configuration-metadata.json
进入主元数据文件。
如果引用已自动检测到的属性,则如果指定了说明、默认值和弃用信息,则将重写这些信息。如果未在当前模块中标识手动属性声明,则将其添加为新属性。
的格式additional-spring-configuration-metadata.json
文件与常规文件完全相同。spring-configuration-metadata.json
。附加属性文件是可选的。如果您没有任何其他属性,请不要添加该文件。
以下是SpringBoot提供的所有自动配置类的列表,以及指向文档和源代码的链接。请记住,还要查看应用程序中的条件报告,以获得更多关于哪些功能被打开的详细信息。(为此,请用--debug
或-Ddebug
或者,在Actuator应用程序中,使用conditions
端点)
下面的自动配置类来自spring-boot-autoconfigure
模块:
配置类 | 链接 |
---|---|
下面的自动配置类来自spring-boot-actuator-autoconfigure
模块:
配置类 | 链接 |
---|---|
下表列出了各种@…Test
可用于测试应用程序的切片及其默认导入的自动配置的注释:
测试片 | 进口自动配置 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
这,这个,那,那个spring-boot-loader
模块允许SpringBoot支持可执行的JAR和WAR文件。如果使用Maven插件或Gradle插件,则会自动生成可执行的JAR,并且通常不需要知道它们如何工作的细节。
如果您需要从不同的构建系统创建可执行的JAR,或者您只是好奇底层技术,本节提供了一些背景知识。
Java没有提供任何加载嵌套JAR文件的标准方法(也就是说,JAR文件本身包含在JAR中)。如果您需要分发可以从命令行运行的自包含应用程序,而不需要解压缩,这可能会有问题。
为了解决这个问题,许多开发人员使用“阴影”JAR。一个阴影的JAR包所有的类,从所有的罐子,到一个单一的“uber JAR”。阴影罐的问题是很难看出应用程序中实际上有哪些库。如果在多个JAR中使用相同的文件名(但内容不同),也会出现问题。SpringBoot采用了一种不同的方法,可以让您直接嵌套罐子。
与SpringBootLoader兼容的JAR文件应该以下方式构造:
- example.jar
- |
- +-META-INF
- | +-MANIFEST.MF
- +-org
- | +-springframework
- | +-boot
- | +-loader
- | +-<spring boot loader classes>
- +-BOOT-INF
- +-classes
- | +-mycompany
- | +-project
- | +-YourClasses.class
- +-lib
- +-dependency1.jar
- +-dependency2.jar

应用程序类应该放在嵌套的BOOT-INF/classes
目录。依赖项应该放在嵌套的BOOT-INF/lib
目录。
与Spring Boot Loader兼容的WAR文件应该以下方式构造:
- example.war
- |
- +-META-INF
- | +-MANIFEST.MF
- +-org
- | +-springframework
- | +-boot
- | +-loader
- | +-<spring boot loader classes>
- +-WEB-INF
- +-classes
- | +-com
- | +-mycompany
- | +-project
- | +-YourClasses.class
- +-lib
- | +-dependency1.jar
- | +-dependency2.jar
- +-lib-provided
- +-servlet-api.jar
- +-dependency3.jar

依赖项应该放在嵌套的WEB-INF/lib
目录。任何在运行嵌入式时所需但在部署到传统web容器时不需要的依赖项都应该放在WEB-INF/lib-provided
.
用于支持加载嵌套JAR的核心类是org.springframework.boot.loader.jar.JarFile
。它允许您从标准JAR文件或嵌套的子JAR数据加载JAR内容。第一次加载时,每个JarEntry
映射到外部JAR的物理文件偏移量,如以下示例所示:
- myapp.jar
- +-------------------+-------------------------+
- | /BOOT-INF/classes | /BOOT-INF/lib/mylib.jar |
- |+-----------------+||+-----------+----------+|
- || A.class ||| B.class | C.class ||
- |+-----------------+||+-----------+----------+|
- +-------------------+-------------------------+
- ^ ^ ^
- 0063 3452 3980
前面的示例显示了如何A.class
可以在/BOOT-INF/classes
在……里面myapp.jar
就位0063
. B.class
实际上可以在myapp.jar
就位3452
,和C.class
已就位3980
.
有了这些信息,我们可以通过寻找外部JAR的适当部分来加载特定的嵌套条目。我们不需要解压缩存档,也不需要将所有输入数据读入内存。
SpringBootLoader努力保持与现有代码和库的兼容性。org.springframework.boot.loader.jar.JarFile
从java.util.jar.JarFile
应该作为替补。这,这个,那,那个getURL()
方法返回URL
打开与java.net.JarURLConnection
可以与Java一起使用URLClassLoader
.
这,这个,那,那个org.springframework.boot.loader.Launcher
类是一个特殊的引导类,用作可执行JAR的主入口点。这是实际的Main-Class
在JAR文件中,它用于设置适当的URLClassLoader
最后打电话给你main()
方法。
有三个启动子类(JarLauncher
, WarLauncher
,和PropertiesLauncher
)它们的目的是加载资源(.class
)目录中的嵌套JAR文件或WAR文件(相对于类路径上的显式文件)。如属JarLauncher
和WarLauncher
,嵌套路径是固定的。JarLauncher
向内看BOOT-INF/lib/
,和WarLauncher
向内看WEB-INF/lib/
和WEB-INF/lib-provided/
。如果你想要更多的话,你可以在这些地方添加额外的罐子。这,这个,那,那个PropertiesLauncher
向内看BOOT-INF/lib/
默认情况下,可以在应用程序存档中添加其他位置,但可以通过设置一个名为LOADER_PATH
或loader.path
在……里面loader.properties
(这是以逗号分隔的目录、档案或档案目录的列表)。
您需要指定适当的Launcher
就像Main-Class
属性META-INF/MANIFEST.MF
。要启动的实际类(即包含main
方法)应在Start-Class
属性。
下面的示例显示了一个典型的MANIFEST.MF
对于可执行的JAR文件:
- Main-Class: org.springframework.boot.loader.JarLauncher
- Start-Class: com.mycompany.project.MyApplication
对于战争档案,如下所示:
- Main-Class: org.springframework.boot.loader.WarLauncher
- Start-Class: com.mycompany.project.MyApplication
![]() |
您不需要指定 |
某些PaaS实现可能在运行之前选择解压缩存档。例如,CloudFoundry就是这样运作的。您可以通过启动适当的启动程序来运行未打包的存档,如下所示:
- $ unzip -q myapp.jar
- $ java org.springframework.boot.loader.JarLauncher
PropertiesLauncher
特征PropertiesLauncher
具有一些可以使用外部属性(系统属性、环境变量、清单项或loader.properties
)下表描述了这些属性:
钥匙 | 目的 |
---|---|
| 逗号分隔的classpath,如 |
| 用于解析 |
| Main方法的默认参数(空格分隔)。 |
| 要启动的主类的名称(例如, |
| 属性文件的名称(例如, |
| 属性文件的路径(例如, |
| 布尔标志,指示应将所有属性添加到默认的系统属性中。 |
当指定为环境变量或清单条目时,应使用下列名称:
钥匙 | 舱单条目 | 环境变量 |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
![]() |
生成插件自动移动 |
以下规则适用于使用PropertiesLauncher
:
loader.properties
被搜索到loader.home
,然后在类路径的根部,然后在classpath:/BOOT-INF/classes
。使用具有该名称的文件的第一个位置。loader.home
仅在下列情况下才为附加属性文件(覆盖默认值)的目录位置。loader.config.location
未指定。loader.path
可以包含目录(对JAR和zip文件进行递归扫描)、归档路径、存档文件中的一个目录,该目录被扫描为JAR文件(例如,dependencies.jar!/lib
),或者通配符模式(用于默认JVM行为)。存档路径可以相对于loader.home
或在文件系统中的任何位置使用jar:file:
前缀。loader.path
(如果为空)默认为BOOT-INF/lib
(如果从存档中运行,则意味着本地目录或嵌套目录)。因为这个,PropertiesLauncher
行为与JarLauncher
当不提供其他配置时。loader.path
不能用于配置loader.properties
(用于搜索后者的类路径是jvm类路径,当PropertiesLauncher
已发射)。loader.properties
,爆炸档案清单和档案清单。在使用SpringBootLoader打包应用程序时,需要考虑以下限制:
ZipEntry
对于嵌套的JAR,必须使用ZipEntry.STORED
方法。这是必需的,这样我们就可以直接查找嵌套JAR中的单个内容。嵌套JAR文件本身的内容仍然可以压缩,外部JAR中的任何其他条目也可以压缩。Thread.getContextClassLoader()
加载类时(默认情况下,大多数库和框架都这样做)。试图用以下方法加载嵌套的JAR类ClassLoader.getSystemClassLoader()
失败了。java.util.Logging
总是使用系统类加载器。因此,您应该考虑使用不同的日志记录实现。如果前面的限制意味着您不能使用SpringBootLoader,请考虑以下选项:
下表提供了Spring Boot在其CLI(命令行接口)、Maven依赖关系管理和Gradle插件中提供的所有依赖版本的详细信息。当您声明依赖于这些工件之一而不声明版本时,将使用表中列出的版本。
组ID | 工件ID | 版本 |
---|---|---|
|
| 2.7.7 |
|
| 1.2.3 |
|
| 1.2.3 |
|
| 1.2.3 |
|
| 4.0.6 |
|
| 4.0.6 |
|
| 4.0.6 |
|
| 2.1.0 |
|
| 2.6.2 |
|
| 3.6.0 |
|
| 3.6.0 |
|
| 1.4.0 |
|
| 2.9.0 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.9.7 |
|
| 2.6.2 |
|
| 2.6.2 |
|
| 2.6.2 |
|
| 2.6.2 |
|
| 2.0.1 |
|
| 1.9.64 |
|
| 2.8.5 |
|
| 1.4.197 |
|
| 3.10.5 |
|
| 3.10.5 |
|
| 1.2.3 |
|
| 3.10.5 |
|
| 2.4.0 |
|
| 2.4.0 |
|
| 6.4.0.jre8 |
|
| 4.2.1 |
|
| 4.2.1 |
|
| 4.2.1 |
|
| 4.2.1 |
|
| 4.2.1 |
|
| 5.4.1 |
|
| 1.14 |
|
| 4.2.1 |
|
| 1.6.2 |
|
| 1.4.0 |
|
| 3.1.0 |
|
| 4.0.8 |
|
| 3.2.0 |
|
| 1.11 |
|
| 1.6 |
|
| 2.1.1 |
|
| 1.6.1 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 3.2.6 |
|
| 5.1.0.RELEASE |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 1.1.0-m.1 |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 2.0.15.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 4.1.29.Final |
|
| 3.2.0.RELEASE |
|
| 3.2.0.RELEASE |
|
| 3.2.0.RELEASE |
|
| 3.2.0.RELEASE |
|
| 3.2.0.RELEASE |
|
| 1.0.1.RELEASE |
|
| 0.8.0.RELEASE |
|
| 1.3.8 |
|
| 1.2.1 |
|
| 2.2.2 |
|
| 3.1.1 |
|
| 3.1.1 |
|
| 3.1.1 |
|
| 3.1.1 |
|
| 3.1.1 |
|
| 3.1.1 |
|
| 6.3.1 |
|
| 2.0.13.Final |
|
| 2.0.13.Final |
|
| 2.0.13.Final |
|
| 1.2.0 |
|
| 1.3.2 |
|
| 1.1.0 |
|
| 2.0.1 |
|
| 1.1.2 |
|
| 1.0 |
|
| 1.6.2 |
|
| 1.0.3 |
|
| 2.2 |
|
| 4.0.1 |
|
| 1.2 |
|
| 1.3 |
|
| 2.0.1.Final |
|
| 1.1 |
|
| 2.3.0 |
|
| 2.3.0 |
|
| 1.1.6 |
|
| 2.10 |
|
| 4.12 |
|
| 8.0.12 |
|
| 1.8.22 |
|
| 1.8.22 |
|
| 4.5.2 |
|
| 4.5.2 |
|
| 2.10.5 |
|
| 2.33 |
|
| 1.3.1 |
|
| 1.9.22 |
|
| 2.3.0 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 5.15.6 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.6.3 |
|
| 2.5.0 |
|
| 3.8 |
|
| 2.6.0 |
|
| 10.14.2.0 |
|
| 4.5.6 |
|
| 4.1.4 |
|
| 4.5.6 |
|
| 4.5.6 |
|
| 4.5.6 |
|
| 4.5.6 |
|
| 4.4.10 |
|
| 4.4.10 |
|
| 4.5.6 |
|
| 1.1.10 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.0.0 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 2.11.1 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 7.4.0 |
|
| 9.0.12 |
|
| 9.0.12 |
|
| 9.0.12 |
|
| 9.0.12 |
|
| 9.0.12 |
|
| 9.0.12 |
|
| 9.0.12 |
|
| 9.0.12 |
|
| 1.9.1 |
|
| 1.9.1 |
|
| 1.9.1 |
|
| 3.11.1 |
|
| 2.1.4 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 2.5.2 |
|
| 3.0.10 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 1.0.1 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 2.2.0.v201112011158 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 9.4.12.v20180830 |
|
| 3.6.0 |
|
| 3.6.0 |
|
| 3.6.0 |
|
| 6.4.1 |
|
| 6.4.1 |
|
| 6.4.1 |
|
| 6.4.1 |
|
| 6.4.1 |
|
| 6.4.1 |
|
| 3.0.5 |
|
| 3.0.5 |
|
| 5.1.4 |
|
| 2.3.28 |
|
| 3.0.0 |
|
| 2.3.0.1 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 2.27 |
|
| 1.3 |
|
| 1.3 |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 5.3.6.Final |
|
| 6.0.13.Final |
|
| 6.0.13.Final |
|
| 2.4.1 |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 9.3.3.Final |
|
| 2.13 |
|
| 7.6.0.Final |
|
| 3.3.2.Final |
|
| 2.0.6 |
|
| 1.2.70 |
|
| 1.2.70 |
|
| 1.2.70 |
|
| 1.2.70 |
|
| 1.2.70 |
|
| 1.2.70 |
|
| 1.2.70 |
|
| 1.6.0 |
|
| 3.11.5 |
|
| 3.11.5 |
|
| 3.11.5 |
|
| 5.3.1 |
|
| 5.3.1 |
|
| 5.3.1 |
|
| 5.3.1 |
|
| 1.3.1 |
|
| 1.3.1 |
|
| 1.3.1 |
|
| 1.3.1 |
|
| 1.3.1 |
|
| 1.3.1 |
|
| 1.3.1 |
|
| 5.3.1 |
|
| 3.6.2 |
|
| 2.3.0 |
|
| 1.0.3 |
|
| 2.22.0 |
|
| 2.22.0 |
|
| 2.22.0 |
|
| 3.8.2 |
|
| 3.8.2 |
|
| 3.8.2 |
|
| 3.8.2 |
|
| 1.9.2 |
|
| 3.8.2 |
|
| 8.5.33 |
|
| 3.1.3 |
|
| 3.1.3 |
|
| 3.1.3 |
|
| 3.1.3 |
|
| 3.1.3 |
|
| 42.2.5 |
|
| 1.18.2 |
|
| 2.3.0 |
|
| 2.3.0 |
|
| 1.0.2 |
|
| 2.32.1 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 3.14.0 |
|
| 1.5.0 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 1.7.25 |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 2.1.0.RC1 |
|
| 2.1.0.RC1 |
|
| 2.1.0.RC1 |
|
| 2.1.0.RC1 |
|
| 4.1.0.RC1 |
|
| 4.1.0.RC1 |
|
| 4.1.0.RC1 |
|
| 4.1.0.RC1 |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.1.0.BUILD-SNAPSHOT |
|
| 2.0.3.RELEASE |
|
| 2.0.3.RELEASE |
|
| 2.0.3.RELEASE |
|
| 2.0.3.RELEASE |
|
| 2.0.3.RELEASE |
|
| 2.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 3.1.0.RELEASE |
|
| 3.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 1.0.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 2.1.0.RELEASE |
|
| 3.1.0.RELEASE |
|
| 3.1.0.RELEASE |
|
| 3.1.0.RELEASE |
|
| 4.0.0.RELEASE |
|
| 0.25.0.RELEASE |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 5.1.0.RC1 |
|
| 2.2.0.RC1 |
|
| 2.2.0.RC1 |
|
| 2.3.2.RELEASE |
|
| 2.3.2.RELEASE |
|
| 2.3.2.RELEASE |
|
| 2.3.2.RELEASE |
|
| 2.3.2.RELEASE |
|
| 2.3.2.RELEASE |
|
| 1.2.0.RELEASE |
|
| 1.2.0.RELEASE |
|
| 2.0.2.RELEASE |
|
| 2.0.2.RELEASE |
|
| 2.0.2.RELEASE |
|
| 2.0.2.RELEASE |
|
| 2.0.2.RELEASE |
|
| 1.2.2.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 5.1.0.RELEASE |
|
| 2.1.0.RC1 |
|
| 2.1.0.M1 |
|
| 2.1.0.M1 |
|
| 2.0.3.RELEASE |
|
| 2.1.0.RC1 |
|
| 2.1.0.RC1 |
|
| 2.1.0.RC1 |
|
| 3.0.4.RELEASE |
|
| 3.0.4.RELEASE |
|
| 3.0.4.RELEASE |
|
| 3.0.4.RELEASE |
|
| 3.0.4.RELEASE |
|
| 1.1.0 |
|
| 3.0.9.RELEASE |
|
| 3.0.9.RELEASE |
|
| 3.0.1.RELEASE |
|
| 3.0.2.RELEASE |
|
| 3325375 |
|
| 0.35 |
|
| 3.23.1 |
|
| 2.6.2 |
|
| 2.6.2 |
|
| 2.6.2 |
|
| 1.23 |
|
| 2.9.0 |
|
| 1.6.3 |
|
| 1.4.01 |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。