地址:https://docs.spring.io/spring-boot/docs/current/reference/html/css
2.0.0.M3html
版權全部©2012-2017前端
目錄node
本節簡要概述了Spring Boot參考文檔。將其視爲文檔其他部分的映射。您能夠以線性方式閱讀本參考指南,或者若是您不感興趣,能夠跳過章節。mysql
Spring Boot參考指南以html, pdf 和epub文檔的形式提供。最新的副本可在docs.spring.io/spring-boot/docs/current/reference上找到。react
本文件的副本可供您本身使用和分發給他人,前提是您不對此類副本收取任何費用,而且每份副本均包含本版權聲明,不管是以印刷版仍是電子版分發。jquery
遇到Spring Boot問題,咱們想幫忙!nginx
spring-boot
。 全部Spring Boot都是開源的,包括文檔!若是您發現文檔有問題; 或者若是你只是想改進它們,請參與其中。git |
準備好開始使用Spring Boot了嗎?咱們已經爲您提供保障。
須要有關Spring Boot核心功能的更多細節? 這是給你的!
當您準備好將Spring Boot應用程序推向生產時,咱們有 一些您可能喜歡的技巧!
若是您剛開始使用Spring Boot,或者通常來講是「Spring」,那麼這就是您的選擇!在這裏,咱們回答基本的「什麼?」,「如何?」和「爲何?」的問題。您將找到Spring Boot的簡要介紹以及安裝說明。而後咱們將構建咱們的第一個Spring Boot應用程序,討論一些核心原則。
Spring Boot能夠輕鬆建立獨立的,生產級的基於Spring的應用程序,您能夠「運行」。咱們對Spring平臺和第三方庫採起了自覺得是的觀點,所以您能夠儘可能少開始。大多數Spring Boot應用程序只須要不多的Spring配置。
您能夠使用Spring Boot建立能夠使用java -jar
或更多傳統戰爭部署啓動的Java應用程序。咱們還提供了一個運行「spring腳本」的命令行工具。
咱們的主要目標是:
Spring Boot 2.0.0.M3須要Java 8和Spring Framework 5.0.0.RC3或更高版本。爲Maven(3.2+)和Gradle 3(3.4或更高版本)提供顯式構建支持。
Spring Boot能夠與「經典」Java開發工具一塊兒使用,也能夠做爲命令行工具安裝。不管如何,您將須要Java SDK v1.8或更高版本。您應該在開始以前檢查當前的Java安裝:
$ java -version
If you are new to Java development, or if you just want to experiment with Spring Boot you might want to try the Spring Boot CLI first, otherwise, read on for 「classic」 installation instructions.
You can use Spring Boot in the same way as any standard Java library. Simply include the appropriate spring-boot-*.jar
files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor; and there is nothing special about a Spring Boot application, so you can run and debug as you would any other Java program.
Although you could just copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).
Spring Boot is compatible with Apache Maven 3.2 or above. If you don’t already have Maven installed you can follow the instructions at maven.apache.org.
On many operating systems Maven can be installed via a package manager. If you’re an OSX Homebrew user try |
Spring Boot dependencies use the org.springframework.boot
groupId
. Typically your Maven POM file will inherit from the spring-boot-starter-parent
project and declare dependencies to one or more 「Starters」. Spring Boot also provides an optional Maven plugin to create executable jars.
Here is a typical pom.xml
file:
<?xml version =「1.0」encoding =「UTF-8」?>
<project xmlns = 「http://maven.apache.org/POM/4.0.0」 xmlns:xsi = 「http://www.w3 .org / 2001 / XMLSchema-instance「 xsi:schemaLocation = 」http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd「 > <modelVersion> 4.0.0 </ modelVersion> <groupId> com.example </ groupId> <artifactId> myproject </ artifactId> <version> 0.0.1-SNAPSHOT </ version> <! - 繼承默認值爲Spring Boot - > <parent> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.0.0.M3 < / version> </ parent> <! - 添加Web應用程序的典型依賴項 - > <dependencies> <dependency> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-web </ artifactId> </ dependency> </依賴> <! - 打包爲可執行jar - > <build> <plugins> <plugin> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin > </ plugins> </ build> <! - 添加Spring存儲庫 - > <! - (若是使用的是.RELEASE版本,則不須要這樣) - > <存儲庫> <存儲庫> <id> spring-snapshots </ id> < url> http://repo.spring.io/snapshot </ url> <snapshots> <enabled> true </ enabled> </ snapshots> </ repository> <repository> <id> spring-milestones </ id> < url> http://repo.spring.io/milestone </ url> </ repository> </ repositories> <pluginRepositories> <pluginRepository> <id> spring-snapshots </ id> <url>http://repo.spring.io/snapshot </ url> </ pluginRepository> <pluginRepository> <id> spring-milestones </ id> <url> http://repo.spring.io/milestone </ url> </ pluginRepository> </ pluginRepositories> </ project>
這 |
Spring Boot與Gradle 3(3.4或更高版本)兼容。若是您還沒有安裝Gradle,則能夠按照www.gradle.org/上的說明進行操做。
Spring Boot依賴項能夠使用org.springframework.boot
group
。一般,您的項目將聲明依賴於一個或多個 「Starters」。Spring Boot提供了一個有用的Gradle插件 ,可用於簡化依賴聲明和建立可執行jar。
這是一個典型的build.gradle
文件:
buildscript { 存儲庫{ jcenter() maven {url'http ://repo.spring.io/snapshot' } maven {url'http ://repo.spring.io/milestone' } } 依賴{ classpath'org.springframework.boot :spring-boot-gradle-plugin:2.0.0.M3' } } apply plugin:' java'apply plugin:'org.springframework.boot'apply plugin:'io.spring.dependency-management' jar { baseName = 'myproject'version = '0.0.1-SNAPSHOT' } 存儲庫{ jcenter() maven {url 「http://repo.spring.io/snapshot」 } maven {url 「http://repo.spring.io/milestone」 } } 依賴{ 編譯(「org.springframework.boot:spring-boot-starter-web」) testCompile(「org.springframework.boot:spring-boot-starter-test」) }
Spring Boot CLI是一個命令行工具,若是您想快速使用Spring進行原型設計,能夠使用它。它容許您運行Groovy腳本,這意味着您有一個熟悉的相似Java的語法,沒有太多的樣板代碼。
您不須要使用CLI來使用Spring Boot,但它絕對是實現Spring應用程序的最快方法。
您能夠從Spring軟件庫下載Spring CLI發行版:
還提供最早進的快照分發。
下載完成後,請按照 解壓縮的存檔中的INSTALL.txt說明進行操做。總結:文件中的目錄中有一個spring
腳本(spring.bat
對於Windows),或者您也能夠使用該文件(腳本能夠幫助您確保正確設置類路徑)。bin/
.zip
java -jar
.jar
SDKMAN!(軟件開發工具包管理器)可用於管理各類二進制SDK的多個版本,包括Groovy和Spring Boot CLI。獲取SDKMAN!來自sdkman.io並安裝Spring Boot
$ sdk install springboot $ spring --version Spring Boot v2.0.0.M3
若是您正在爲CLI開發功能並但願輕鬆訪問剛構建的版本,請遵循這些額外說明。
$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.0.0.M3-bin/spring-2.0.0.M3/ $ sdk默認springboot dev $ spring --version Spring CLI v2.0.0.M3
這將安裝一個spring
名爲dev
實例的本地實例。它指向您的目標構建位置,所以每次重建Spring Boot時,spring
都將是最新的。
你能夠經過這樣作看到它:
$ sdk ls springboot ================================================== ============================== 可用的Springboot版本 ================================================== ============================== > + dev * 2.0.0.M3 ================================================== ============================== + - 本地版本 * - 已安裝 > - 目前正在使用中 ================================================== ==============================
若是您使用的是Mac並使用Homebrew,那麼安裝Spring Boot CLI所須要作的就是:
$ brew tap pivotal / tap $ brew install springboot
Homebrew將安裝spring
到/usr/local/bin
。
若是您沒有看到公式,那麼您的brew安裝可能已過期。只需執行 |
若是您使用的是Mac並使用MacPorts,那麼安裝Spring Boot CLI所須要作的就是:
$ sudo port install spring-boot-cli
Spring Boot CLI附帶了爲BASH和 zsh shell 提供命令完成的腳本 。您能夠在任何shell中建立source
腳本(也稱爲 spring
),或者將其放在我的或系統範圍的bash完成初始化中。在Debian系統上,系統範圍的腳本都在,/shell-completion/bash
而且當新shell啓動時,該目錄中的全部腳本都會被執行。要手動運行腳本,例如,若是已使用SDKMAN安裝!
$。〜/ .sdkman /候選人/ springboot /電流/殼完成/慶典/彈簧 $ spring <HIT TAB HERE> 抓住幫助jar運行測試版
若是使用Homebrew或MacPorts安裝Spring Boot CLI,命令行完成腳本將自動註冊到shell。 |
這是一個很是簡單的Web應用程序,可用於測試您的安裝。建立一個名爲的文件app.groovy
:
@RestController 類 ThisWillActuallyRun { @RequestMapping( 「/」) String home(){ 「你好,世界!」 } }
而後只需從shell運行它:
$ spring run app.groovy
首次運行應用程序時須要一些時間,由於下載了依賴項。後續運行會更快。 |
在您喜歡的Web瀏覽器中打開localhost:8080,您應該看到如下輸出:
你好,世界!
讓咱們用Java開發一個簡單的「Hello World!」Web應用程序,它突出了一些Spring Boot的主要功能。咱們將使用Maven來構建這個項目,由於大多數IDE都支持它。
該spring.io網站包含使用Spring的引導許多「入門」指南。若是你想解決一個特定的問題; 先檢查那裏。 您能夠經過轉到start.spring.io並 |
在開始以前,打開終端以檢查您是否安裝了有效的Java和Maven版本。
$ java -version java版「1.8.0_102」 Java(TM)SE運行時環境(版本1.8.0_102-b14) Java HotSpot(TM)64位服務器VM(版本25.102-b14,混合模式)
$ mvn -v Apache Maven 3.3.9(bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47 + 00:00) Maven home:/usr/local/Cellar/maven/3.3.9/libexec Java版本:1.8.0_102,供應商:Oracle Corporation
此示例須要在其本身的文件夾中建立。後續說明假定您已建立合適的文件夾,而且它是您的「當前目錄」。 |
咱們須要從建立Maven pom.xml
文件開始。這pom.xml
是用於構建項目的配方。打開您喜歡的文本編輯器並添加如下內容:
<?xml version =「1.0」encoding =「UTF-8」?>
<project xmlns = 「http://maven.apache.org/POM/4.0.0」 xmlns:xsi = 「http://www.w3 .org / 2001 / XMLSchema-instance「 xsi:schemaLocation = 」http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd「 > <modelVersion> 4.0.0 </ modelVersion> <groupId> com.example </ groupId> <artifactId> myproject </ artifactId> <version> 0.0.1-SNAPSHOT </ version> <parent> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.0.0.M3 </ version> </ parent> <! - 這裏要添加的其餘行...... - > <! - (若是您使用的是.RELEASE版本,則不須要此項) - > <repositories> <repository> <id> spring-snapshots </ id> <url> http://repo.spring。 io / snapshot </ url> <snapshots> <enabled> true </ enabled> </ snapshots> </ repository> <repository> <id> spring-milestones </ id> <url> http://repo.spring。 io / milestone </ url> </ repository> </ repositories> <pluginRepositories> <pluginRepository> <id> spring-snapshots </ id> <url> http://repo.spring.io/snapshot </ url> </ pluginRepository> <pluginRepository> <id> spring-milestones </ id> <url> http://repo.spring.io/milestone </ url> </ pluginRepository> </ pluginRepositories> </ project>
這應該給你一個工做的構建,你能夠經過運行測試它mvn package
(你能夠忽略「jar將是空的 - 沒有內容被標記爲包含!」警告如今)。
此時,您能夠將項目導入IDE(大多數現代Java IDE包含對Maven的內置支持)。爲簡單起見,咱們將繼續爲此示例使用純文本編輯器。 |
Spring Boot提供了許多「Starters」,能夠輕鬆地將jar添加到類路徑中。咱們的示例應用程序已經spring-boot-starter-parent
在parent
POM部分中使用過 。這spring-boot-starter-parent
是一個特殊的啓動器,提供有用的Maven默認值。它還提供了一個 dependency-management
部分,以便您能夠省略version
「祝福」依賴項的標記。
其餘「Starters」只提供在開發特定類型的應用程序時可能須要的依賴項。因爲咱們正在開發一個Web應用程序,咱們將添加一個spring-boot-starter-web
依賴項 - 但在此以前,讓咱們看看咱們目前擁有的內容。
$ mvn依賴:樹 [INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
該mvn dependency:tree
命令打印項目依賴項的樹表示。您能夠看到它spring-boot-starter-parent
自己不提供依賴關係。讓咱們編輯咱們pom.xml
並spring-boot-starter-web
在該parent
部分下面添加依賴項:
<dependencies>
<dependency> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-web </ artifactId> </ dependency> </ dependencies>
若是mvn dependency:tree
再次運行,您將看到如今有許多其餘依賴項,包括Tomcat Web服務器和Spring Boot自己。
要完成咱們的應用程序,咱們須要建立一個Java文件。Maven將src/main/java
默認編譯源代碼,所以您須要建立該文件夾結構,而後添加一個名爲的文件src/main/java/Example.java
:
import org.springframework.boot。*; import org.springframework.boot.autoconfigure。*; import org.springframework.stereotype。*; import org.springframework.web.bind.annotation。*; @RestController @EnableAutoConfiguration 公共 類示例{ @RequestMapping( 「/」) String home(){ 返回 「Hello World!」 ; } public static void main(String [] args)throws Exception { SpringApplication.run(例如.class,args); } }
雖然這裏的代碼很少,但仍是有不少代碼。讓咱們逐步完成重要部分。
咱們Example
班上的第一個註釋是@RestController
。這被稱爲 構造型註釋。它爲閱讀代碼的人提供了提示,對於Spring,該類扮演着特定的角色。在這種狀況下,咱們的類是一個Web,@Controller
因此Spring在處理傳入的Web請求時會考慮它。
該@RequestMapping
註釋提供「路由」的信息。它告訴Spring,任何帶有路徑「/」的HTTP請求都應該映射到該home
方法。該 @RestController
註解告訴Spring使獲得的字符串直接返回給調用者。
在 |
The second class-level annotation is @EnableAutoConfiguration
. This annotation tells Spring Boot to 「guess」 how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web
added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.
The final part of our application is the main
method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication
class by calling run
. SpringApplication
will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server. We need to pass Example.class
as an argument to the run
method to tell SpringApplication
which is the primary Spring component. The args
array is also passed through to expose any command-line arguments.
At this point our application should work. Since we have used the spring-boot-starter-parent
POM we have a useful run
goal that we can use to start the application. Type mvn spring-boot:run
from the root project directory to start the application:
$ mvn spring-boot:run 。____ _ __ _ _ / \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ (()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \ \\ / ___)| | _)| | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / / ========= | _ | ============== | ___ / = / _ / _ / _ / :: Spring Boot ::(v2.0.0.M3) ....... 。。 ....... 。。(此處輸出日誌) ....... 。。 ........ 2.222秒啓動示例(JVM運行6.514)
若是您打開到localhost:8080的Web瀏覽器,您應該看到如下輸出:
你好,世界!
要優雅地退出應用程序命中ctrl-c
。
讓咱們經過建立一個徹底自包含的可執行jar文件來完成咱們的示例,咱們能夠在生產中運行它。可執行jar(有時稱爲「fat jar」)是包含已編譯類以及代碼須要運行的全部jar依賴項的歸檔。
要建立一個可執行jar,咱們須要添加spring-boot-maven-plugin
到咱們的 pom.xml
。在該dependencies
部分正下方插入如下行:
<build>
<plugins> <plugin> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build>
所述 |
保存pom.xml
並從命令行運行mvn package
:
$ mvn包 [INFO]掃描項目...... [信息] [INFO] ----------------------------------------------- ------------------------- [INFO]構建myproject 0.0.1-SNAPSHOT [INFO] ----------------------------------------------- ------------------------- [INFO] .... [INFO] --- maven-jar-plugin:2.4:jar(default-jar)@ myproject --- [INFO]構建jar:/Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar [信息] [INFO] --- spring-boot-maven-plugin:2.0.0.M3:從新打包(默認)@ myproject --- [INFO] ----------------------------------------------- ------------------------- [信息]創建成功 [INFO] ----------------------------------------------- -------------------------
若是你查看target
目錄,你應該看到myproject-0.0.1-SNAPSHOT.jar
。該文件大小應爲10 MB左右。若是你想偷看內部,你能夠使用jar tvf
:
$ jar tvf target / myproject-0.0.1-SNAPSHOT.jar
您還應該看到目錄中命名myproject-0.0.1-SNAPSHOT.jar.original
的文件小得多target
。這是Maven在Spring Boot從新打包以前建立的原始jar文件。
要運行該應用程序,請使用如下java -jar
命令:
$ java -jar target / myproject-0.0.1-SNAPSHOT.jar 。____ _ __ _ _ / \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ (()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \ \\ / ___)| | _)| | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / / ========= | _ | ============== | ___ / = / _ / _ / _ / :: Spring Boot ::(v2.0.0.M3) ....... 。。 ....... 。。(此處輸出日誌) ....... 。。 ........ 2.536秒啓動示例(JVM運行2.864)
和之前同樣,優雅地退出應用程序命中ctrl-c
。
但願本節爲您提供了一些Spring Boot基礎知識,並幫助您編寫本身的應用程序。若是您是面向任務的開發人員類型,您可能須要跳轉到spring.io並查看一些 入門指南,這些指南解決了具體的「如何使用Spring執行此操做」問題; 咱們還有Spring Boot特定 的操做方法參考文檔。
在春季啓動庫也有 一堆樣品能夠運行。樣本獨立於其他代碼(即您無需構建其他代碼來運行或使用示例)。
不然,下一個邏輯步驟是閱讀第III部分「使用Spring Boot」。若是你真的不耐煩,你也能夠跳過去閱讀 Spring Boot功能。
本節詳細介紹瞭如何使用Spring Boot。它涵蓋了諸如構建系統,自動配置以及如何運行應用程序等主題。咱們還介紹了一些Spring Boot最佳實踐。雖然Spring Boot沒有什麼特別之處(它只是你能夠使用的另外一個庫),但有一些建議,若是遵循這些建議,將使您的開發過程更容易一些。
若是您剛剛開始使用Spring Boot,那麼在深刻了解本節以前,您應該閱讀「 入門指南」。
強烈建議您選擇支持依賴關係管理的構建系統 ,而且能夠使用發佈到「Maven Central」存儲庫的工件。咱們建議您選擇Maven或Gradle。可讓Spring Boot與其餘構建系統(例如Ant)一塊兒工做,但它們不會獲得特別好的支持。
每一個版本的Spring Boot都提供了它支持的依賴項的精選列表。實際上,您不須要爲構建配置中的任何這些依賴項提供版本,由於Spring Boot正在爲您管理這些依賴項。當您升級Spring Boot時,這些依賴項也將以一致的方式升級。
You can still specify a version and override Spring Boot’s recommendations if you feel that’s necessary. |
The curated list contains all the spring modules that you can use with Spring Boot as well as a refined list of third party libraries. The list is available as a standard Bills of Materials (spring-boot-dependencies
) that can be used with both Maven and Gradle.
Each release of Spring Boot is associated with a base version of the Spring Framework so we highly recommend you to not specify its version on your own. |
Maven users can inherit from the spring-boot-starter-parent
project to obtain sensible defaults. The parent project provides the following features:
<version>
tags for common dependencies, inherited from the spring-boot-dependencies
POM.application.properties
and application.yml
including profile-specific files (e.g. application-foo.properties
and application-foo.yml
)On the last point: since the default config files accept Spring style placeholders (${…}
) the Maven filtering is changed to use @..@
placeholders (you can override that with a Maven property resource.delimiter
).
To configure your project to inherit from the spring-boot-starter-parent
simply set the parent
:
<!-- Inherit defaults from Spring Boot -->
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.M3</version> </parent>
You should only need to specify the Spring Boot version number on this dependency. If you import additional starters, you can safely omit the version number. |
With that setup, you can also override individual dependencies by overriding a property in your own project. For instance, to upgrade to another Spring Data release train you’d add the following to your pom.xml
.
<properties>
<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version> </properties>
Check the |
Not everyone likes inheriting from the spring-boot-starter-parent
POM. You may have your own corporate standard parent that you need to use, or you may just prefer to explicitly declare all your Maven configuration.
If you don’t want to use the spring-boot-starter-parent
, you can still keep the benefit of the dependency management (but not the plugin management) by using a scope=import
dependency:
<dependencyManagement>
<dependencies> <dependency> <!-- Import dependency management from Spring Boot --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.0.0.M3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
That setup does not allow you to override individual dependencies using a property as explained above. To achieve the same result, you’d need to add an entry in thedependencyManagement
of your project before the spring-boot-dependencies
entry. For instance, to upgrade to another Spring Data release train you’d add the following to your pom.xml
.
<dependencyManagement>
<dependencies> <! - 覆蓋Spring Boot提供的Spring Data版本系列 - > <dependency> <groupId> org.springframework.data </ groupId> <artifactId> spring-data-releasetrain </ artifactId> < version> Fowler-SR2 </ version> <scope> import </ scope> <type> pom </ type> </ dependency> <dependency> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot -dependencies </ artifactId> <version>2.0.0.M3 </ version> <type> pom</ type> <scope> import </ scope> </ dependency> </ dependencies> </ dependencyManagement>
在上面的示例中,咱們指定了BOM,可是能夠經過這種方式覆蓋任何依賴關係類型。 |
Spring Boot包含一個Maven插件 ,能夠將項目打包爲可執行jar。<plugins>
若是要使用它,請將插件添加到您的部分:
<build>
<plugins> <plugin> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build>
若是使用Spring Boot啓動程序父pom,則只需添加插件,除非要更改父項中定義的設置,不然無需對其進行配置。 |
能夠使用Apache Ant + Ivy構建Spring Boot項目。該 spring-boot-antlib
「的antlib」模塊還能夠幫助螞蟻建立可執行的JAR文件。
要聲明依賴項,典型ivy.xml
文件將以下所示:
<ivy-module version = 「2.0」 > <info organization = 「org.springframework.boot」 module = 「spring-boot-sample-ant」 /> <configurations> <conf name = 「compile」 description = 「所需的一切編譯此模塊「 /> <conf name = 」runtime「 extends = 」compile「 description = 」運行此模塊所需的一切「 /> </ configurations> <dependencies> <依賴 org =「org.springframework.boot」 name = 「spring-boot-starter」 rev = 「$ {spring-boot.version}」 conf = 「compile」 /> </ dependencies> </ ivy-module>
典型的build.xml
看起來像這樣:
<project
xmlns:ivy = 「antlib:org.apache.ivy.ant」 xmlns:spring-boot = 「antlib:org.springframework.boot.ant」 name = 「myapp」 default = 「build」 > <property name = 「spring-boot.version」 value = 「1.3.0.BUILD-SNAPSHOT」 /> <target name = 「resolve」 description = 「 - >使用常春藤檢索依賴關係」 > <ivy:retrieve pattern = 「lib / [conf] / [artifact] - [type] - [revision]。[ext]」 /> </目標> <target name = 「classpaths」 depends = 「resolve」 > <path id = 「compile.classpath」 > <fileset dir = 「lib / compile」 includes = 「* .jar」 /> </ path> </ target> <target name = 「init」 depends = 「classpaths」 > <mkdir dir = 「build / classes」 /> </ target> <target name = 「compile」 depends = 「init」 description = 「compile」 > <javac srcdir = 「src / main / java」 destdir = 「build / classes」 classpathref = 「compile.classpath」 /> </ target> <target name = 「build」 depends = 「compile」 > <spring-boot:exejar destfile = 「build / myapp.jar」 classes = 「build / classes」 > <spring-boot:lib> <fileset dir = 「lib / runtime「 /> </ spring-boot:lib> </ spring-boot:exejar> </ target> </ project>
若是您不想使用該模塊,請參見第85.9節「從Ant構建可執行存檔而不使用spring-boot-antlib」 「操做方法」 |
啓動器是一組方便的依賴關係描述符,您能夠在應用程序中包含這些描述符。您能夠得到所需的全部Spring和相關技術的一站式服務,而無需搜索示例代碼並複製粘貼的依賴描述符。例如,若是您想開始使用Spring和JPA進行數據庫訪問,只需spring-boot-starter-data-jpa
在項目中包含依賴項,就能夠了。
啓動器包含許多依賴項,這些依賴項是使項目快速啓動和運行所需的依賴項,以及一組受支持的託管傳遞依賴項。
如下應用程序啓動程序由Spring Boot在org.springframework.boot
組下提供 :
Table 13.1. Spring Boot application starters
Name | Description | Pom |
---|---|---|
Core starter, including auto-configuration support, logging and YAML |
||
Starter for JMS messaging using Apache ActiveMQ |
||
Starter for using Spring AMQP and Rabbit MQ |
||
Starter for aspect-oriented programming with Spring AOP and AspectJ |
||
Starter for JMS messaging using Apache Artemis |
||
Starter for using Spring Batch |
||
Starter for using Spring Framework’s caching support |
||
Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku |
||
Starter for using Cassandra distributed database and Spring Data Cassandra |
||
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive |
||
Starter for using Couchbase document-oriented database and Spring Data Couchbase |
||
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch |
||
Starter for using Spring Data JPA with Hibernate |
||
Starter for using Spring Data LDAP |
||
Starter for using MongoDB document-oriented database and Spring Data MongoDB |
||
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive |
||
Starter for using Neo4j graph database and Spring Data Neo4j |
||
Starter for using Redis key-value data store with Spring Data Redis and the Jedis client |
||
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client |
||
Starter for exposing Spring Data repositories over REST using Spring Data REST |
||
Starter for using the Apache Solr search platform with Spring Data Solr |
||
Starter for building MVC web applications using FreeMarker views |
||
Starter for building MVC web applications using Groovy Templates views |
||
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS |
||
Starter for using Spring Integration |
||
Starter for using JDBC with the Tomcat JDBC connection pool |
||
Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to |
||
Starter for using jOOQ to access SQL databases. An alternative to |
||
Starter for JTA transactions using Atomikos |
||
Starter for JTA transactions using Bitronix |
||
Spring Boot Narayana JTA Starter |
||
Starter for using Java Mail and Spring Framework’s email sending support |
||
Starter for building web applications using Spring Mobile |
||
Starter for building web applications using Mustache views |
||
Spring Boot Quartz Starter |
||
Starter for using Spring Security |
||
Starter for using Spring Social Facebook |
||
Stater for using Spring Social LinkedIn |
||
Starter for using Spring Social Twitter |
||
Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito |
||
Starter for building MVC web applications using Thymeleaf views |
||
Starter for using Java Bean Validation with Hibernate Validator |
||
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container |
||
Starter for using Spring Web Services |
||
Starter for building WebFlux applications using Spring Framework’s Reactive Web support |
||
Starter for building WebSocket applications using Spring Framework’s WebSocket support |
In addition to the application starters, the following starters can be used to add production ready features:
Table 13.2. Spring Boot production starters
Name | Description | Pom |
---|---|---|
Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application |
Finally, Spring Boot also includes some starters that can be used if you want to exclude or swap specific technical facets:
Table 13.3. Spring Boot technical starters
Name | Description | Pom |
---|---|---|
Starter for using Jetty as the embedded servlet container. An alternative to |
||
Starter for reading and writing json |
||
Starter for using Log4j2 for logging. An alternative to |
||
Starter for logging using Logback. Default logging starter |
||
Starter for using Reactor Netty as the embedded reactive HTTP server. |
||
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by |
||
Starter for using Undertow as the embedded servlet container. An alternative to |
有關其餘社區的列表貢獻首先,看 README文件中 |
Spring Boot不須要任何特定的代碼佈局,可是,有一些最佳實踐能夠提供幫助。
當一個類不包含package
聲明時,它被認爲是在「默認包」中。一般不鼓勵使用「默認包」,應該避免使用。這可能會致使使用Spring的啓動應用程序的特殊問題@ComponentScan
,@EntityScan
或@SpringBootApplication
註解,由於從每個罐子每個類,將被讀取。
咱們建議您遵循Java推薦的包命名約定並使用反向域名(例如, |
咱們一般建議您將主應用程序類放在其餘類之上的根包中。該@EnableAutoConfiguration
註解每每放在你的主類,它隱含地定義爲某些項目一基地「搜索包」。例如,若是您正在編寫JPA應用程序,@EnableAutoConfiguration
則將使用帶註釋的類的包 來搜索@Entity
項目。
使用根包還容許使用@ComponentScan
註釋而無需指定basePackage
屬性。@SpringBootApplication
若是主類位於根包中,也能夠使用 註釋。
這是一個典型的佈局:
COM + - 例子 + - myproject + - Application.java | + - 域名 | + - Customer.java | + - CustomerRepository.java | + - 服務 | + - CustomerService.java | + - 網絡 + - CustomerController.java
該Application.java
文件將聲明該main
方法以及基本方法 @Configuration
。
package com.example.myproject;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String [] args){ SpringApplication.run(Application.class, args); } }
Spring Boot favors Java-based configuration. Although it is possible to use SpringApplication
with an XML sources, we generally recommend that your primary source is a single @Configuration
class. Usually the class that defines the main
method is also a good candidate as the primary @Configuration
.
Many Spring configuration examples have been published on the Internet that use XML configuration. Always try to use the equivalent Java-based configuration if possible. Searching for |
You don’t need to put all your @Configuration
into a single class. The @Import
annotation can be used to import additional configuration classes. Alternatively, you can use @ComponentScan
to automatically pick up all Spring components, including @Configuration
classes.
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDB
is on your classpath, and you have not manually configured any database connection beans, then we will auto-configure an in-memory database.
You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration
or @SpringBootApplication
annotations to one of your @Configuration
classes.
You should only ever add one |
Auto-configuration is noninvasive, at any point you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own DataSource
bean, the default embedded database support will back away.
If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug
switch. This will enable debug logs for a selection of core loggers and log an auto-configuration report to the console.
若是您發現正在應用您不想要的特定自動配置類,則能夠使用exclude屬性@EnableAutoConfiguration
來禁用它們。
import org.springframework.boot.autoconfigure。*; import org.springframework.boot.autoconfigure.jdbc。*; import org.springframework.context.annotation。*; @Configuration @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) public class MyConfiguration { }
若是類不在類路徑上,則能夠使用excludeName
註釋的屬性並指定徹底限定名稱。最後,您還能夠控制要經過spring.autoconfigure.exclude
屬性排除的自動配置類列表 。
您能夠在註釋級別和使用屬性定義排除項。 |
您能夠自由地使用任何標準的Spring Framework技術來定義bean及其注入的依賴項。爲簡單起見,咱們常常發現使用@ComponentScan
找到你的bean,結合@Autowired
構造函數注入效果很好。
若是按照上面的建議構建代碼(在根包中定位應用程序類),則能夠添加@ComponentScan
不帶任何參數的代碼。您的全部應用程序組件(的@Component
,@Service
,@Repository
,@Controller
等)將自動註冊爲春豆。
下面是一個示例@Service
Bean,它使用構造函數注入來獲取所需的RiskAssessor
bean。
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DatabaseAccountService實現 AccountService { 私人 最終 RiskAssessor riskAssessor; @Autowired public DatabaseAccountService(RiskAssessor riskAssessor){ this .riskAssessor = riskAssessor; } // ... }
若是bean有一個構造函數,你能夠省略@Autowired
。
@Service public class DatabaseAccountService實現 AccountService { 私人 最終 RiskAssessor riskAssessor; public DatabaseAccountService(RiskAssessor riskAssessor){ this .riskAssessor = riskAssessor; } // ... }
請注意使用構造函數注入如何將 |
許多春季引導開發者老是有其主類註解爲@Configuration
, @EnableAutoConfiguration
和@ComponentScan
。因爲這些註釋常常一塊兒使用(特別是若是您遵循 上面的最佳實踐),Spring Boot提供了一個方便的@SpringBootApplication
替代方案。
該@SpringBootApplication
註解至關於使用@Configuration
, @EnableAutoConfiguration
並@ComponentScan
與他們的默認屬性:
package com.example.myproject;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication //與@Configuration相同@EnableAutoConfiguration @ComponentScan public class Application { public static void main(String [] args){ SpringApplication.run(Application .class,args); } }
|
將應用程序打包爲jar並使用嵌入式HTTP服務器的最大優點之一是,您能夠像運行任何其餘應用程序同樣運行應用程序。調試Spring Boot應用程序也很容易; 您不須要任何特殊的IDE插件或擴展。
本節僅介紹基於jar的打包,若是選擇將應用程序打包爲war文件,則應參閱服務器和IDE文檔。 |
您能夠從IDE運行Spring Boot應用程序做爲簡單的Java應用程序,可是,首先您須要導入項目。導入步驟將根據您的IDE和構建系統而有所不一樣。大多數IDE能夠直接導入Maven項目,例如Eclipse用戶能夠從菜單中選擇Import…
→ 。Existing Maven Projects
File
若是沒法將項目直接導入IDE,則能夠使用構建插件生成IDE元數據。Maven包含Eclipse和 IDEA的插件 ; Gradle提供各類IDE的插件。
若是您不當心運行Web應用程序兩次,您將看到「端口已在使用中」錯誤。STS用戶能夠使用該 |
若是您使用Spring Boot Maven或Gradle插件來建立可執行jar,則能夠使用它來運行您的應用程序java -jar
。例如:
$ java -jar target / myproject-0.0.1-SNAPSHOT.jar
也能夠運行啓用了遠程調試支持的打包應用程序。這容許您將調試器附加到打包的應用程序:
$ java -Xdebug -Xrunjdwp:server = y,transport = dt_socket,address = 8000,suspend = n \ -jar target / myproject-0.0.1-SNAPSHOT.jar
Spring Boot Maven插件包含一個run
可用於快速編譯和運行應用程序的目標。應用程序以分解形式運行,就像在IDE中同樣。
$ mvn spring-boot:run
您可能還想使用有用的操做系統環境變量:
$ export MAVEN_OPTS = -Xmx1024m
Spring Boot Gradle插件還包含一個bootRun
任務,可用於以爆炸形式運行您的應用程序。該bootRun
每當你應用的任務添加org.springframework.boot
和java
插件:
$ gradle bootRun
您可能還想使用此有用的操做系統環境變量:
$ export JAVA_OPTS = -Xmx1024m
因爲Spring Boot應用程序只是普通的Java應用程序,所以JVM熱交換應該是開箱即用的。JVM熱交換在某種程度上受限於它能夠替換的字節碼,由於能夠使用更完整的解決方案 JRebel。該 spring-boot-devtools
模塊還包括對快速應用程序重啓的支持。
有關詳細信息,請參閱下面的第20章「 開發人員工具」部分和 熱交換「操做方法」。
Spring Boot包含一組額外的工具,能夠使應用程序開發體驗更加愉快。該spring-boot-devtools
模塊能夠包含在任何項目中,以提供額外的開發時間功能。要包含devtools支持,只需將模塊依賴項添加到您的構建:
Maven的。
<dependencies>
<dependency> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-devtools </ artifactId> <optional> true </ optional> </ dependency> </ dependencies>
搖籃。
依賴{ compile(「org.springframework.boot:spring-boot-devtools」) }
運行徹底打包的應用程序時會自動禁用開發人員工具。若是您的應用程序是使用啓動的, |
從新打包的歸檔默認狀況下不包含devtools。若是要使用 某些遠程devtools功能,則須要禁用 |
Several of the libraries supported by Spring Boot use caches to improve performance. For example, template engines will cache compiled templates to avoid repeatedly parsing template files. Also, Spring MVC can add HTTP caching headers to responses when serving static resources.
Whilst caching is very beneficial in production, it can be counter productive during development, preventing you from seeing the changes you just made in your application. For this reason, spring-boot-devtools will disable those caching options by default.
Cache options are usually configured by settings in your application.properties
file. For example, Thymeleaf offers the spring.thymeleaf.cache
property. Rather than needing to set these properties manually, the spring-boot-devtools
module will automatically apply sensible development-time configuration.
For a complete list of the properties that are applied see DevToolsPropertyDefaultsPostProcessor. |
Applications that use spring-boot-devtools
will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.
You can also start your application via the supported build plugins (i.e. Maven and Gradle) as long as forking is enabled since DevTools need an isolated application classloader to operate properly. Gradle and Maven do that by default when they detect DevTools on the classpath. |
Automatic restart works very well when used with LiveReload. See below for details. If you use JRebel automatic restarts will be disabled in favor of dynamic class reloading. Other devtools features (such as LiveReload and property overrides) can still be used. |
DevTools relies on the application context’s shutdown hook to close it during a restart. It will not work correctly if you have disabled the shutdown hook ( |
When deciding if an entry on the classpath should trigger a restart when it changes, DevTools automatically ignores projects named |
DevTools needs to customize the |
Certain resources don’t necessarily need to trigger a restart when they are changed. For example, Thymeleaf templates can just be edited in-place. By default changing resources in /META-INF/maven
, /META-INF/resources
,/resources
,/static
,/public
or /templates
will not trigger a restart but will trigger a live reload. If you want to customize these exclusions you can use the spring.devtools.restart.exclude
property. For example, to exclude only /static
and /public
you would set the following:
spring.devtools.restart.exclude=static/**,public/**
if you want to keep those defaults and add additional exclusions, use the |
You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath. To do so, use thespring.devtools.restart.additional-paths
property to configure additional paths to watch for changes. You can use the spring.devtools.restart.exclude
property described above to control whether changes beneath the additional paths will trigger a full restart or just a live reload.
If you don’t want to use the restart feature you can disable it using the spring.devtools.restart.enabled
property. In most cases you can set this in yourapplication.properties
(this will still initialize the restart classloader but it won’t watch for file changes).
If you need to completely disable restart support, for example, because it doesn’t work with a specific library, you need to set a System
property before callingSpringApplication.run(…)
. For example:
public static void main(String[] args) { System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(MyApp.class, args); }
若是使用不斷編譯已更改文件的IDE,則可能更喜歡僅在特定時間觸發從新啓動。爲此,您能夠使用「觸發器文件」,這是一個特殊文件,當您想要實際觸發從新啓動檢查時,必須對其進行修改。更改文件只會觸發檢查,只有在Devtools檢測到必須執行某些操做時纔會從新啓動。觸發器文件能夠手動更新,也能夠經過IDE插件更新。
要使用觸發器文件,請使用該spring.devtools.restart.trigger-file
屬性。
您可能但願將其設置 |
如上面的Restart vs Reload部分所述,使用兩個類加載器實現了重啓功能。對於大多數應用程序,此方法頗有效,但有時它可能會致使類加載問題。
默認狀況下,IDE中的任何打開項目都將使用「restart」類加載器加載,任何常規.jar
文件都將使用「base」類加載器加載。若是您處理多模塊項目,而不是將每一個模塊導入IDE,則可能須要自定義項目。爲此,您能夠建立一個META-INF/spring-devtools.properties
文件。
該spring-devtools.properties
文件能夠包含restart.exclude.
和 restart.include.
前綴屬性。該include
元素是應該被拉高到「重啓」的類加載器的項目,以及exclude
要素是應該向下推入「基地」類加載器的項目。屬性的值是將應用於類路徑的正則表達式模式。
例如:
restart.exclude.companycommonlibs = / MyCorp的共用- [\\瓦特- ]。+ \罐子 restart.include.projectcommon = / MyCorp的-的Myproj - [\\瓦特- ]。+ \罐
全部屬性鍵必須是惟一的。只要房產開始 |
|
該spring-boot-devtools
模塊包括一個嵌入式LiveReload服務器,可用於在更改資源時觸發瀏覽器刷新。LiveReload瀏覽器擴展程序可從livereload.com免費用於Chrome,Firefox和Safari 。
若是您不想在應用程序運行時啓動LiveReload服務器,則能夠將spring.devtools.livereload.enabled
屬性設置爲false
。
您一次只能運行一個LiveReload服務器。在啓動應用程序以前,請確保沒有其餘LiveReload服務器正在運行。若是從IDE啓動多個應用程序,則只有第一個應用程序具備LiveReload支持。 |
您能夠經過添加一個文件名爲配置全局devtools設置 .spring-boot-devtools.properties
你的$HOME
文件夾(注意:文件名開頭「」)。添加到此文件的任何屬性都將應用於計算機上使用devtools的全部 Spring Boot應用程序。例如,要將restart配置爲始終使用觸發器文件,請添加如下內容:
〜/ .spring引導-devtools.properties。
spring.devtools.reload.trigger-file = .reloadtrigger
Spring Boot開發人員工具不只限於本地開發。遠程運行應用程序時,您還能夠使用多個功能。遠程支持是選擇加入,要啓用它,您須要確保它devtools
包含在從新打包的存檔中:
<build>
<plugins> <plugin> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> <configuration> <excludeDevtools> false </ excludeDevtools> </ configuration> </ plugin> </ plugins> </ build>
而後你須要設置一個spring.devtools.remote.secret
屬性,例如:
spring.devtools.remote.secret = mysecret
|
遠程devtools支持分爲兩部分; 有一個接受鏈接的服務器端端點,以及在IDE中運行的客戶端應用程序。spring.devtools.remote.secret
設置屬性後,將自動啓用服務器組件。必須手動啓動客戶端組件。
遠程客戶端應用程序旨在從IDE中運行。您須要org.springframework.boot.devtools.RemoteSpringApplication
使用與要鏈接的遠程項目相同的類路徑運行 。傳遞給應用程序的非選項參數應該是您要鏈接的遠程URL。
例如,若是您使用的是Eclipse或STS,而且您有一個名爲my-app
已部署到Cloud Foundry的項目,那麼您將執行如下操做:
Run Configurations…
從Run
菜單。Java Application
「啓動配置」。my-app
項目。org.springframework.boot.devtools.RemoteSpringApplication
做主類。https://myapp.cfapps.io
到Program arguments
(或任何遠程URL)。正在運行的遠程客戶端將以下所示:
。____ _ __ _ _ / \\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ (()\ ___ |'_ |'_ ||'_ \ / _` | | _ \ ___ _ __ ___ | | _ ___ \ \ \ \ \\ / ___)| | _)| | | | | || (_ | [] :::::: [] / -_)'\ / _ \ _ / -_)))))) ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / =========|_|==============|___/===================================/_/_/_/ :: Spring Boot Remote :: 2.0.0.M3 2015-06-10 18:25:06.632 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication on pwmbp with PID 14938 (/Users/pwebb/projects/spring-boot/code/spring-boot-devtools/target/classes started by pwebb in /Users/pwebb/projects/spring-boot/code/spring-boot-samples/spring-boot-sample-devtools) 2015-06-10 18:25:06.671 INFO 14938 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a17b7b6: startup date [Wed Jun 10 18:25:06 PDT 2015]; root of context hierarchy 2015-06-10 18:25:07.043 WARN 14938 --- [ main] o.s.b.d.r.c.RemoteClientConfiguration : The connection to http://localhost:8080 is insecure. You should use a URL starting with 'https://'. 2015-06-10 18:25:07.074 INFO 14938 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2015-06-10 18:25:07.130 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105)
Because the remote client is using the same classpath as the real application it can directly read application properties. This is how the |
It’s always advisable to use |
If you need to use a proxy to access the remote application, configure the |
The remote client will monitor your application classpath for changes in the same way as the local restart. Any updated resource will be pushed to the remote application and (if required) trigger a restart. This can be quite helpful if you are iterating on a feature that uses a cloud service that you don’t have locally. Generally remote updates and restarts are much quicker than a full rebuild and deploy cycle.
Files are only monitored when the remote client is running. If you change a file before starting the remote client, it won’t be pushed to the remote server. |
Executable jars can be used for production deployment. As they are self-contained, they are also ideally suited for cloud-based deployment.
For additional 「production ready」 features, such as health, auditing and metric REST or JMX end-points; consider adding spring-boot-actuator
. See Part V, 「Spring Boot Actuator: Production-ready features」 for details.
您如今應該很好地理解如何使用Spring Boot以及您應該遵循的一些最佳實踐。您如今能夠繼續深刻瞭解特定的 Spring Boot功能,或者您能夠跳過並閱讀Spring Boot 的「 生產就緒 」方面。
本節深刻介紹Spring Boot的詳細信息。在這裏,您能夠了解要使用和自定義的主要功能。若是您尚未,可能須要閱讀第II部分「入門」和 第III部分「使用Spring Boot」部分,以便您掌握基礎知識。
本SpringApplication
類提供了一個方便的方式來引導,未來自啓動Spring應用程序main()
的方法。在許多狀況下,您能夠委託靜態SpringApplication.run
方法:
public static void main(String [] args){ SpringApplication.run(MySpringConfiguration 類,參數); }
當您的應用程序啓動時,您應該看到相似於如下內容:
。____ _ __ _ _ / \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ (()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \ \\ / ___)| | _)| | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / / ========= | _ | ============== | ___ / = / _ / _ / _ / :: Spring Boot :: v2.0.0.M3 2013-07-31 00:08:16.117 INFO 56603 --- [main] osbsapp.SampleApplication:在個人計算機上使用PID 56603啓動SampleApplication v0.1.0(/ apps / myapp.jar由pwebb啓動) 2013-07-31 00:08:16.166 INFO 56603 --- [main] ationConfigServletWebServerApplicationContext:刷新org.springframework.boot.web.ser vlet.context.AnnotationConfigServletWebServerApplicationContext @ 6e5a8246:啓動日期[Wed Jul 31 00:08:16 PDT 2013]; 上下文層次結構的根 2014-03-04 13:09:54.912 INFO 41370 --- [main] .t.TomcatServletWebServerFactory:服務器初始化端口:8080 2014-03-04 13:09:56.501 INFO 41370 --- [main] osbsapp.SampleApplication:在2.992秒內啓動SampleApplication(JVM運行3.658)
默認狀況下,INFO
將顯示日誌消息,包括一些相關的啓動詳細信息,例如啓動應用程序的用戶。
若是您的應用程序沒法啓動,則已註冊FailureAnalyzers
有機會提供專用錯誤消息和具體操做來解決問題。例如,若是您在端口上啓動Web應用程序8080
而且該端口已在使用中,您應該看到相似於如下內容的內容:
*************************** 應用程序未能啓動 *************************** 描述: 嵌入式servlet容器沒法啓動。8080端口已經投入使用。 行動: 識別並中止正在偵聽端口8080的進程或將此應用程序配置爲偵聽另外一個端口。
Spring Boot提供了許多 |
若是沒有故障分析器可以處理異常,您仍然能夠顯示完整的自動配置報告,以更好地瞭解出現了什麼問題。要作到這一點,你須要 使debug
財產或 啓用DEBUG
日誌記錄的 org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer
。
例如,若是您使用的是運行應用程序,則java -jar
能夠debug
按以下方式啓用該 屬性:
$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
The banner that is printed on start up can be changed by adding a banner.txt
file to your classpath, or by setting banner.location
to the location of such a file. If the file has an unusual encoding you can set banner.charset
(default is UTF-8
). In addition to a text file, you can also add a banner.gif
, banner.jpg
or banner.png
image file to your classpath, or set a banner.image.location
property. Images will be converted into an ASCII art representation and printed above any text banner.
Inside your banner.txt
file you can use any of the following placeholders:
Table 23.1. Banner variables
Variable | Description |
---|---|
|
The version number of your application as declared in |
|
爲 |
|
您正在使用的Spring Boot版本。例如 |
|
您正在使用的Spring Boot版本用於顯示(用括號括起來並帶有前綴 |
|
|
|
您申請的標題 |
|
您還能夠使用該spring.main.banner-mode
屬性來肯定是否必須使用配置的記錄器()打印System.out
(console
),log
或者根本不打印橫幅(off
)。
打印的橫幅將在名稱下注冊爲單個bean springBootBanner
。
YAML映射 spring: main: banner-mode:「off」 |
若是SpringApplication
默認值不符合您的須要,您能夠建立一個本地實例並進行自定義。例如,要關閉您要寫的橫幅:
public static void main(String [] args){ SpringApplication應用= 新 SpringApplication(MySpringConfiguration。類); app.setBannerMode(Banner.Mode.OFF); app.run(參數); }
傳遞給的構造函數參數 |
也能夠配置SpringApplication
使用application.properties
文件。有關詳細信息,請參見第24章,外部化配置。
有關配置選項的完整列表,請參閱 SpringApplication
Javadoc。
若是您須要構建ApplicationContext
層次結構(具備父/子關係的多個上下文),或者您只是喜歡使用'流暢'構建器API,則能夠使用SpringApplicationBuilder
。
將SpringApplicationBuilder
讓您鏈在一塊兒的多個方法調用,包括parent
和child
,讓您建立一個層次結構的方法。
例如:
新的 SpringApplicationBuilder() .sources(家長。類) .child(申請。班) .bannerMode(Banner.Mode.OFF) .RUN(參數);
建立 |
除了一般的Spring Framework事件以外,例如 ContextRefreshedEvent
,SpringApplication
發送一些額外的應用程序事件。
某些事件實際上 若是您但願自動註冊這些偵聽器而無論應用程序的建立方式如何,您能夠將 org.springframework.context.ApplicationListener = com.example.project.MyListener |
應用程序運行時,應按如下順序發送應用程序事件:
ApplicationStartingEvent
是在一個運行開始發送,但除了聽衆和初始化的登記任何處理以前。ApplicationEnvironmentPreparedEvent
當被髮送Environment
到在上下文已知被使用,可是在建立上下文以前。ApplicationPreparedEvent
被髮送刷新開始以前,但通過bean定義已經被加載。ApplicationReadyEvent
在刷新以後發送一個而且已經處理了任何相關的回調以指示應用程序已準備好服務請求。ApplicationFailedEvent
若是在啓動時異常發送。 您一般不須要使用應用程序事件,但知道它們存在可能很方便。在內部,Spring Boot使用事件來處理各類任務。 |
A SpringApplication
將嘗試ApplicationContext
表明您建立正確的類型。默認狀況下,將使用AnnotationConfigApplicationContext
或AnnotationConfigServletWebServerApplicationContext
將使用,具體取決於您是否正在開發Web應用程序。
用於肯定「web環境」的算法至關簡單(基於幾個類的存在)。setWebEnvironment(boolean webEnvironment)
若是須要覆蓋默認值,則能夠使用。
It is also possible to take complete control of the ApplicationContext
type that will be used by calling setApplicationContextClass(…)
.
It is often desirable to call |
If you need to access the application arguments that were passed to SpringApplication.run(…)
you can inject aorg.springframework.boot.ApplicationArguments
bean. The ApplicationArguments
interface provides access to both the raw String[]
arguments as well as parsed option
and non-option
arguments:
import org.springframework.boot.*
import org.springframework.beans.factory.annotation.* import org.springframework.stereotype.* @Component public class MyBean { @Autowired public MyBean(ApplicationArguments args) { boolean debug = args.containsOption("debug"); List<String> files = args.getNonOptionArgs(); // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] } }
Spring Boot will also register a |
If you need to run some specific code once the SpringApplication
has started, you can implement the ApplicationRunner
or CommandLineRunner
interfaces. Both interfaces work in the same way and offer a single run
method which will be called just before SpringApplication.run(…)
completes.
The CommandLineRunner
interfaces provides access to application arguments as a simple string array, whereas the ApplicationRunner
uses the ApplicationArguments
interface discussed above.
import org.springframework.boot.*
import org.springframework.stereotype.* @Component public class MyBean implements CommandLineRunner { public void run(String... args) { // Do something... } }
You can additionally implement the org.springframework.core.Ordered
interface or use the org.springframework.core.annotation.Order
annotation if several CommandLineRunner
or ApplicationRunner
beans are defined that must be called in a specific order.
Each SpringApplication
will register a shutdown hook with the JVM to ensure that the ApplicationContext
is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean
interface, or the @PreDestroy
annotation) can be used.
In addition, beans may implement the org.springframework.boot.ExitCodeGenerator
interface if they wish to return a specific exit code when SpringApplication.exit()
is called. This exit code can then be passed to System.exit()
to return it as a status code.
@SpringBootApplication public class ExitCodeApplication { @Bean public ExitCodeGenerator exitCodeGenerator() { return () -> 42; } public static void main(String[] args) { System.exit(SpringApplication .exit(SpringApplication.run(ExitCodeApplication 類,參數))); } }
此外,ExitCodeGenerator
能夠經過例外來實現接口。遇到這種異常時,Spring Boot將返回實現getExitCode()
方法提供的退出代碼。
能夠經過指定spring.application.admin.enabled
屬性爲應用程序啓用與管理相關的功能 。這暴露 SpringApplicationAdminMXBean
了平臺MBeanServer
。您能夠使用此功能遠程管理Spring Boot應用程序。這對任何服務包裝器實現也頗有用。
若是您想知道應用程序正在運行的HTTP端口,請使用密鑰獲取屬性 |
啓用此功能時要當心,由於MBean公開了一種關閉應用程序的方法。 |
Spring Boot容許您外部化配置,以便在不一樣環境中使用相同的應用程序代碼。您能夠使用屬性文件,YAML文件,環境變量和命令行參數來外部化配置。能夠使用@Value
註釋將屬性值直接注入到bean中,經過Spring的Environment
抽象訪問或 經過綁定到結構化對象@ConfigurationProperties
。
Spring Boot使用一種很是特殊的PropertySource
順序,旨在容許合理地覆蓋值。按如下順序考慮屬性:
~/.spring-boot-devtools.properties
當devtools處於活動狀態時)。@TestPropertySource
你的測試註釋。@SpringBootTest#properties
測試中的註釋屬性。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 公共 類 MyBean { @Value(「$ {name}」) 私有字符串名稱; // ... }
在您的應用程序類路徑(例如,在您的jar中),您能夠擁有一個 application.properties
爲其提供合理的默認屬性值name
。在新環境中運行時,application.properties
能夠在jar外部提供覆蓋name
; 對於一次性測試,您能夠使用特定的命令行開關啓動(例如java -jar app.jar --name="Spring"
)。
該 $ SPRING_APPLICATION_JSON ='{「foo」:{「bar」:「spam」}}'java -jar myapp.jar 在這個例子中,你將 $ java -Dspring.application.json ='{「foo」:「bar」}'-jar myapp.jar 或命令行參數: $ java -jar myapp.jar --spring.application.json ='{「foo」:「bar」}' 或者做爲JNDI變量 |
這RandomValuePropertySource
對於注入隨機值(例如,進入祕密或測試用例)很是有用。它能夠產生整數,長整數,uuids或字符串,例如
my.secret = $ {random.value} my.number = $ {random.int} my.bignumber = $ {random.long} my.uuid = $ {random.uuid} my.number.less.than.ten = $ {random.int(10)} my.number.in.range = $ {random.int [1024,65536]}
該random.int*
語法是OPEN value (,max) CLOSE
其中的OPEN,CLOSE
任何字符和value,max
是整數。若是max
提供則value
是最小值而且max
是最大值(不包括)。
默認狀況下,SpringApplication
將任何命令行選項參數(以' - '開頭,例如--server.port=9000
)轉換爲a property
並將其添加到Spring Environment
。如上所述,命令行屬性始終優先於其餘屬性源。
若是您不但願將命令行屬性添加到Environment
您能夠使用它們禁用它們SpringApplication.setAddCommandLineProperties(false)
。
SpringApplication
將從application.properties
如下位置的文件加載屬性並將它們添加到Spring Environment
:
/config
當前目錄下的子目錄。/config
包列表按優先級排序(在列表中較高位置定義的屬性將覆蓋在較低位置中定義的屬性)。
您還能夠使用YAML('。mil')文件替代'.properties'。 |
若是您不喜歡application.properties
配置文件名,能夠經過指定spring.config.name
環境屬性切換到另外一個。您還能夠使用spring.config.location
environment屬性(以逗號分隔的目錄位置列表或文件路徑)來引用顯式位置。
$ java -jar myproject.jar --spring.config.name = myproject
要麼
$ java -jar myproject.jar --spring.config.location = classpath:/default.properties,classpath:/override.properties
|
若是spring.config.location
包含目錄(而不是文件),則它們應該以/
(而且將附加spring.config.name
在加載以前生成的名稱,包括特定於配置文件的文件名)附加。指定的文件 spring.config.location
按原樣使用,不支持特定於配置文件的變體,並將被任何特定於配置文件的屬性覆蓋。
以相反的順序搜索配置位置。默認狀況下,配置的位置是 classpath:/,classpath:/config/,file:./,file:./config/
。生成的搜索順序爲:
file:./config/
file:./
classpath:/config/
classpath:/
配置自定義配置位置時,除默認位置外,還會使用它們。在默認位置以前搜索自定義位置。例如,若是classpath:/custom-config/,file:./custom-config/
配置了自定義位置,則搜索順序將變爲:
file:./custom-config/
classpath:custom-config/
file:./config/
file:./
classpath:/config/
classpath:/
This search ordering allows you to specify default values in one configuration file and then selectively override those values in another. You can provide default values for you application in application.properties
(or whatever other basename you choose with spring.config.name
) in one of the default locations. These default values can then be overriden at runtime with a different file located in one of the custom locations.
If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (e.g. |
If you are running in a container then JNDI properties (in |
In addition to application.properties
files, profile-specific properties can also be defined using the naming convention application-{profile}.properties
. TheEnvironment
has a set of default profiles (by default [default]
) which are used if no active profiles are set (i.e. if no profiles are explicitly activated then properties from application-default.properties
are loaded).
Profile-specific properties are loaded from the same locations as standard application.properties
, with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.
If several profiles are specified, a last wins strategy applies. For example, profiles specified by the spring.profiles.active
property are added after those configured via the SpringApplication
API and therefore take precedence.
若是您已指定任何文件 |
當使用它們時,application.properties
將經過現有值過濾這些值,Environment
以便您能夠返回先前定義的值(例如,從系統屬性)。
app.name = MyApp app.description = $ {app.name}是一個Spring Boot應用程序
您還能夠使用此技術建立現有Spring Boot屬性的「短」變體。有關詳細信息,請參見第73.4節「使用'短'命令行參數」操做方法。 |
YAML是JSON的超集,所以是用於指定分層配置數據的很是方便的格式。該SpringApplication
課程將自動支持YAML做爲一種替代性,只要你有 SnakeYAML在classpath庫。
若是您使用'Starters',將自動提供SnakeYAML |
Spring Framework提供了兩個方便的類,可用於加載YAML文檔。在YamlPropertiesFactoryBean
將加載YAML做爲Properties
和 YamlMapFactoryBean
將加載YAML做爲Map
。
例如,如下YAML文檔:
環境: dev: url:http://dev.bar.com 名稱:Developer Setup prod: url:http://foo.bar.com name:My Cool App
將轉化爲這些屬性:
environments.dev.url = http://dev.bar.com environments.dev.name =開發人員設置 environment.prod.url = http://foo.bar.com environments.prod.name =個人酷應用
YAML列表表示爲具備[index]
解除引用的屬性鍵,例如此YAML:
個人: 服務器: - dev.bar.com - foo.bar.com
將轉化爲這些屬性:
my.servers [0] = dev.bar.com my.servers [1] = foo.bar.com
要使用Spring DataBinder
實用程序綁定到相似的屬性(這是什麼 @ConfigurationProperties
),您須要在類型java.util.List
(或Set
)的目標bean中具備屬性, 而且您須要提供一個setter,或者使用可變值初始化它,例如this將綁定到上面的屬性
@ConfigurationProperties(prefix =「my」) public class Config { private List <String> servers = new ArrayList <String>(); public List <String> getServers(){ return this .servers; } }
配置列表時須要格外當心,由於覆蓋將沒法正常工做。在上面的示例中,當 個人: 服務器:dev.bar.com,foo.bar.com |
本YamlPropertySourceLoader
類可用於暴露YAML做爲PropertySource
在春節Environment
。這容許您使用熟悉的@Value
註釋和佔位符語法來訪問YAML屬性。
您能夠使用spring.profiles
鍵指定文檔什麼時候適用,從而在單個文件中指定多個特定於配置文件的YAML文檔。例如:
服務器: 地址:192.168。1.100 --- spring: profiles:開發 服務器: 地址:127.0。0.1 --- spring: profiles:生產 服務器: 地址:192.168。1.120
在上面的示例中,若是 配置文件處於活動狀態,則server.address
屬性爲。若是未 啓用和配置文件,則屬性的值將爲。127.0.0.1
development
development
production
192.168.1.100
若是在應用程序上下文啓動時沒有顯式活動,則激活默認配置文件。所以,在這個YAML咱們設定的值security.user.password
是 只可在「默認」的我的資料:
server: port:8000 --- spring: profiles:默認 安全: user: 密碼:弱
whereas in this example, the password is always set because it isn’t attached to any profile, and it would have to be explicitly reset in all other profiles as necessary:
server:
port: 8000 security: user: password: weak
Spring profiles designated using the "spring.profiles" element may optionally be negated using the !
character. If both negated and non-negated profiles are specified for a single document, at least one non-negated profile must match and no negated profiles may match.
YAML files can’t be loaded via the @PropertySource
annotation. So in the case that you need to load values that way, you need to use a properties file.
As we have seen above, any YAML content is ultimately transformed to properties. That process may be counter intuitive when overriding 「list」 properties via a profile.
For example, assume a MyPojo
object with name
and description
attributes that are null
by default. Let’s expose a list of MyPojo
from FooProperties
:
@ConfigurationProperties("foo") public class FooProperties { private final List<MyPojo> list = new ArrayList<>(); public List<MyPojo> getList() { return this.list; } }
Consider the following configuration:
foo: list: - name:my name description:my description --- spring: profiles:dev foo: list: - name:my another name
若是dev
配置文件未激活,FooProperties.list
將包含一個MyPojo
如上定義的條目。dev
可是,若是啓用了配置文件,list
則仍將 只包含一個條目(名稱爲「個人另外一個名稱」和描述null
)。此配置不會MyPojo
向列表添加第二個實例,也不會合並項目。
在多個配置文件中指定集合時,將使用具備最高優先級的集合(而且僅使用該集合):
foo: list: - name:my name description:my description - name:another name description:another description --- spring: profiles:dev foo: list: - name:my another name
在上面的示例中,考慮到dev
配置文件處於活動狀態,FooProperties.list
將包含一個 MyPojo
條目(名稱爲「個人另外一個名稱」和描述null
)。
使用@Value("${property}")
註釋注入配置屬性有時會很麻煩,尤爲是在使用多個屬性或數據本質上是分層的狀況下。Spring Boot提供了一種使用屬性的替代方法,容許強類型bean管理和驗證應用程序的配置。
包 com.example;
import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(「foo」) 公共 類 FooProperties { private boolean enabled; private InetAddress remoteAddress; private final Security security = new Security(); public boolean isEnabled(){...} public void setEnabled(boolean enabled){...} public InetAddress getRemoteAddress(){...} public void setRemoteAddress(InetAddress remoteAddress){...} 公共安全 getSecurity(){...} public static class Security { 私有 String用戶名; 私有字符串密碼; private List <String> roles = new ArrayList <>(Collections.singleton(「USER」)); public String getUsername(){...} public void setUsername(String username){...} public String getPassword(){...} public void setPassword(String password){...} public List <String> getRoles(){...} public void setRoles(List <String> roles){...} } }
上面的POJO定義瞭如下屬性:
foo.enabled
,false
默認狀況下foo.remote-address
,具備能夠強制的類型 String
foo.security.username
,帶有嵌套的「安全性」,其名稱由屬性名稱決定。特別是那裏根本沒有使用返回類型SecurityProperties
foo.security.password
foo.security.roles
,收集 String
getter和setter一般是必需的,由於綁定是經過標準的Java Beans屬性描述符,就像在Spring MVC中同樣。有些狀況下可能會省略setter:
Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok doesn’t generate any particular constructor for such type as it will be used automatically by the container to instantiate the object. |
See also the differences between |
You also need to list the properties classes to register in the @EnableConfigurationProperties
annotation:
@Configuration @EnableConfigurationProperties(FooProperties.class) public class MyConfiguration { }
When The bean name in the example above will be |
Even if the configuration above will create a regular bean for FooProperties
, we recommend that @ConfigurationProperties
only deal with the environment and in particular does not inject other beans from the context. Having said that, The @EnableConfigurationProperties
annotation is also automatically applied to your project so that any existing bean annotated with @ConfigurationProperties
will be configured from the Environment
. You could shortcut MyConfiguration
above by making sure FooProperties
is a already a bean:
@Component @ConfigurationProperties(prefix="foo") public class FooProperties { // ... see above }
This style of configuration works particularly well with the SpringApplication
external YAML configuration:
# application.yml
foo: remote-address: 192.168.1.1 security: username: foo roles: - USER - ADMIN # additional configuration as required
To work with @ConfigurationProperties
beans you can just inject them in the same way as any other bean.
@Service public class MyService { private final FooProperties properties; @Autowired public MyService(FooProperties properties) { this.properties = properties; } //... @PostConstruct public void openConnection() { Server server = new Server(this.properties.getRemoteAddress()); // ... } }
Using |
As well as using @ConfigurationProperties
to annotate a class, you can also use it on public @Bean
methods. This can be particularly useful when you want to bind properties to third-party components that are outside of your control.
To configure a bean from the Environment
properties, add @ConfigurationProperties
to its bean registration:
@ConfigurationProperties(prefix = "bar") @Bean public BarComponent barComponent() { ... }
Any property defined with the bar
prefix will be mapped onto that BarComponent
bean in a similar manner as the FooProperties
example above.
Spring Boot uses some relaxed rules for binding Environment
properties to @ConfigurationProperties
beans, so there doesn’t need to be an exact match between the Environment
property name and the bean property name. Common examples where this is useful include dashed separated (e.g. context-path
binds to contextPath
), and capitalized (e.g. PORT
binds to port
) environment properties.
For example, given the following @ConfigurationProperties
class:
@ConfigurationProperties(prefix =「person」) public class OwnerProperties { private String firstName; public String getFirstName(){ return this .firstName; } public void setFirstName(String firstName){ this .firstName = firstName; } }
能夠使用如下屬性名稱:
表24.1。輕鬆綁定
屬性 | 注意 |
---|---|
|
標準的駝峯案例語法。 |
|
烤肉串,建議用於 |
|
下劃線表示法,用於 |
|
大寫格式。建議在使用系統環境變量時使用。 |
|
表24.2。每一個屬性源放寬綁定規則
物業來源 | 簡單 | 名單 |
---|---|---|
屬性文件 |
駱駝箱,烤肉串或下劃線表示法 |
標準列表語法使用 |
YAML文件 |
駱駝箱,烤肉串或下劃線表示法 |
標準YAML列表語法或逗號分隔值 |
環境變量 |
大寫格式,下劃線做爲分隔符。 |
下劃線包圍的數字值。例如: |
系統屬性 |
駱駝箱,烤肉串或下劃線表示法 |
標準列表語法使用 |
咱們建議,若是可能,屬性以小寫kebab格式存儲。即 |
Spring will attempt to coerce the external application properties to the right type when it binds to the @ConfigurationProperties
beans. If you need custom type conversion you can provide a ConversionService
bean (with bean id conversionService
) or custom property editors (via a CustomEditorConfigurer
bean) or custom Converters
(with bean definitions annotated as @ConfigurationPropertiesBinding
).
As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your |
Spring Boot will attempt to validate @ConfigurationProperties
classes whenever they are annotated with Spring’s @Validated
annotation. You can use JSR-303 javax.validation
constraint annotations directly on your configuration class. Simply ensure that a compliant JSR-303 implementation is on your classpath, then add constraint annotations to your fields:
@ConfigurationProperties(prefix="foo") @Validated public class FooProperties { @NotNull private InetAddress remoteAddress; // ... getters and setters }
In order to validate values of nested properties, you must annotate the associated field as @Valid
to trigger its validation. For example, building upon the aboveFooProperties
example:
@ConfigurationProperties(prefix="connection") @Validated public class FooProperties { @NotNull private InetAddress remoteAddress; @Valid private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty public String username; // ... getters and setters } }
您還能夠Validator
經過建立名爲的bean定義 來添加自定義Spring configurationPropertiesValidator
。@Bean
應聲明該方法static
。配置屬性驗證器是在應用程序生命週期的早期建立的,並將該@Bean
方法聲明爲static,容許建立bean而無需實例化@Configuration
該類。這避免了早期實例化可能致使的任何問題。有一個 屬性驗證示例,您能夠看到如何設置。
該 |
@Value
是一個核心容器功能,它不提供與類型安全的配置屬性相同的功能。下表彙總了支持的功能@ConfigurationProperties
和@Value
:
若是爲本身的組件定義一組配置鍵,咱們建議您將它們分組到帶註釋的POJO中@ConfigurationProperties
。另請注意,因爲@Value
不支持寬鬆綁定,所以若是須要使用環境變量提供值,則不是一個很好的選擇。
最後,雖然您能夠編寫SpEL
表達式@Value
,但不會從Application屬性文件處理此類表達式。
Spring Profiles提供了一種隔離應用程序配置部分並使其僅在特定環境中可用的方法。任何@Component
或@Configuration
能夠標記@Profile
以限制什麼時候加載:
@Configuration @Profile(「production」) 公共 類 ProductionConfiguration { // ... }
在常規Spring方式中,您能夠使用spring.profiles.active
Environment
屬性指定哪些配置文件處於活動狀態。您能夠經過任何經常使用方式指定屬性,例如,您能夠將其包含在application.properties
:
spring.profiles.active = dev,hsqldb
或使用開關在命令行上指定--spring.profiles.active=dev,hsqldb
。
該spring.profiles.active
物業遵循與其餘物業相同的訂購規則,最高PropertySource
將獲勝。這意味着您能夠指定活動配置文件,application.properties
而後使用命令行開關替換它們。
有時,將特定於配置文件的屬性添加到活動配置文件而不是替換它們是有用的。該spring.profiles.include
屬性可用於無條件添加活動配置文件。該SpringApplication
入口點還設置額外的配置文件(即對那些被激活頂部的Java API的 spring.profiles.active
屬性):看setAdditionalProfiles()
方法。
例如,當與如下屬性的應用程序正在使用開關運行 --spring.profiles.active=prod
的proddb
和prodmq
輪廓也將被激活:
---
my.property:fromyamlfile --- spring.profiles:PROD spring.profiles.include: - proddb - prodmq
請記住, |
您能夠SpringApplication.setAdditionalProfiles(…)
在應用程序運行以前經過調用以編程方式設置活動配置文 也能夠使用Spring的ConfigurableEnvironment
界面激活配置文件。
Spring Boot使用Commons Logging進行全部內部日誌記錄,但保留底層日誌實現。爲Java Util Logging, Log4J2和Logback提供了默認配置 。在每種狀況下,記錄器都預先配置爲使用控制檯輸出,而且還提供可選的文件輸出。
默認狀況下,若是使用「啓動器」,則將使用Logback進行日誌記錄。還包括適當的Logback路由,以確保使用Java Util Logging,Commons Logging,Log4J或SLF4J的依賴庫都能正常工做。
Java有不少日誌框架可供使用。若是以上列表看起來使人困惑,請不要擔憂。一般,您不須要更改日誌記錄依賴項,Spring Boot默認值也能夠正常工做。 |
Spring Boot的默認日誌輸出以下所示:
2014-03-05 10:57:51.112 INFO 45469 --- [main] org.apache.catalina.core.StandardEngine:啓動Servlet引擎:Apache Tomcat / 7.0.52 2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] oaccC [Tomcat]。[localhost]。[/]:初始化Spring嵌入式WebApplicationContext 2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] osweb.context.ContextLoader:Root WebApplicationContext:初始化在1358 ms完成 2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] osbceServletRegistrationBean:將servlet:'dispatcherServlet'映射到[/] 2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean:映射過濾器:'hiddenHttpMethodFilter'到:[/ *]
輸出如下項目:
ERROR
,,WARN
或。INFO
DEBUG
TRACE
---
分離器來區分實際日誌消息的開始。 Logback does not have a |
The default log configuration will echo messages to the console as they are written. By default ERROR
, WARN
and INFO
level messages are logged. You can also enable a 「debug」 mode by starting your application with a --debug
flag.
$ java -jar myapp.jar --debug
you can also specify |
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG
level.
Alternatively, you can enable a 「trace」 mode by starting your application with a --trace
flag (or trace=true
in your application.properties
). This will enable trace logging for a selection of core loggers (embedded container, Hibernate schema generation and the whole Spring portfolio).
If your terminal supports ANSI, color output will be used to aid readability. You can set spring.output.ansi.enabled
to a supported value to override the auto detection.
Color coding is configured using the %clr
conversion word. In its simplest form the converter will color the output according to the log level, for example:
%clr(%5p)
The mapping of log level to a color is as follows:
Level | Color |
---|---|
|
Red |
|
Red |
|
Yellow |
|
Green |
|
Green |
|
Green |
Alternatively, you can specify the color or style that should be used by providing it as an option to the conversion. For example, to make the text yellow:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
The following colors and styles are supported:
blue
cyan
faint
green
magenta
red
yellow
By default, Spring Boot will only log to the console and will not write log files. If you want to write log files in addition to the console output you need to set alogging.file
or logging.path
property (for example in your application.properties
).
The following table shows how the logging.*
properties can be used together:
Table 26.1. Logging properties
logging.file |
logging.path |
Example | Description |
---|---|---|---|
(none) |
(none) |
Console only logging. |
|
Specific file |
(none) |
|
Writes to the specified log file. Names can be an exact location or relative to the current directory. |
(none) |
Specific directory |
|
寫入 |
日誌文件將在達到10 MB時旋轉,而且與控制檯輸出同樣ERROR
,WARN
而且INFO
默認狀況下會記錄級別消息。
日誌記錄系統在應用程序生命週期的早期初始化,所以在經過 |
日誌記錄屬性獨立於實際的日誌記錄基礎結構。所以, |
全部受支持的日誌記錄系統均可以使用'logging.level。* = LEVEL'在Spring中設置記錄器級別 Environment
(例如application.properties
),其中'LEVEL'是TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF之一。該root
記錄器能夠經過如下方式配置logging.level.root
。示例application.properties
:
logging.level.root = WARN logging.level.org.springframework.web = DEBUG logging.level.org.hibernate = ERROR
默認狀況下,Spring Boot會從新映射Thymeleaf |
能夠經過在類路徑中包含適當的庫來激活各類日誌記錄系統,並經過在類路徑的根目錄中或Spring Environment
屬性 指定的位置提供合適的配置文件來進一步自定義logging.config
。
您能夠使用org.springframework.boot.logging.LoggingSystem
系統屬性強制Spring Boot使用特定的日誌記錄系統 。該值應該是實現的徹底限定類名LoggingSystem
。您還能夠經過使用值來徹底禁用Spring Boot的日誌記錄配置none
。
因爲記錄被初始化以前的 |
根據您的日誌記錄系統,將加載如下文件:
記錄系統 | 定製 |
---|---|
的logback |
|
Log4j2 |
|
JDK(Java Util Logging) |
|
若是可能,咱們建議您使用 |
Java Util Logging存在已知的類加載問題,從「可執行jar」運行時會致使問題。咱們建議您儘量避免使用它。 |
爲了幫助定製,一些其餘屬性從Spring轉移 Environment
到System屬性:
春天的環境 | 系統屬性 | 評論 |
---|---|---|
|
|
記錄異常時使用的轉換字。 |
|
|
若是已定義,則用於默認日誌配置。 |
|
|
若是已定義,則用於默認日誌配置。 |
|
|
要在控制檯上使用的日誌模式(stdout)。(僅支持默認的logback設置。) |
|
|
要在文件中使用的日誌模式(若是啓用了LOG_FILE)。(僅支持默認的logback設置。) |
|
|
用於呈現日誌級別的格式(默認 |
|
|
當前進程ID(若是可能,則在未定義爲OS環境變量時發現)。 |
支持的全部日誌記錄系統在解析其配置文件時均可以參考系統屬性。有關spring-boot.jar
示例,請參閱默認配置。
若是要在日誌記錄屬性中使用佔位符,則應使用 Spring Boot的語法而不是底層框架的語法。值得注意的是,若是您使用的是Logback,則應將其 |
您能夠經過僅覆蓋 2015-09-30 12:30:04.031用戶:juergen INFO 22174 --- [nio-8080-exec-0] demo.Controller 處理通過身份驗證的請 |
Spring Boot包含許多Logback擴展,能夠幫助進行高級配置。您能夠在logback-spring.xml
配置文件中使用這些擴展名。
您不能在標準 |
擴展不能與Logback的 配置掃描一塊兒使用。若是您嘗試這樣作,更改配置文件將致使相似於如下記錄之一的錯誤: |
ch.qos.logback.core.joran.spi.Interpreter@4中的錯誤:71 - [springProperty]沒有適用的操做,當前的ElementPath是[[configuration] [springProperty]]ch.qos.logback.core.joran.spi.Interpreter@4中的 錯誤:71 - [springProfile]沒有適用的操做,當前的ElementPath是[[configuration] [springProfile]]
該<springProfile>
標籤容許您有選擇地包括或排除基於主動春型材配置的部分。在<configuration>
元素內的任何位置都支持配置文件節。使用該name
屬性指定哪一個配置文件接受配置。能夠使用逗號分隔列表指定多個配置文件。
<springProfile name = 「staging」 > <! - 「暫存」配置文件處於活動狀態時啓用的配置 - > </ springProfile> <springProfile name = 「dev,staging」 > <! - 在「dev」或「staging」配置文件處於活動狀態時啓用的配置 - > </ springProfile> <springProfile name = 「!production」 > <! - 「生產」配置文件未激活時要啓用的配置 - > </ springProfile>
The <springProperty>
tag allows you to surface properties from the Spring Environment
for use within Logback. This can be useful if you want to access values from your application.properties
file in your logback configuration. The tag works in a similar way to Logback’s standard <property>
tag, but rather than specifying a direct value
you specify the source
of the property (from the Environment
). You can use the scope
attribute if you need to store the property somewhere other than in local
scope. If you need a fallback value in case the property is not set in the Environment
, you can use the defaultValue
attribute.
<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host" defaultValue="localhost"/> <appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender"> <remoteHost>${fluentHost}</remoteHost> ... </appender>
The |
Spring Boot is well suited for web application development. You can easily create a self-contained HTTP server using embedded Tomcat, Jetty, Undertow, or Netty. Most web applications will use the spring-boot-starter-web
module to get up and running quickly. You can also choose to use to build reactive web applications by using the spring-boot-starter-webflux
module.
If you haven’t yet developed a Spring Boot web application you can follow the "Hello World!" example in the Getting started section.
Spring Web MVC框架(一般簡稱爲「Spring MVC」)是一個豐富的「模型視圖控制器」Web框架。Spring MVC容許您建立特殊@Controller
或@RestController
bean來處理傳入的HTTP請求。控制器中的方法使用@RequestMapping
註釋映射到HTTP 。
如下是@RestController
提供JSON數據的典型示例:
@RestController @RequestMapping(value =「/ users」) public class MyRestController { @RequestMapping(value =「/ {user}」,method = RequestMethod.GET) public User getUser( @PathVariable Long user){ // ... } @RequestMapping(value =「/ {user} / customers」,method = RequestMethod.GET) List <Customer> getUserCustomers( @PathVariable Long user){ // ... } @RequestMapping(value =「/ {user}」,method = RequestMethod.DELETE) public User deleteUser( @PathVariable Long user){ // ... } }
Spring MVC是核心Spring Framework的一部分,詳細信息可在參考文檔中找到。Spring.io/guides還提供了幾個涵蓋Spring MVC的指南。
Spring Boot爲Spring MVC提供自動配置,適用於大多數應用程序。
自動配置在Spring的默認值之上添加了如下功能:
ContentNegotiatingViewResolver
和BeanNameViewResolver
豆類。Converter
,GenericConverter
,Formatter
豆類。HttpMessageConverters
(見下文)。MessageCodesResolver
(見下文)。index.html
支持。Favicon
支持(見下文)。ConfigurableWebBindingInitializer
bean(見下文)。若是你想保留Spring Boot MVC功能,而且你只想添加額外的MVC配置(攔截器,格式化程序,視圖控制器等),你能夠添加本身的@Configuration
類類型WebMvcConfigurer
,但沒有 @EnableWebMvc
。若是您但願提供自定義實例RequestMappingHandlerMapping
,RequestMappingHandlerAdapter
或者ExceptionHandlerExceptionResolver
您能夠聲明WebMvcRegistrationsAdapter
提供此類組件的實例。
若是您想徹底控制Spring MVC,能夠添加本身的@Configuration
註釋@EnableWebMvc
。
Spring MVC使用該HttpMessageConverter
接口來轉換HTTP請求和響應。靈敏的默認值包含在開箱即用中,例如,對象能夠自動轉換爲JSON(使用Jackson庫)或XML(若是可用則使用Jackson XML擴展,不然使用JAXB)。字符串UTF-8
默認使用。
若是您須要添加或自定義轉換器,能夠使用Spring Boot的 HttpMessageConverters
類:
import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation。*; import org.springframework.http.converter。*; @Configuration 公共 類 MyConfiguration { @Bean public HttpMessageConverters customConverters(){ HttpMessageConverter<?> additional = ... HttpMessageConverter<?> another = ... return new HttpMessageConverters(additional, another); } }
Any HttpMessageConverter
bean that is present in the context will be added to the list of converters. You can also override default converters that way.
If you’re using Jackson to serialize and deserialize JSON data, you might want to write your own JsonSerializer
and JsonDeserializer
classes. Custom serializers are usually registered with Jackson via a Module, but Spring Boot provides an alternative @JsonComponent
annotation which makes it easier to directly register Spring Beans.
You can use @JsonComponent
directly on JsonSerializer
or JsonDeserializer
implementations. You can also use it on classes that contains serializers/deserializers as inner-classes. For example:
import java.io.*;
import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import org.springframework.boot.jackson.*; @JsonComponent public class Example { public static class Serializer extends JsonSerializer<SomeObject> { // ... } public static class Deserializer extends JsonDeserializer<SomeObject> { // ... } }
All @JsonComponent
beans in the ApplicationContext
will be automatically registered with Jackson, and since @JsonComponent
is meta-annotated with @Component
, the usual component-scanning rules apply.
Spring Boot also provides JsonObjectSerializer
and JsonObjectDeserializer
base classes which provide useful alternatives to the standard Jackson versions when serializing Objects. See the Javadoc for details.
Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: MessageCodesResolver
. Spring Boot will create one for you if you set the spring.mvc.message-codes-resolver.format
property PREFIX_ERROR_CODE
or POSTFIX_ERROR_CODE
(see the enumeration in DefaultMessageCodesResolver.Format
).
By default Spring Boot will serve static content from a directory called /static
(or /public
or /resources
or /META-INF/resources
) in the classpath or from the root of the ServletContext
. It uses the ResourceHttpRequestHandler
from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurer
and overriding the addResourceHandlers
method.
In a stand-alone web application the default servlet from the container is also enabled, and acts as a fallback, serving content from the root of the ServletContext
if Spring decides not to handle it. Most of the time this will not happen (unless you modify the default MVC configuration) because Spring will always be able to handle requests through the DispatcherServlet
.
By default, resources are mapped on /**
but you can tune that via spring.mvc.static-path-pattern
. For instance, relocating all resources to /resources/**
can be achieved as follows:
spring.mvc.static-path-pattern=/resources/**
You can also customize the static resource locations using spring.resources.static-locations
(replacing the default values with a list of directory locations). If you do this the default welcome page detection will switch to your custom locations, so if there is an index.html
in any of your locations on startup, it will be the home page of the application.
In addition to the ‘standard’ static resource locations above, a special case is made for Webjars content. Any resources with a path in /webjars/**
will be served from jar files if they are packaged in the Webjars format.
Do not use the |
Spring Boot also supports advanced resource handling features provided by Spring MVC, allowing use cases such as cache busting static resources or using version agnostic URLs for Webjars.
To use version agnostic URLs for Webjars, simply add the webjars-locator
dependency. Then declare your Webjar, taking jQuery for example, as "/webjars/jquery/dist/jquery.min.js"
which results in "/webjars/jquery/x.y.z/dist/jquery.min.js"
where x.y.z
is the Webjar version.
If you are using JBoss, you’ll need to declare the |
To use cache busting, the following configuration will configure a cache busting solution for all static resources, effectively adding a content hash in URLs, such as<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>
:
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
Links to resources are rewritten at runtime in template, thanks to a |
When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option. That’s why other strategies are also supported and can be combined. A "fixed" strategy will add a static version string in the URL, without changing the file name:
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/** spring.resources.chain.strategy.fixed.enabled=true spring.resources.chain.strategy.fixed.paths=/js/lib/ spring.resources.chain.strategy.fixed.version=v12
With this configuration, JavaScript modules located under "/js/lib/"
will use a fixed versioning strategy "/v12/js/lib/mymodule.js"
while other resources will still use the content one <link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>
.
有關ResourceProperties
更多支持的選項,請參閱。
Spring MVC使用a WebBindingInitializer
來初始化WebDataBinder
特定請求。若是您本身建立ConfigurableWebBindingInitializer
@Bean
,Spring Boot將自動配置Spring MVC以使用它。
除REST Web服務外,您還能夠使用Spring MVC來提供動態HTML內容。Spring MVC支持各類模板技術,包括Thymeleaf,FreeMarker和JSP。許多其餘模板引擎也提供本身的Spring MVC集成。
Spring Boot包括對如下模板引擎的自動配置支持:
若是可能,應該避免使用JSP,將它們與嵌入式servlet容器一塊兒使用時有幾個 已知的限制。 |
當您使用默認配置的其中一個模板引擎時,您的模板將自動從中獲取src/main/resources/templates
。
IntelliJ IDEA根據您運行應用程序的方式對類路徑進行不一樣的排序。經過主方法在IDE中運行應用程序將致使與使用Maven或Gradle或其打包的jar運行應用程序時的順序不一樣。這可能致使Spring Boot沒法在類路徑中找到模板。若是您受此問題的影響,能夠在IDE中從新排序類路徑,以便首先放置模塊的類和資源。或者,您能夠配置模板前綴以搜索類路徑上的每一個模板目錄: |
Spring Boot /error
默認提供映射,以合理的方式處理全部錯誤,並在servlet容器中註冊爲「全局」錯誤頁面。對於機器客戶端,它將生成一個JSON響應,其中包含錯誤,HTTP狀態和異常消息的詳細信息。對於瀏覽器客戶端,有一個「whitelabel」錯誤視圖,它以HTML格式呈現相同的數據(要自定義它,只需添加一個View
解析爲'錯誤'的數據)。要徹底替換默認行爲,您能夠實現 ErrorController
並註冊該類型的bean定義,或者只是添加類型的bean ErrorAttributes
以使用現有機制但替換內容。
在 |
您還能夠定義一個@ControllerAdvice
自定義JSON文檔以返回特定控制器和/或異常類型。
@ControllerAdvice(basePackageClasses = FooController.class) 公共 類 FooControllerAdvice擴展 ResponseEntityExceptionHandler { @ExceptionHandler(YourException.class) @ResponseBody ResponseEntity <?> handleControllerException(HttpServletRequest request,Throwable ex){ HttpStatus status = getStatus(request); 返回 新的 ResponseEntity <>(new CustomErrorType(status.value(),ex.getMessage()),status); } private HttpStatus getStatus(HttpServletRequest request){ 整數statusCode =(整數)request.getAttribute(「javax.servlet.error.status_code」); if(statusCode == null){ return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } }
在上面的示例中,若是YourException
由在同一個包中定義的控制器拋出,則將使用POJO FooController
的json表示CustomerErrorType
而不是ErrorAttributes
表示。
若是要爲給定的狀態代碼顯示自定義HTML錯誤頁面,請將文件添加到文件/error
夾。錯誤頁面能夠是靜態HTML(即添加到任何靜態資源文件夾下),也能夠使用模板構建。文件名應該是確切的狀態代碼或系列掩碼。
例如,要映射404
到靜態HTML文件,您的文件夾結構將以下所示:
SRC / + - 主要/ + - java / | + <源代碼> + - 資源/ + - 公共/ + - 錯誤/ | + - 404.html + - <其餘公共資產>
要5xx
使用FreeMarker模板映射全部錯誤,您將擁有以下結構:
SRC / + - 主要/ + - java / | + <源代碼> + - 資源/ + - 模板/ + - 錯誤/ | + - 5xx.ftl + - <其餘模板>
對於更復雜的映射,您還能夠添加實現該ErrorViewResolver
接口的bean 。
公共 類 MyErrorViewResolver 實現 ErrorViewResolver { @覆蓋 公共的ModelAndView resolveErrorView(HttpServletRequest的請求, HttpStatus狀態,Map <String,Object> model){ //使用請求或狀態可選擇返回ModelAndView 返回 ... } }
您還能夠使用常規的Spring MVC功能,如 @ExceptionHandler
方法和 @ControllerAdvice
。而後,ErrorController
將會發現任何未處理的異常。
對於不使用Spring MVC的應用程序,能夠使用該ErrorPageRegistrar
接口直接註冊ErrorPages
。這種抽象直接與底層嵌入式servlet容器一塊兒工做,即便你沒有Spring MVC也能工做 DispatcherServlet
。
@Bean public ErrorPageRegistrar errorPageRegistrar(){ return new MyErrorPageRegistrar(); } // ... 私有 靜態 類 MyErrorPageRegistrar 實現 ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry){ registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST,「/ 400」)); } }
注意若是你註冊的ErrorPage
路徑最終會被a處理 Filter
(例如,像一些非Spring網頁框架同樣常見,好比Jersey和Wicket),那麼Filter
必須明確註冊爲ERROR
調度程序,例如
@Bean public FilterRegistrationBean myFilter(){ FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new MyFilter()); ... registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); return registration; }
(the default FilterRegistrationBean
does not include the ERROR
dispatcher type).
When deployed to a servlet container, a Spring Boot uses its error page filter to forward a request with an error status to the appropriate error page. The request can only be forwarded to the correct error page if the response has not already been committed. By default, WebSphere Application Server 8.0 and later commits the response upon successful completion of a servlet’s service method. You should disable this behaviour by setting com.ibm.ws.webcontainer.invokeFlushAfterService
to false
若是您正在開發一個使用超媒體的RESTful API,Spring Boot爲Spring HATEOAS提供了自動配置,適用於大多數應用程序。自動配置取代了使用@EnableHypermediaSupport
和註冊多個bean 的須要,以便於構建基於超媒體的應用程序,包括 LinkDiscoverers
(用於客戶端支持)和ObjectMapper
配置爲正確地將響應編組到所需表示中。在ObjectMapper
將根據定製spring.jackson.*
的屬性或者Jackson2ObjectMapperBuilder
若是存在豆。
您能夠使用控制Spring HATEOAS的配置 @EnableHypermediaSupport
。請注意,這將禁用上述ObjectMapper
自定義。
跨源資源共享 (CORS)是大多數瀏覽器實現 的W3C規範,容許您以靈活的方式指定受權何種類型的跨域請求,而不是使用一些安全性較低且功能較弱的方法,如IFRAME或JSONP。
從版本4.2開始,Spring MVC 支持開箱即用的CORS。 在Spring Boot應用程序中使用帶有 註釋的控制器方法CORS配置@CrossOrigin
不須要任何特定配置。 能夠經過使用自定義 方法註冊bean 來定義全局CORS配置:WebMvcConfigurer
addCorsMappings(CorsRegistry)
@Configuration 公共 類 MyConfiguration { @Bean public WebMvcConfigurer corsConfigurer(){ return new WebMvcConfigurer(){ @ Override public void addCorsMappings(CorsRegistry registry){ registry.addMapping(「/ api / **」); } }; } }
Spring WebFlux是Spring Framework 5.0中引入的新的響應式Web框架。與Spring MVC不一樣,它不須要Servlet API,徹底異步且無阻塞,並 經過Reactor項目實現Reactive Streams規範。
Spring WebFlux有兩種版本 - 基於註釋的版本與咱們所知道的Spring MVC模型很是接近:
@RestController @RequestMapping(「/ users」) 公共 類 MyRestController { @GetMapping(「/ {user}」) public Mono <User> getUser( @PathVariable Long user){ // ... } @GetMapping(「/ {user} / customers」) Flux <Customer> getUserCustomers( @PathVariable Long user){ // ... } @DeleteMapping(「/ {user}」) public Mono <User> deleteUser( @PathVariable Long user){ // ... } }
'WebFlux.fn'是功能變體,它將路由配置與請求的實際處理分開:
@Configuration public class RoutingConfiguration { @Bean public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) { return route(GET("/{user}").and(accept(APPLICATION_JSON)), userHandler::getUser) .andRoute(GET("/{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers) .andRoute(DELETE("/{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser); } } @Component public class UserHandler { public Mono<ServerResponse> getUser(ServerRequest request) { // ... } public Mono<ServerResponse> getUserCustomers(ServerRequest request) { // ... } public Mono<ServerResponse> deleteUser(ServerRequest request) { // ... } }
WebFlux is part of the Spring Framework and detailed information is available in the reference documentation.
To get started, add the spring-boot-starter-webflux
module to your application.
Adding both |
Spring Boot provides auto-configuration for Spring WebFlux that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
HttpMessageReader
and HttpMessageWriter
instances (see below).If you want to keep Spring Boot WebFlux features, and you just want to add additional WebFlux configuration you can add your own @Configuration
class of type WebFluxConfigurer
, but without @EnableWebFlux
.
If you want to take complete control of Spring WebFlux, you can add your own @Configuration
annotated with @EnableWebFlux
.
Spring WebFlux uses the HttpMessageReader
and HttpMessageWriter
interface to convert HTTP requests and responses. They are configured with CodecConfigurer
with sensible defaults, by looking at the libraries available in your classpath.
Spring Boot will apply further customization using CodecCustomizer
instances. For example, spring.jackson.*
configuration keys will be applied to the Jackson codec.
若是須要添加或自定義編解碼器,能夠建立自定義CodecCustomizer
組件:
import org.springframework.boot.web.codec.CodecCustomizer;
@Configuration
公共 類 MyConfiguration { @Bean public CodecCustomizer myCodecCustomizer(){ return codecConfigurer - > { // ... } } }
您還能夠利用Boot的自定義JSON序列化程序和反序列化程序。
默認狀況下,Spring Boot將從類路徑中名爲/static
( /public
或/resources
或/META-INF/resources
)的目錄中提供靜態內容。它使用ResourceWebHandler
Spring WebFlux,所以您能夠經過添加本身WebFluxConfigurer
的addResourceHandlers
方法來修改該行爲並覆蓋該 方法。
默認狀況下,會映射資源,/**
但您能夠經過調整該 資源spring.mvc.static-path-pattern
。例如,從新定位全部資源/resources/**
能夠實現以下:
spring.mvc.static-path-pattern = / resources / **
您還能夠使用spring.resources.static-locations
(使用目錄位置列表替換默認值)自定義靜態資源位置 。若是您這樣作,默認的歡迎頁面檢測將切換到您的自定義位置,所以若是index.html
您在啓動時的任何位置,它將是應用程序的主頁。
除了上面的「標準」靜態資源位置以外,還爲Webjars內容製做了一個特例。具備路徑的全部資源/webjars/**
若是以Webjars格式打包,將從jar文件中提供。
Spring WebFlux應用程序並不嚴格依賴於Servlet API,所以不能將它們部署爲war而且不使用該 |
除REST Web服務外,您還能夠使用Spring WebFlux來提供動態HTML內容。Spring WebFlux支持各類模板技術,包括Thymeleaf,FreeMarker和Mustache。
Spring Boot包括對如下模板引擎的自動配置支持:
當您使用默認配置的其中一個模板引擎時,您的模板將自動從中獲取src/main/resources/templates
。
If you prefer the JAX-RS programming model for REST endpoints you can use one of the available implementations instead of Spring MVC. Jersey 1.x and Apache CXF work quite well out of the box if you just register their Servlet
or Filter
as a @Bean
in your application context. Jersey 2.x has some native Spring support so we also provide auto-configuration support for it in Spring Boot together with a starter.
To get started with Jersey 2.x just include the spring-boot-starter-jersey
as a dependency and then you need one @Bean
of type ResourceConfig
in which you register all the endpoints:
@Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(Endpoint.class); } }
Jersey’s support for scanning executable archives is rather limited. For example, it cannot scan for endpoints in a package found in |
You can also register an arbitrary number of beans implementing ResourceConfigCustomizer
for more advanced customizations.
All the registered endpoints should be @Components
with HTTP resource annotations (@GET
etc.), e.g.
@Component @Path("/hello") public class Endpoint { @GET public String message() { return "Hello"; } }
Since the Endpoint
is a Spring @Component
its lifecycle is managed by Spring and you can @Autowired
dependencies and inject external configuration with @Value
. The Jersey servlet will be registered and mapped to /*
by default. You can change the mapping by adding @ApplicationPath
to your ResourceConfig
.
By default Jersey will be set up as a Servlet in a @Bean
of type ServletRegistrationBean
named jerseyServletRegistration
. By default, the servlet will be initialized lazily but you can customize it with spring.jersey.servlet.load-on-startup
.You can disable or override that bean by creating one of your own with the same name. You can also use a Filter instead of a Servlet by setting spring.jersey.type=filter
(in which case the @Bean
to replace or override isjerseyFilterRegistration
). The servlet has an @Order
which you can set with spring.jersey.filter.order
. Both the Servlet and the Filter registrations can be given init parameters using spring.jersey.init.*
to specify a map of properties.
There is a Jersey sample so you can see how to set things up. There is also a Jersey 1.x sample. Note that in the Jersey 1.x sample that the spring-boot maven plugin has been configured to unpack some Jersey jars so they can be scanned by the JAX-RS implementation (because the sample asks for them to be scanned in its Filter
registration). You may need to do the same if any of your JAX-RS resources are packaged as nested jars.
Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. Most developers will simply use the appropriate ‘Starter’ to obtain a fully configured instance. By default the embedded server will listen for HTTP requests on port 8080
.
If you choose to use Tomcat on CentOS be aware that, by default, a temporary directory is used to store compiled JSPs, file uploads etc. This directory may be deleted by |
When using an embedded servlet container you can register Servlets, Filters and all the listeners from the Servlet spec (e.g. HttpSessionListener
) either by using Spring beans or by scanning for Servlet components.
Any Servlet
, Filter
or Servlet *Listener
instance that is a Spring bean will be registered with the embedded container. This can be particularly convenient if you want to refer to a value from your application.properties
during configuration.
By default, if the context contains only a single Servlet it will be mapped to /
. In the case of multiple Servlet beans the bean name will be used as a path prefix. Filters will map to /*
.
If convention-based mapping is not flexible enough you can use the ServletRegistrationBean
, FilterRegistrationBean
and ServletListenerRegistrationBean
classes for complete control.
Embedded servlet containers will not directly execute the Servlet 3.0+ javax.servlet.ServletContainerInitializer
interface, or Spring’sorg.springframework.web.WebApplicationInitializer
interface. This is an intentional design decision intended to reduce the risk that 3rd party libraries designed to run inside a war will break Spring Boot applications.
If you need to perform servlet context initialization in a Spring Boot application, you should register a bean that implements theorg.springframework.boot.web.servlet.ServletContextInitializer
interface. The single onStartup
method provides access to the ServletContext
, and can easily be used as an adapter to an existing WebApplicationInitializer
if necessary.
When using an embedded container, automatic registration of @WebServlet
, @WebFilter
, and @WebListener
annotated classes can be enabled using @ServletComponentScan
.
|
Under the hood Spring Boot uses a new type of ApplicationContext
for embedded servlet container support. The ServletWebServerApplicationContext
is a special type of WebApplicationContext
that bootstraps itself by searching for a single ServletWebServerFactory
bean. Usually a TomcatServletWebServerFactory
, JettyServletWebServerFactory
, or UndertowServletWebServerFactory
will have been auto-configured.
You usually won’t need to be aware of these implementation classes. Most applications will be auto-configured and the appropriate |
Common servlet container settings can be configured using Spring Environment
properties. Usually you would define the properties in your application.properties
file.
Common server settings include:
server.port
), interface address to bind to server.address
, etc.server.session.persistence
), session timeout (server.session.timeout
), location of session data (server.session.store-dir
) and session-cookie configuration (server.session.cookie.*
).server.error.path
), etc.Spring Boot tries as much as possible to expose common settings but this is not always possible. For those cases, dedicated namespaces offer server-specific customizations (see server.tomcat
and server.undertow
). For instance, access logs can be configured with specific features of the embedded servlet container.
See the |
If you need to configure your embedded servlet container programmatically you can register a Spring bean that implements the WebServerFactoryCustomizer
interface. WebServerFactoryCustomizer
provides access to the ConfigurableServletWebServerFactory
which includes numerous customization setter methods. Dedicated variants exists for Tomcat, Jetty and Undertow.
import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.stereotype.Component; @Component 公共 類 CustomizationBean實現 WebServerFactoryCustomizer <ConfigurableServletWebServerFactory> { @Override public void customize(ConfigurableServletWebServerFactory server){ server.setPort(9000); } }
若是上面的自定義方法太有限,你能夠註冊 TomcatServletWebServerFactory
,JettyServletWebServerFactory
或 UndertowServletWebServerFactory
豆你本身。
@Bean public ConfigurableServletWebServerFactory webServerFactory(){ TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); factory.setPort(9000); factory.setSessionTimeout(10,TimeUnit.MINUTES); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,「/ notfound.html」)); 返回工廠; }
爲許多配置選項提供了Setter。若是您須要作一些更具異國情調的事情,還會提供幾種受保護的方法「掛鉤」。有關詳細信息,請參閱源代碼文檔。
若是Spring Security位於類路徑上,則默認狀況下Web應用程序將在全部HTTP端點上使用「基本」身份驗證。要向Web應用程序添加方法級安全性,您還能夠@EnableGlobalMethodSecurity
使用所需的設置進行添加。其餘信息能夠在Spring Security Reference中找到。
默認設置AuthenticationManager
只有一個用戶('用戶'用戶名和隨機密碼,在應用程序啓動時以INFO級別打印)
使用默認安全密碼:78fa095d-3f4c-48b1-ad50-e24c31d5cf35
若是您對日誌記錄配置進行微調,請確保將 |
您能夠經過提供一個來更改密碼security.user.password
。此屬性和其餘有用屬性經過SecurityProperties
(屬性前綴「security」)外部化 。
默認安全配置在SecurityAutoConfiguration
從那裏導入的類中實現(SpringBootWebSecurityConfiguration
對於Web安全性和AuthenticationManagerConfiguration
用於非Web應用程序中相關的身份驗證配置)。要徹底關閉默認Web應用程序安全配置,您能夠添加一個bean @EnableWebSecurity
(這不會禁用身份驗證管理器配置或Actuator的安全性)。要自定義它,一般使用外部屬性和類型的bean WebSecurityConfigurerAdapter
(例如,添加基於表單的登陸)。
若是添加 |
要關閉身份驗證管理器配置,您能夠添加類型的bean AuthenticationManager
,或者AuthenticationManager
經過自動裝配AuthenticationManagerBuilder
到其中一個@Configuration
類中的方法來配置全局。Spring Boot示例中有幾個安全的應用程序能夠幫助您開始使用常見的用例。
您在Web應用程序中開箱即用的基本功能包括:
AuthenticationManager
具備內存存儲和單個用戶的bean(請參閱用戶 SecurityProperties.User
的屬性)。/css/**
,/js/**
, /images/**
,/webjars/**
和**/favicon.ico
)。ApplicationEventPublisher
(成功和不成功的身份驗證和訪問被拒絕)。以上全部內容均可以使用外部屬性(security.*
)打開或關閉或修改。要覆蓋訪問規則不改變任何其它的自動配置功能添加@Bean
型WebSecurityConfigurerAdapter
與 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
並對其進行配置,以知足您的需求。
默認狀況下,a |
若是您具備spring-security-oauth2
類路徑,則能夠利用某些自動配置來輕鬆設置受權或資源服務器。有關完整詳細信息,請參閱「 Spring Security OAuth 2開發人員指南」。
要建立受權服務器並授予訪問令牌,您須要使用 @EnableAuthorizationServer
和提供security.oauth2.client.client-id
和security.oauth2.client.client-secret]
屬性。客戶端將在內存存儲庫中爲您註冊。
完成後,您將可以使用客戶端憑據建立訪問令牌,例如:
$ curl client:secret @ localhost :8080 / oauth / token -d grant_type = password -d username = user -d password = pwd
/token
端點的基自己份驗證憑據是client-id
和 client-secret
。用戶憑據是正常的Spring Security用戶詳細信息(在Spring Boot中默認爲「user」和隨機密碼)。
要關閉自動配置並自行配置受權服務器功能,只需添加一種@Bean
類型AuthorizationServerConfigurer
。
To use the access token you need a Resource Server (which can be the same as the Authorization Server). Creating a Resource Server is easy, just add@EnableResourceServer
and provide some configuration to allow the server to decode access tokens. If your application is also an Authorization Server it already knows how to decode tokens, so there is nothing else to do. If your app is a standalone service then you need to give it some more configuration, one of the following options:
security.oauth2.resource.user-info-uri
to use the /me
resource (e.g. https://uaa.run.pivotal.io/userinfo
on PWS)security.oauth2.resource.token-info-uri
to use the token decoding endpoint (e.g. https://uaa.run.pivotal.io/check_token
on PWS).If you specify both the user-info-uri
and the token-info-uri
then you can set a flag to say that one is preferred over the other (prefer-token-info=true
is the default).
Alternatively (instead of user-info-uri
or token-info-uri
) if the tokens are JWTs you can configure a security.oauth2.resource.jwt.key-value
to decode them locally (where the key is a verification key). The verification key value is either a symmetric secret or PEM-encoded RSA public key. If you don’t have the key and it’s public you can provide a URI where it can be downloaded (as a JSON object with a 「value」 field) with security.oauth2.resource.jwt.key-uri
. E.g. on PWS:
$ curl https://uaa.run.pivotal.io/token_key {"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"}
If you use the |
OAuth2 resources are protected by a filter chain with order security.oauth2.resource.filter-order
and the default is after the filter protecting the actuator endpoints by default (so actuator endpoints will stay on HTTP Basic unless you change the order).
Google, and certain other 3rd party identity providers, are more strict about the token type name that is sent in the headers to the user info endpoint. The default is 「Bearer」 which suits most providers and matches the spec, but if you need to change it you can set security.oauth2.resource.token-type
.
If you have a user-info-uri
, the resource server features use an OAuth2RestTemplate
internally to fetch user details for authentication. This is provided as a @Bean
of type UserInfoRestTemplateFactory
. The default should be fine for most providers, but occasionally you might need to add additional interceptors, or change the request authenticator (which is how the token gets attached to outgoing requests). To add a customization just create a bean of type UserInfoRestTemplateCustomizer
- it has a single method that will be called after the bean is created but before it is initialized. The rest template that is being customized here is only used internally to carry out authentication. Alternatively, you could define your own UserInfoRestTemplateFactory
@Bean
to take full control.
To set an RSA key value in YAML use the 「pipe」 continuation marker to split it over multiple lines (「|」) and remember to indent the key value (it’s a standard YAML language feature). Example: security:
oauth2: resource: jwt: keyValue: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC... -----END PUBLIC KEY----- |
To make your web-app into an OAuth2 client you can simply add @EnableOAuth2Client
and Spring Boot will create a OAuth2ClientContext
and OAuth2ProtectedResourceDetails
that are necessary to create an OAuth2RestOperations
. Spring Boot does not automatically create such bean but you can easily create your own:
@Bean public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) { return new OAuth2RestTemplate(details, oauth2ClientContext); }
You may want to add a qualifier and review your configuration as more than one |
This configuration uses security.oauth2.client.*
as credentials (the same as you might be using in the Authorization Server), but in addition it will need to know the authorization and token URIs in the Authorization Server. For example:
application.yml.
security:
oauth2: client: clientId: bd1c0a783ccdd1c9b9e4 clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1 accessTokenUri: https://github.com/login/oauth/access_token userAuthorizationUri: https://github.com/login/oauth/authorize clientAuthenticationScheme: form
An application with this configuration will redirect to Github for authorization when you attempt to use the OAuth2RestTemplate
. If you are already signed into Github you won’t even notice that it has authenticated. These specific credentials will only work if your application is running on port 8080 (register your own client app in Github or other provider for more flexibility).
To limit the scope that the client asks for when it obtains an access token you can set security.oauth2.client.scope
(comma separated or an array in YAML). By default the scope is empty and it is up to Authorization Server to decide what the defaults should be, usually depending on the settings in the client registration that it holds.
There is also a setting for |
In a non-web application you can still create an |
An OAuth2 Client can be used to fetch user details from the provider (if such features are available) and then convert them into an Authentication
token for Spring Security. The Resource Server above support this via the user-info-uri
property This is the basis for a Single Sign On (SSO) protocol based on OAuth2, and Spring Boot makes it easy to participate by providing an annotation @EnableOAuth2Sso
. The Github client above can protect all its resources and authenticate using the Github /user/
endpoint, by adding that annotation and declaring where to find the endpoint (in addition to the security.oauth2.client.*
configuration already listed above):
application.yml.
security:
oauth2: ... resource: userInfoUri: https://api.github.com/user preferTokenInfo: false
Since all paths are secure by default, there is no 「home」 page that you can show to unauthenticated users and invite them to login (by visiting the /login
path, or the path specified by security.oauth2.sso.login-path
).
To customize the access rules or paths to protect, so you can add a 「home」 page for instance, @EnableOAuth2Sso
can be added to a WebSecurityConfigurerAdapter
and the annotation will cause it to be decorated and enhanced with the necessary pieces to get the /login
path working. For example, here we simply allow unauthenticated access to the home page at "/" and keep the default for everything else:
@Configuration static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override public void init(WebSecurity web) { web.ignoring().antMatchers("/"); } @Override protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/**").authorizeRequests().anyRequest().authenticated(); } }
If the Actuator is also in use, you will find:
AuditEvent
instances and published to the AuditEventRepository
.ACTUATOR
role as well as the USER
role.The Actuator security features can be modified using external properties (management.security.*
). To override the application access rules add a @Bean
of type WebSecurityConfigurerAdapter
and use @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
if you don’t want to override the actuator access rules, or @Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
if you do want to override the actuator access rules.
The Spring Framework provides extensive support for working with SQL databases. From direct JDBC access using JdbcTemplate
to complete ‘object relational mapping’ technologies such as Hibernate. Spring Data provides an additional level of functionality, creating Repository
implementations directly from interfaces and using conventions to generate queries from your method names.
Java’s javax.sql.DataSource
interface provides a standard method of working with database connections. Traditionally a DataSource uses a URL
along with some credentials to establish a database connection.
Check also the ‘How-to’ section for more advanced examples, typically to take full control over the configuration of the DataSource. |
It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.
The ‘How-to’ section includes a section on how to initialize a database |
Spring Boot can auto-configure embedded H2, HSQL and Derby databases. You don’t need to provide any connection URLs, simply include a build dependency to the embedded database that you want to use.
If you are using this feature in your tests, you may notice that the same database is reused by your whole test suite regardless of the number of application contexts that you use. If you want to make sure that each context has a separate embedded database, you should set |
For example, typical POM dependencies would be:
<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <scope>runtime</scope> </dependency>
You need a dependency on |
If, for whatever reason, you do configure the connection URL for an embedded database, care should be taken to ensure that the database’s automatic shutdown is disabled. If you’re using H2 you should use |
Production database connections can also be auto-configured using a pooling DataSource
. Here’s the algorithm for choosing a specific implementation:
DataSource
is available we will use it.If you use the spring-boot-starter-jdbc
or spring-boot-starter-data-jpa
‘starters’ you will automatically get a dependency to HikariCP
.
You can bypass that algorithm completely and specify the connection pool to use via the |
Additional connection pools can always be configured manually. If you define your own |
DataSource configuration is controlled by external configuration properties in spring.datasource.*
. For example, you might declare the following section inapplication.properties
:
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver
You should at least specify the url using the |
You often won’t need to specify the |
For a pooling |
See DataSourceProperties
for more of the supported options. These are the standard options that work regardless of the actual implementation. It is also possible to fine-tune implementation-specific settings using their respective prefix (spring.datasource.hikari.*
, spring.datasource.tomcat.*
, and spring.datasource.dbcp2.*
). Refer to the documentation of the connection pool implementation you are using for more details.
For instance, if you are using the Tomcat connection pool you could customize many additional settings:
#若是沒有可用鏈接,則在拋出異常以前要等待的ms數。
spring.datasource.tomcat.max-wait = 10000 #能夠同時從該池分配的最大活動鏈接數。 spring.datasource.tomcat.max-active = 50 #在從池中借用鏈接以前驗證鏈接。 spring.datasource.tomcat.test-on-borrow = true
若是要將Spring Boot應用程序部署到Application Server,則可能須要使用Application Server內置功能配置和管理DataSource,並使用JNDI訪問它。
該spring.datasource.jndi-name
屬性能夠被用做一個替代 spring.datasource.url
,spring.datasource.username
和spring.datasource.password
屬性來訪問DataSource
從一個特定的JNDI位置。例如,如下部分application.properties
顯示瞭如何訪問定義的JBoss AS DataSource
:
spring.datasource.jndi-name = java:jboss / datasources / customers
Spring JdbcTemplate
和NamedParameterJdbcTemplate
類是自動配置的,你能夠將@Autowire
它們直接放到你本身的bean中:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component 公共 類 MyBean { private final JdbcTemplate jdbcTemplate; @Autowired public MyBean(JdbcTemplate jdbcTemplate){ this .jdbcTemplate = jdbcTemplate; } // ... }
您能夠使用如下spring.jdbc.template.*
屬性自定義模板的某些屬性:
spring.jdbc.template.max-rows = 500
在 |
Java Persistence API是一種標準技術,容許您將對象「映射」到關係數據庫。該spring-boot-starter-data-jpa
POM提供了上手的快捷方式。它提供如下關鍵依賴項:
咱們不會在這裏討論太多關於JPA或Spring Data的細節。您能夠按照 「使用JPA訪問數據」從引導 spring.io並宣讀了春天的數據JPA 和Hibernate的參考文檔。 |
傳統上,JPA「實體」類在persistence.xml
文件中指定。使用Spring Boot,此文件不是必需的,而是使用「實體掃描」。默認狀況下,將搜索主配置類下面的全部包(用@EnableAutoConfiguration
or 註釋 @SpringBootApplication
)。
任何類註釋用@Entity
,@Embeddable
或@MappedSuperclass
將予以考慮。典型的實體類看起來像這樣:
package com.example.myapp.domain;
import java.io.Serializable; import javax.persistence。*; @Entity 公共 類 City實現 Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) 私有 String名稱; @Column(nullable = false) 私有 String狀態; // ...其餘成員,一般包括@OneToMany映射 protected City(){ // JPA規範要求的no-args構造函數 //這個是受保護的,由於它不該該直接使用 } public City(String name,String state){ this .name = name; 這個 .country = country; } public String getName(){ return this .name; } public String getState(){ return this .state; } //等等 }
您能夠使用 |
Spring Data JPA存儲庫是您能夠定義以訪問數據的接口。JPA查詢是從您的方法名稱自動建立的。例如,CityRepository
接口可能會聲明一種findAllByState(String state)
方法來查找給定狀態中的全部城市。
對於更復雜的查詢,您能夠使用Spring Data的Query
註釋來註釋您的方法 。
Spring Data存儲庫一般從Repository
或 CrudRepository
接口擴展 。若是您使用的是自動配置,則將從包含主配置類(帶有@EnableAutoConfiguration
或標註的類)的軟件包中搜索存儲庫 @SpringBootApplication
。
這是一個典型的Spring Data存儲庫:
package com.example.myapp.domain;
import org.springframework.data.domain。*; import org.springframework.data.repository。*; 公共 接口 CityRepository 擴展了 Repository <City,Long> { Page <City> findAll(可分頁可分頁); City findByNameAndCountryAllIgnoringCase(String name,String country); }
咱們幾乎沒有涉及Spring Data JPA的表面。有關詳細信息,請查看其參考文檔。 |
默認狀況下,僅當您使用嵌入式數據庫(H2,HSQL或Derby)時,纔會自動建立JPA數據庫。您能夠使用spring.jpa.*
屬性顯式配置JPA設置 。例如,要建立和刪除表,您能夠將如下內容添加到您的表中application.properties
。
spring.jpa.hibernate.ddl-AUTO =創造降
Hibernate本身的內部屬性名稱(若是你碰巧記得更好)是 |
spring.jpa.properties.hibernate.globally_quoted_identifiers =真
傳遞hibernate.globally_quoted_identifiers
給Hibernate實體管理器。
默認狀況下,DDL執行(或驗證)將延遲到ApplicationContext
啓動。還有一個spring.jpa.generate-ddl
標誌,但若是Hibernate autoconfig處於活動狀態,則不會使用該標誌,由於ddl-auto
設置更精細。
若是您正在運行Web應用程序,Spring Boot將默認註冊 OpenEntityManagerInViewInterceptor
以應用「在視圖中打開EntityManager」模式,即容許在Web視圖中進行延遲加載。若是你不但願這種行爲,你應該設置spring.jpa.open-in-view
到 false
你application.properties
。
該H2數據庫提供了一個 基於瀏覽器的控制檯是春天開機便可自動爲您配置。知足如下條件時,將自動配置控制檯:
com.h2database:h2
在類路徑上 若是您沒有使用Spring Boot的開發人員工具,但仍想使用H2的控制檯,那麼您能夠經過配置 |
Java面向對象查詢(jOOQ)是Data Geekery的一個流行產品, 它從您的數據庫生成Java代碼,並容許您經過其流暢的API構建類型安全的SQL查詢。商業版和開源版均可以與Spring Boot一塊兒使用。
In order to use jOOQ type-safe queries, you need to generate Java classes from your database schema. You can follow the instructions in the jOOQ user manual. If you are using the jooq-codegen-maven
plugin (and you also use the spring-boot-starter-parent
「parent POM」) you can safely omit the plugin’s <version>
tag. You can also use Spring Boot defined version variables (e.g. h2.version
) to declare the plugin’s database dependency. Here’s an example:
<plugin>
<groupId>org.jooq</groupId> <artifactId>jooq-codegen-maven</artifactId> <executions> ... </executions> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>${h2.version}</version> </dependency> </dependencies> <configuration> <jdbc> <driver>org.h2.Driver</driver> <url>jdbc:h2:~/yourdatabase</url> </jdbc> <generator> ... </generator> </configuration> </plugin>
The fluent API offered by jOOQ is initiated via the org.jooq.DSLContext
interface. Spring Boot will auto-configure a DSLContext
as a Spring Bean and connect it to your application DataSource
. To use the DSLContext
you can just @Autowire
it:
@Component public class JooqExample implements CommandLineRunner { private final DSLContext create; @Autowired public JooqExample(DSLContext dslContext) { this.create = dslContext; } }
The jOOQ manual tends to use a variable named |
You can then use the DSLContext
to construct your queries:
public List<GregorianCalendar> authorsBornAfter1980() {
return this.create.selectFrom(AUTHOR) .where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1))) .fetch(AUTHOR.DATE_OF_BIRTH); }
Spring Boot determines the SQL dialect to use for your datasource unless the spring.jooq.sql-dialect
property has been configured. If the dialect couldn’t be detected, DEFAULT
is used.
Spring Boot can only auto-configure dialects supported by the open source version of jOOQ. |
More advanced customizations can be achieved by defining your own @Bean
definitions which will be used when the jOOQ Configuration
is created. You can define beans for the following jOOQ Types:
ConnectionProvider
TransactionProvider
RecordMapperProvider
RecordListenerProvider
ExecuteListenerProvider
VisitListenerProvider
You can also create your own org.jooq.Configuration
@Bean
if you want to take complete control of the jOOQ configuration.
Spring Data provides additional projects that help you access a variety of NoSQL technologies including MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire,Cassandra, Couchbase and LDAP. Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr Cassandra, Couchbase and LDAP; you can make use of the other projects, but you will need to configure them yourself. Refer to the appropriate reference documentation at projects.spring.io/spring-data.
Redis is a cache, message broker and richly-featured key-value store. Spring Boot offers basic auto-configuration for the Jedis and Lettuce client library and abstractions on top of it provided by Spring Data Redis.
There is a spring-boot-starter-data-redis
‘Starter’ for collecting the dependencies in a convenient way that uses Jedis by default. If you are building a reactive application, the spring-boot-starter-data-redis-reactive
‘Starter’ will get you going.
You can inject an auto-configured RedisConnectionFactory
, StringRedisTemplate
or vanilla RedisTemplate
instance as you would any other Spring Bean. By default the instance will attempt to connect to a Redis server using localhost:6379
:
@Component public class MyBean { 私有 StringRedisTemplate模板; @Autowired public MyBean(StringRedisTemplate template){ this .template = template; } // ... }
您還能夠註冊任意數量的bean,以實現 |
若是您添加@Bean
本身的任何自動配置類型,它將替換默認值(除非RedisTemplate
排除是基於bean名稱'redisTemplate'而不是其類型)。若是commons-pool2
在類路徑上,默認狀況下您將得到池鏈接工廠。
MongoDB是一個開源的NoSQL文檔數據庫,它使用相似JSON的模式而不是傳統的基於表的關係數據。Spring Boot提供了一些使用MongoDB的便利,包括spring-boot-starter-data-mongodb
和spring-boot-starter-data-mongodb-reactive
'Starters'。
您能夠注入自動配置org.springframework.data.mongodb.MongoDbFactory
以訪問Mongo數據庫。默認狀況下,實例將嘗試使用URL鏈接到MongoDB服務器mongodb://localhost/test
:
import org.springframework.data.mongodb.MongoDbFactory; import com.mongodb.DB; @Component 公共 類 MyBean { 私人 決賽 MongoDbFactory mongo; @Autowired public MyBean(MongoDbFactory mongo){ this .mongo = mongo; } // ... public void example(){ DB db = mongo.getDb(); // ... } }
您能夠設置spring.data.mongodb.uri
屬性以更改URL並配置其餘設置,例如副本集:
spring.data.mongodb.uri = mongodb:// user:secret@mongo1.example.com :12345,mongo2.example.com:23456 / test
或者,只要您使用Mongo 2.x,請指定host
/ port
。例如,您能夠在如下內容中聲明如下內容application.properties
:
spring.data.mongodb.host = mongoserver spring.data.mongodb.port = 27017
|
若是 |
若是您不使用Spring Data Mongo,則能夠注入 |
若是要徹底控制創建MongoDB鏈接,也能夠聲明本身的bean MongoDbFactory
或Mongo
bean。
Spring Data Mongo提供了一個MongoTemplate
與Spring的設計很是類似的 類JdbcTemplate
。與JdbcTemplate
Spring Boot同樣,自動配置一個bean,只需注入:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; @Component 公共 類 MyBean { 私人 決賽 MongoTemplate mongoTemplate; @Autowired public MyBean(MongoTemplate mongoTemplate){ this .mongoTemplate = mongoTemplate; } // ... }
有關MongoOperations
完整的詳細信息,請參閱Javadoc。
Spring Data包括MongoDB的存儲庫支持。與前面討論的JPA存儲庫同樣,基本原則是根據方法名稱自動爲您構建查詢。
事實上,Spring Data JPA和Spring Data MongoDB共享相同的通用基礎架構; 因此你能夠從前面拿到JPA示例,假設它City
如今是一個Mongo數據類而不是JPA @Entity
,它將以相同的方式工做。
package com.example.myapp.domain;
import org.springframework.data.domain。*; import org.springframework.data.repository。*; 公共 接口 CityRepository 擴展了 Repository <City,Long> { Page <City> findAll(可分頁可分頁); City findByNameAndCountryAllIgnoringCase(String name,String country); }
有關Spring Data MongoDB的完整詳細信息,包括其豐富的對象映射技術,請參閱其參考文檔。 |
Spring Boot爲Embedded Mongo提供自動配置 。要在Spring Boot應用程序中使用它,請添加依賴項 de.flapdoodle.embed:de.flapdoodle.embed.mongo
。
能夠使用該spring.data.mongodb.port
屬性配置Mongo將偵聽的端口。要使用隨機分配的空閒端口,請使用零值。在MongoClient
由建立MongoAutoConfiguration
將被自動配置爲使用隨機分配的端口。
若是您不配置自定義端口,則默認狀況下嵌入式支持將使用隨機端口(而不是27017)。 |
若是類路徑上有SLF4J,Mongo生成的輸出將自動路由到名爲的記錄器org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo
。
您能夠聲明本身的bean IMongodConfig
和IRuntimeConfig
bean來控制Mongo實例的配置和日誌記錄路由。
Neo4j是一個開源的NoSQL圖形數據庫,它使用與第一類關係相關的節點的豐富數據模型,與傳統的rdbms方法相比,它更適合於鏈接的大數據。Spring Boot爲使用Neo4j提供了一些便利,包括spring-boot-starter-data-neo4j
「Starter」。
你能夠注入的自動配置Neo4jSession
,Session
或者Neo4jOperations
,就像任何其餘的Spring Bean實例。默認狀況下,實例將嘗試使用如下命令鏈接到Neo4j服務器localhost:7474
:
@Component 公共 類 MyBean { private final Neo4jTemplate neo4jTemplate; @Autowired public MyBean(Neo4jTemplate neo4jTemplate) { this.neo4jTemplate = neo4jTemplate; } // ... }
You can take full control of the configuration by adding a org.neo4j.ogm.config.Configuration
@Bean
of your own. Also, adding a @Bean
of typeNeo4jOperations
disables the auto-configuration.
You can configure the user and credentials to use via the spring.data.neo4j.*
properties:
spring.data.neo4j.uri=http://my-server:7474
spring.data.neo4j.username=neo4j spring.data.neo4j.password=secret
若是添加org.neo4j:neo4j-ogm-embedded-driver
到應用程序的依賴項,Spring Boot將自動配置Neo4j的進程內嵌入式實例,在應用程序關閉時不會保留任何數據。您能夠使用顯式禁用該模式spring.data.neo4j.embedded.enabled=false
。您還能夠爲嵌入模式啓用持久性:
spring.data.neo4j.uri =文件://var/tmp/graph.db
Neo4j OGM嵌入式驅動程序不提供Neo4j內核。用戶須要手動提供此依賴關係, 有關詳細信息,請參閱 文檔。 |
默認狀況下,若是您正在運行Web應用程序,則會話將綁定到線程以進行整個請求處理(即「在視圖中打開會話」模式)。若是您不想要此行爲,請將如下內容添加到您的application.properties
:
spring.data.neo4j.open式視=假
Spring Data包含對Neo4j的存儲庫支持。
事實上,Spring Data JPA和Spring Data Neo4j共享相同的通用基礎架構; 因此你能夠從前面拿到JPA例子,假設City
如今是Neo4j OGM @NodeEntity
而不是JPA @Entity
,它將以相同的方式工做。
您能夠使用 |
要啓用存儲庫支持(以及可選的支持@Transactional
),請在Spring配置中添加如下兩個註釋:
@ EnableNeo4jRepositories(basePackages =「com.example.myapp.repository」) @EnableTransactionManagement
package com.example.myapp.domain;
import org.springframework.data.domain。*; import org.springframework.data.repository。*; 公共 接口 CityRepository 擴展了 GraphRepository <City> { Page <City> findAll(可分頁可分頁); City findByNameAndCountry(String name,String country); }
有關Spring Data Neo4j的完整詳細信息,包括其豐富的對象映射技術,請參閱其參考文檔。 |
Spring Data Gemfire提供了方便的Spring友好工具,用於訪問 Pivotal Gemfire數據管理平臺。有一個spring-boot-starter-data-gemfire
'Starter'用於以方便的方式收集依賴項。目前沒有對Gemfire的自動配置支持,但您能夠使用單個註釋(@EnableGemfireRepositories
)啓用Spring Data Repositories 。
Apache Solr是一個搜索引擎。Spring Boot爲Solr 5客戶端庫提供基本的自動配置,並在Spring Data Solr提供的基礎上提供抽象 。有一個spring-boot-starter-data-solr
'Starter'用於以方便的方式收集依賴項。
You can inject an auto-configured SolrClient
instance as you would any other Spring bean. By default the instance will attempt to connect to a server usinglocalhost:8983/solr
:
@Component public class MyBean { private SolrClient solr; @Autowired public MyBean(SolrClient solr) { this.solr = solr; } // ... }
If you add a @Bean
of your own of type SolrClient
it will replace the default.
Spring Data includes repository support for Apache Solr. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.
In fact, both Spring Data JPA and Spring Data Solr share the same common infrastructure; so you could take the JPA example from earlier and, assuming that City
is now a @SolrDocument
class rather than a JPA @Entity
, it will work in the same way.
For complete details of Spring Data Solr, refer to their reference documentation. |
Elasticsearch is an open source, distributed, real-time search and analytics engine. Spring Boot offers basic auto-configuration for the Elasticsearch and abstractions on top of it provided by Spring Data Elasticsearch. There is a spring-boot-starter-data-elasticsearch
‘Starter’ for collecting the dependencies in a convenient way. Spring Boot also supports Jest.
If you have Jest
on the classpath, you can inject an auto-configured JestClient
targeting localhost:9200
by default. You can further tune how the client is configured:
spring.elasticsearch.jest.uris=http://search.example.com:9200
spring.elasticsearch.jest.read-timeout=10000 spring.elasticsearch.jest.username=user spring.elasticsearch.jest.password=secret
You can also register an arbitrary number of beans implementing HttpClientConfigBuilderCustomizer
for more advanced customizations. The example below tunes additional HTTP settings:
static class HttpSettingsCustomizer implements HttpClientConfigBuilderCustomizer { @Override public void customize(HttpClientConfig.Builder builder) { builder.maxTotalConnection(100).defaultMaxTotalConnectionPerRoute(5); } }
To take full control over the registration, define a JestClient
bean.
To connect to Elasticsearch you must provide the address of one or more cluster nodes. The address can be specified by setting the spring.data.elasticsearch.cluster-nodes
property to a comma-separated ‘host:port’ list. With this configuration in place, an ElasticsearchTemplate
or TransportClient
can be injected like any other Spring bean:
spring.data.elasticsearch.cluster-nodes=localhost:9300
@Component public class MyBean { private final ElasticsearchTemplate template; public MyBean(ElasticsearchTemplate template) { this.template = template; } // ... }
If you add your own ElasticsearchTemplate
or TransportClient
@Bean
it will replace the default.
Spring Data includes repository support for Elasticsearch. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.
In fact, both Spring Data JPA and Spring Data Elasticsearch share the same common infrastructure; so you could take the JPA example from earlier and, assuming thatCity
is now an Elasticsearch @Document
class rather than a JPA @Entity
, it will work in the same way.
有關Spring Data Elasticsearch的完整詳細信息,請參閱其 參考文檔。 |
Cassandra是一個開源的分佈式數據庫管理系統,旨在處理許多商用服務器上的大量數據。Spring Boot提供了由Spring Data Cassandra提供的Cassandra和抽象的自動配置 。有一個spring-boot-starter-data-cassandra
'Starter'用於以方便的方式收集依賴項。
您能夠 像使用任何其餘Spring Bean同樣注入自動配置CassandraTemplate
或Cassandra Session
實例。這些spring.data.cassandra.*
屬性可用於自定義鏈接。通常來講,您將提供 keyspace-name
和contact-points
屬性:
spring.data.cassandra.keyspace-name = mykeyspace spring.data.cassandra.contact-points = cassandrahost1,cassandrahost2
@Component 公共 類 MyBean { 私人 CassandraTemplate模板; @Autowired public MyBean(CassandraTemplate模板){ this .template = template; } // ... }
若是您添加@Bean
本身的類型CassandraTemplate
,它將替換默認值。
Spring Data包含對Cassandra的基本存儲庫支持。目前,這比前面討論的JPA存儲庫更有限,而且須要使用註釋方法註釋@Query
。
有關Spring Data Cassandra的完整詳細信息,請參閱其 參考文檔。 |
Couchbase是一個開源的,分佈式的多模型NoSQL面向文檔的數據庫,針對交互式應用程序進行了優化。Spring Boot提供了由Spring Data Couchbase提供的Couchbase和抽象的自動配置 。有一個spring-boot-starter-data-couchbase
'Starter'用於以方便的方式收集依賴項。
您能夠很是輕鬆地得到Bucket
並Cluster
添加Couchbase SDK和一些配置。這些spring.couchbase.*
屬性可用於自定義鏈接。一般,您將提供引導主機,存儲桶名稱和密碼:
spring.couchbase.bootstrap-hosts=my-host-1,192.168.1.123
spring.couchbase.bucket.name=my-bucket spring.couchbase.bucket.password=secret
You need to provide at least the bootstrap host(s), in which case the bucket name is |
It is also possible to customize some of the CouchbaseEnvironment
settings. For instance the following configuration changes the timeout to use to open a new Bucket
and enables SSL support:
spring.couchbase.env.timeouts.connect = 3000 spring.couchbase.env.ssl.key-store = / location / of / keystore.jks spring.couchbase.env.ssl.key-store-password = secret
檢查spring.couchbase.env.*
屬性以獲取更多詳細信息。
Spring Data包括對Couchbase的存儲庫支持。有關Spring Data Couchbase的完整詳細信息,請參閱其 參考文檔。
您能夠CouchbaseTemplate
像使用任何其餘Spring Bean同樣注入自動配置的實例,只要默認 CouchbaseConfigurer
值可用(當您啓用如上所述的couchbase支持時就會發生這種狀況)。
@Component 公共 類 MyBean { 私人 決賽 CouchbaseTemplate模板; @Autowired public MyBean(CouchbaseTemplate template){ this .template = template; } // ... }
您能夠在本身的配置中定義一些bean來覆蓋自動配置提供的bean:
CouchbaseTemplate
@Bean
名字couchbaseTemplate
IndexManager
@Bean
名字couchbaseIndexManager
CustomConversions
@Bean
名字couchbaseCustomConversions
爲避免在您本身的配置中對這些名稱進行硬編碼,您能夠重複使用BeanNames
Spring Data Couchbase。例如,您能夠自定義要使用的轉換器,以下所示:
@Configuration 公共 類 SomeConfiguration { @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) public CustomConversions myCustomConversions(){ return new CustomConversions(...); } // ... }
若是要徹底繞過Spring Data Couchbase的自動配置,請提供本身的 |
LDAP(輕量級目錄訪問協議)是一種開放的,與供應商無關的行業標準應用程序協議,用於經過IP網絡訪問和維護分佈式目錄信息服務。Spring Boot爲任何兼容的LDAP服務器提供自動配置,併爲UnboundID支持嵌入式內存中LDAP服務器 。
LDAP抽象由 Spring Data LDAP提供。有一個spring-boot-starter-data-ldap
'Starter'用於以方便的方式收集依賴項。
要鏈接到LDAP服務器,請確保聲明對spring-boot-starter-data-ldap
「Starter」 的依賴關係, 或者spring-ldap-core
在application.properties中聲明服務器的URL:
spring.ldap.urls = ldap:// myserver:1235 spring.ldap.username = admin spring.ldap.password = secret
若是須要自定義鏈接設置,能夠使用spring.ldap.base
和 spring.ldap.base-environment
屬性。
Spring Data includes repository support for LDAP. For complete details of Spring Data LDAP, refer to their reference documentation.
You can also inject an auto-configured LdapTemplate
instance as you would with any other Spring Bean.
@Component public class MyBean { private final LdapTemplate template; @Autowired public MyBean(LdapTemplate template) { this.template = template; } // ... }
For testing purposes Spring Boot supports auto-configuration of an in-memory LDAP server from UnboundID. To configure the server add a dependency to com.unboundid:unboundid-ldapsdk
and declare a base-dn
property:
spring.ldap.embedded.base-dn=dc=spring,dc=io
By default the server will start on a random port and they trigger the regular LDAP support (there is no need to specify a spring.ldap.urls
property).
If there is a schema.ldif
file on your classpath it will be used to initialize the server. You can also use the spring.ldap.embedded.ldif
property if you want to load the initialization script from a different resource.
By default, a standard schema will be used to validate LDIF
files, you can turn off validation altogether using the spring.ldap.embedded.validation.enabled
property. If you have custom attributes, you can use spring.ldap.embedded.validation.schema
to define your custom attribute types or object classes.
InfluxDB is an open-source time series database optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet of Things sensor data, and real-time analytics.
Spring Boot auto-configures an InfluxDB
instance as long as the influxdb-java
client is on the classpath and the url of the database is set:
spring.influx.url=http://172.0.0.1:8086
If the connection to InfluxDB requires a user and password, you can set the spring.influx.user
and spring.influx.password
properties accordingly.
InfluxDB relies on OkHttp. If you need to tune the http client InfluxDB
uses behind the scenes, you can register a OkHttpClient.Builder
bean.
Spring Framework支持透明地嚮應用程序添加緩存。從本質上講,抽象將緩存應用於方法,從而減小了基於緩存中可用信息的執行次數。緩存邏輯是透明應用的,不會對調用者形成任何干擾。只要經過@EnableCaching
註釋啓用了緩存支持,Spring Boot就會自動配置緩存基礎結構。
簡而言之,將緩存添加到服務操做就像在其方法中添加相關注釋同樣簡單:
import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Component; @Component 公共 類 MathService { @Cacheable(「piDecimals」) public int computePiDecimal( int i){ // ... } }
此示例演示瞭如何在可能代價高昂的操做上使用緩存。在調用以前computePiDecimal
,抽象將在piDecimals
與i
參數匹配的緩存中查找條目。若是找到條目,則緩存中的內容會當即返回給調用者,而且不會調用該方法。不然,在返回值以前調用該方法並更新緩存。
您還能夠 |
若是您不添加任何特定的緩存庫,Spring Boot將自動配置在內存中使用併發映射的 Simple提供程序。當須要緩存時(即piDecimals
在上面的示例中),此提供程序將爲您即時建立它。簡單的提供程序並非真正推薦用於生產用途,但它很是適合入門並確保您瞭解這些功能。當您決定使用緩存提供程序時,請務必閱讀其文檔以瞭解如何配置應用程序使用的緩存。實際上,全部提供程序都要求您顯式配置在應用程序中使用的每一個緩存。有些提供了一種自定義spring.cache.cache-names
屬性定義的默認緩存的方法。
若是您使用的緩存基礎結構包含非基於接口的bean,請確保啓用該 |
緩存抽象不提供實際存儲,而是依賴於org.springframework.cache.Cache
和 org.springframework.cache.CacheManager
接口實現的抽象。
若是還沒有定義類型的bean CacheManager
或CacheResolver
命名 的bean cacheResolver
(請參閱參考資料CachingConfigurer
),Spring Boot會嘗試檢測如下提供程序(按此順序):
It is also possible to force the cache provider to use via the |
Use the |
If the CacheManager
is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean implementing theCacheManagerCustomizer
interface. The following sets a flag to say that null values should be passed down to the underlying map.
@Bean public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() { return new CacheManagerCustomizer<ConcurrentMapCacheManager>() { @Override public void customize(ConcurrentMapCacheManager cacheManager) { cacheManager.setAllowNullValues(false); } }; }
In the example above, an auto-configured |
Generic caching is used if the context defines at least one org.springframework.cache.Cache
bean. A CacheManager
wrapping all beans of that type is created.
JCache is bootstrapped via the presence of a javax.cache.spi.CachingProvider
on the classpath (i.e. a JSR-107 compliant caching library) and the JCacheCacheManager
provided by the spring-boot-starter-cache
‘Starter’. There are various compliant libraries out there and Spring Boot provides dependency management for Ehcache 3, Hazelcast and Infinispan. Any other compliant library can be added as well.
It might happen that more than one provider is present, in which case the provider must be explicitly specified. Even if the JSR-107 standard does not enforce a standardized way to define the location of the configuration file, Spring Boot does its best to accommodate with implementation details.
# Only necessary if more than one provider is present
spring.cache.jcache.provider=com.acme.MyCachingProvider spring.cache.jcache.config=classpath:acme.xml
Since a cache library may offer both a native implementation and JSR-107 support Spring Boot will prefer the JSR-107 support so that the same features are available if you switch to a different JSR-107 implementation. |
Spring Boot has a general support for Hazelcast. If a single |
There are several ways to customize the underlying javax.cache.cacheManager
:
spring.cache.cache-names
property. If a custom javax.cache.configuration.Configuration
bean is defined, it is used to customize them.org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer
beans are invoked with the reference of the CacheManager
for full customization. If a standard |
EhCache 2.x is used if a file named ehcache.xml
can be found at the root of the classpath. If EhCache 2.x, the EhCacheCacheManager
provided by thespring-boot-starter-cache
‘Starter’ and such file is present it is used to bootstrap the cache manager. An alternate configuration file can be provided as well using:
spring.cache.ehcache.config=classpath:config/another-config.xml
Spring Boot has a general support for Hazelcast. If a HazelcastInstance
has been auto-configured, it is automatically wrapped in a CacheManager
.
Infinispan has no default configuration file location so it must be specified explicitly (or the default bootstrap is used).
spring.cache.infinispan.config=infinispan.xml
Caches can be created on startup via the spring.cache.cache-names
property. If a custom ConfigurationBuilder
bean is defined, it is used to customize them.
The support of Infinispan in Spring Boot is restricted to the embedded mode and is quite basic. If you want more options you should use the official Infinispan Spring Boot starter instead, check the documentation for more details. |
If the Couchbase java client and the couchbase-spring-cache
implementation are available and Couchbase is configured, a CouchbaseCacheManager
will be auto-configured. It is also possible to create additional caches on startup using the spring.cache.cache-names
property. These will operate on the Bucket
that was auto-configured. You can also create additional caches on another Bucket
using the customizer: assume you need two caches on the "main" Bucket
(foo
and bar
) and one biz
cache with a custom time to live of 2sec on the another
Bucket
. First, you can create the two first caches simply via configuration:
spring.cache.cache-names=foo,bar
Then define this extra @Configuration
to configure the extra Bucket
and the biz
cache:
@Configuration public class CouchbaseCacheConfiguration { private final Cluster cluster; public CouchbaseCacheConfiguration(Cluster cluster) { this.cluster = cluster; } @Bean public Bucket anotherBucket() { return this.cluster.openBucket("another", "secret"); } @Bean public CacheManagerCustomizer<CouchbaseCacheManager> cacheManagerCustomizer() { return c -> { c.prepareCache("biz", CacheBuilder.newInstance(anotherBucket()) .withExpiration(2)); }; } }
This sample configuration reuses the Cluster
that was created via auto-configuration.
If Redis is available and configured, the RedisCacheManager
is auto-configured. It is also possible to create additional caches on startup using the spring.cache.cache-names
property.
By default, a key prefix is added to prevent that if two separate caches use the same key, Redis would have overlapping keys and be likely to return invalid values. We strongly recommend to keep this setting enabled if you create your own |
Caffeine is a Java 8 rewrite of Guava’s cache that supersede the Guava support. If Caffeine is present, a CaffeineCacheManager
(provided by thespring-boot-starter-cache
‘Starter’) is auto-configured. Caches can be created on startup using the spring.cache.cache-names
property and customized by one of the following (in this order):
spring.cache.caffeine.spec
com.github.benmanes.caffeine.cache.CaffeineSpec
bean is definedcom.github.benmanes.caffeine.cache.Caffeine
bean is definedFor instance, the following configuration creates a foo
and bar
caches with a maximum size of 500 and a time to live of 10 minutes
spring.cache.cache-names=foo,bar
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
此外,若是com.github.benmanes.caffeine.cache.CacheLoader
定義了bean,它會自動關聯到CaffeineCacheManager
。因爲CacheLoader
它將與緩存管理器管理的全部緩存相關聯,所以必須將其定義爲CacheLoader<Object, Object>
。自動配置將忽略任何其餘泛型類型。
若是找不到其餘提供程序,ConcurrentHashMap
則配置使用as cache store 的簡單實現 。若是應用程序中不存在緩存庫,則這是默認值。默認狀況下,即時建立緩存,但您能夠使用該cache-names
屬性限制可用緩存的列表。例如,若是您只想foo
和bar
緩存:
spring.cache.cache-names = foo,bar
若是執行此操做而且您的應用程序使用未列出的緩存,那麼在運行時須要緩存時它將失敗,但在啓動時則不會。這相似於「真實」緩存提供程序在使用未聲明的緩存時的行爲方式。
Spring Framework爲與消息傳遞系統的集成提供了普遍的支持:從簡化使用JMS API JmsTemplate
到完整的基礎架構,以異步接收消息。Spring AMQP爲「高級消息隊列協議」提供了相似的功能集,Spring Boot還爲RabbitTemplate
RabbitMQ 提供了自動配置選項。Spring WebSocket自己也支持STOMP消息傳遞,Spring Boot經過啓動器和少許自動配置支持。Spring Boot也支持Apache Kafka。
該javax.jms.ConnectionFactory
接口提供了一種建立javax.jms.Connection
與JMS代理交互的標準方法 。雖然Spring須要 ConnectionFactory
使用JMS,但您一般不須要本身直接使用它,而是能夠依賴於更高級別的消息傳遞抽象(有關詳細信息,請參閱Spring Framework參考文檔的 相關部分)。Spring Boot還自動配置發送和接收消息所需的基礎結構。
Spring Boot還能夠ConnectionFactory
在檢測到ActiveMQ在類路徑上可用時進行配置。若是代理存在,則會自動啓動並配置嵌入式代理(只要經過配置未指定代理URL)。
若是您正在使用 |
ActiveMQ配置由外部配置屬性控制 spring.activemq.*
。例如,您能夠在如下部分聲明如下部分 application.properties
:
spring.activemq.broker-url = tcp://192.168.1.210:9876 spring.activemq.user = admin spring.activemq.password = secret
您還能夠經過添加依賴項org.apache.activemq:activemq-pool
並相應地配置來池化JMS資源 PooledConnectionFactory
:
spring.activemq.pool.enabled = true spring.activemq.pool.max-connections = 50
有關 |
默認狀況下,ActiveMQ會建立一個目標(若是它尚不存在),所以目標將根據其提供的名稱進行解析。
Spring Boot can auto-configure a ConnectionFactory
when it detects that Artemis is available on the classpath. If the broker is present, an embedded broker is started and configured automatically (unless the mode property has been explicitly set). The supported modes are: embedded
(to make explicit that an embedded broker is required and should lead to an error if the broker is not available in the classpath), and native
to connect to a broker using the netty
transport protocol. When the latter is configured, Spring Boot configures a ConnectionFactory
connecting to a broker running on the local machine with the default settings.
If you are using |
Artemis configuration is controlled by external configuration properties in spring.artemis.*
. For example, you might declare the following section inapplication.properties
:
spring.artemis.mode=native
spring.artemis.host=192.168.1.210 spring.artemis.port=9876 spring.artemis.user=admin spring.artemis.password=secret
When embedding the broker, you can choose if you want to enable persistence, and the list of destinations that should be made available. These can be specified as a comma-separated list to create them with the default options; or you can define bean(s) of typeorg.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration
or org.apache.activemq.artemis.jms.server.config.TopicConfiguration
, for advanced queue and topic configurations respectively.
See ArtemisProperties
for more of the supported options.
No JNDI lookup is involved at all and destinations are resolved against their names, either using the ‘name’ attribute in the Artemis configuration or the names provided through configuration.
If you are running your application in an Application Server Spring Boot will attempt to locate a JMS ConnectionFactory
using JNDI. By default the locations java:/JmsXA
and java:/XAConnectionFactory
will be checked. You can use the spring.jms.jndi-name
property if you need to specify an alternative location:
spring.jms.jndi-name=java:/MyConnectionFactory
Spring’s JmsTemplate
is auto-configured and you can autowire it directly into your own beans:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final JmsTemplate jmsTemplate; @Autowired public MyBean(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } // ... }
|
When the JMS infrastructure is present, any bean can be annotated with @JmsListener
to create a listener endpoint. If no JmsListenerContainerFactory
has been defined, a default one is configured automatically. If a DestinationResolver
or MessageConverter
beans are defined, they are associated automatically to the default factory.
The default factory is transactional by default. If you are running in an infrastructure where a JtaTransactionManager
is present, it will be associated to the listener container by default. If not, the sessionTransacted
flag will be enabled. In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding @Transactional
on your listener method (or a delegate thereof). This will make sure that the incoming message is acknowledged once the local transaction has completed. This also includes sending response messages that have been performed on the same JMS session.
The following component creates a listener endpoint on the someQueue
destination:
@Component public class MyBean { @JmsListener(destination =「someQueue」) public void processMessage(String content){ // ... } }
查看Javadoc以 |
若是您須要建立更多JmsListenerContainerFactory
實例,或者若是要覆蓋默認實例,則Spring Boot提供了一個DefaultJmsListenerContainerFactoryConfigurer
可用於初始化a DefaultJmsListenerContainerFactory
的設置,其設置與自動配置的設置相同。
例如,如下公開了另外一個使用特定的工廠 MessageConverter
:
@Configuration 靜態 類 JmsConfiguration { @Bean public DefaultJmsListenerContainerFactory myFactory( DefaultJmsListenerContainerFactoryConfigurer configurer){ DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory,connectionFactory()); factory.setMessageConverter(myMessageConverter()); 返回工廠; } }
而後您能夠在任何@JmsListener
註釋方法中使用以下:
@Component 公共 類 MyBean { @JmsListener(destination = 「someQueue」,containerFactory =「myFactory」) public void processMessage(String content){ // ... } }
高級消息隊列協議(AMQP)是面向消息的中間件的平臺中立的線級協議。Spring AMQP項目將核心Spring概念應用於基於AMQP的消息傳遞解決方案的開發。Spring Boot提供了幾種經過RabbitMQ使用AMQP的便利,包括 spring-boot-starter-amqp
'Starter'。
RabbitMQ是一個基於AMQP協議的輕量級,可靠,可擴展且可移植的消息代理。Spring使用RabbitMQ
AMQP協議進行通訊。
RabbitMQ配置由外部配置屬性控制 spring.rabbitmq.*
。例如,您能夠在如下部分聲明如下部分 application.properties
:
spring.rabbitmq.host = localhost spring.rabbitmq.port = 5672 spring.rabbitmq.username = admin spring.rabbitmq.password = secret
有關RabbitProperties
更多支持的選項,請參閱。
檢查瞭解AMQP,RabbitMQ使用的協議以 獲取更多詳細信息。 |
Spring的AmqpTemplate
並AmqpAdmin
配置自動,您能夠直接自動裝配它們變成你本身的豆:
import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyBean { private final AmqpAdmin amqpAdmin; private final AmqpTemplate amqpTemplate; @Autowired public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) { this.amqpAdmin = amqpAdmin; this.amqpTemplate = amqpTemplate; } // ... }
|
Any org.springframework.amqp.core.Queue
that is defined as a bean will be automatically used to declare a corresponding queue on the RabbitMQ instance if necessary.
您能夠在AmqpTemplate
重試操做上啓用重試,例如在代理鏈接丟失的狀況下。默認狀況下禁用重試。
當Rabbit基礎結構存在時,能夠使用任何bean來註釋 @RabbitListener
以建立偵聽器端點。若是RabbitListenerContainerFactory
未定義,SimpleRabbitListenerContainerFactory
則會自動配置默認值,您能夠使用該spring.rabbitmq.listener.type
屬性切換到直接容器 。若是 定義了一個MessageConverter
或MessageRecoverer
bean,它們將自動關聯到默認工廠。
如下組件在someQueue
隊列上建立偵聽器端點:
@Component 公共 類 MyBean { @RabbitListener(queues =「someQueue」) public void processMessage(String content){ // ... } }
查看Javadoc以 |
若是您須要建立更多的RabbitListenerContainerFactory
實例或若是要覆蓋默認,春天啓動提供了一個 SimpleRabbitListenerContainerFactoryConfigurer
和DirectRabbitListenerContainerFactoryConfigurer
你能夠用它來初始化 SimpleRabbitListenerContainerFactory
,並DirectRabbitListenerContainerFactory
使用相同的設置,經過自動配置中使用的一個。
您選擇的容器類型可有可無,這兩個bean經過自動配置公開。 |
例如,如下公開了另外一個使用特定的工廠 MessageConverter
:
@Configuration 靜態 類 RabbitConfiguration { @Bean public SimpleRabbitListenerContainerFactory myFactory( SimpleRabbitListenerContainerFactoryConfigurer configurer){ SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory,connectionFactory); factory.setMessageConverter(myMessageConverter()); 返回工廠; } }
而後您能夠在任何@RabbitListener
註釋方法中使用以下:
@Component 公共 類 MyBean { @RabbitListener(queues = 「someQueue」,containerFactory =「myFactory」) public void processMessage(String content){ // ... } }
You can enable retries to handle situations where your listener throws an exception. By default RejectAndDontRequeueRecoverer
is used but you can define a MessageRecoverer
of your own. When retries are exhausted, the message will be rejected and either dropped or routed to a dead-letter exchange if the broker is configured so. Retries are disabled by default.
Important | |
---|---|
If retries are not enabled and the listener throws an exception, by default the delivery will be retried indefinitely. You can modify this behavior in two ways; set the |
Apache Kafka is supported by providing auto-configuration of the spring-kafka
project.
Kafka configuration is controlled by external configuration properties in spring.kafka.*
. For example, you might declare the following section inapplication.properties
:
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup
See KafkaProperties
for more of the supported options.
Spring’s KafkaTemplate
is auto-configured and you can autowire them directly in your own beans:
@Component public class MyBean { private final KafkaTemplate kafkaTemplate; @Autowired public MyBean(KafkaTemplate kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } // ... }
When the Apache Kafka infrastructure is present, any bean can be annotated with @KafkaListener
to create a listener endpoint. If no KafkaListenerContainerFactory
has been defined, a default one is configured automatically with keys defined in spring.kafka.listener.*
.
The following component creates a listener endpoint on the someTopic
topic:
@Component public class MyBean { @KafkaListener(topics = "someTopic") public void processMessage(String content) { // ... } }
The properties supported by auto configuration are shown in Appendix A, Common application properties. Note that these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties for the most part, refer to the Apache Kafka documentation for details.
The first few of these properties apply to both producers and consumers, but can be specified at the producer or consumer level if you wish to use different values for each. Apache Kafka designates properties with an importance: HIGH, MEDIUM and LOW. Spring Boot auto configuration supports all HIGH importance properties, some selected MEDIUM and LOW, and any that do not have a default value.
只有Kafka支持的屬性的子集可經過KafkaProperties
該類得到。若是您但願使用不直接支持的其餘屬性配置生產者或使用者,請使用如下命令:
spring.kafka.properties.foo.bar = baz spring.kafka.consumer.properties.fiz.buz = qux spring,kafka.producer.properties.baz.qux = fiz
這將常見的foo.bar
Kafka屬性設置爲baz
(適用於生產者和使用者),將消費者fiz.buz
屬性設置qux
爲baz.qux
生產者屬性fiz
。
重要 | |
---|---|
以這種方式設置的屬性將覆蓋Spring Boot明確支持的任何配置項。 |
若是須要從應用程序調用遠程REST服務,能夠使用Spring Framework的RestTemplate
類。因爲RestTemplate
實例在使用以前一般須要自定義,所以Spring Boot不提供任何單個自動配置的 RestTemplate
bean。可是,它會自動配置a RestTemplateBuilder
,可RestTemplate
在須要時用於建立實例。自動配置RestTemplateBuilder
將確保將敏感HttpMessageConverters
應用於RestTemplate
實例。
這是一個典型的例子:
@Service public class MyService { 私人 決賽 RestTemplate restTemplate; public MyBean(RestTemplateBuilder restTemplateBuilder){ this .restTemplate = restTemplateBuilder.build(); } 公衆詳細someRestCall(字符串名稱){ 返回 此 .restTemplate.getForObject(「/ {名} /詳細信息」,詳細信息。類,名); } }
|
RestTemplate
自定義有三種主要方法,具體取決於您但願自定義應用的普遍程度。
要使任何自定義的範圍儘量窄,請注入自動配置 RestTemplateBuilder
,而後根據須要調用其方法。每一個方法調用都返回一個新RestTemplateBuilder
實例,所以自定義只會影響構建器的使用。
爲了實現應用程序範圍的附加定製,RestTemplateCustomizer
能夠使用bean。全部這些bean都自動註冊自動配置 RestTemplateBuilder
,並將應用於使用它構建的任何模板。
這是一個定製器的示例,它爲全部主機配置代理的使用,除了 192.168.0.5
:
靜態 類 ProxyCustomizer 實現 RestTemplateCustomizer { @Override public void customize(RestTemplate restTemplate){ HttpHost proxy = new HttpHost(「proxy.example.com」); HttpClient httpClient = HttpClientBuilder.create() .setRoutePlanner(new DefaultProxyRoutePlanner(proxy){ @覆蓋 公共 HttpHost determineProxy(HttpHost目標, HttpRequest請求,HttpContext上下文) 拋出 HttpException { if(target.getHostName()。equals(「192.168.0.5」)){ return null; } return super .determineProxy(target,request,context); } })。創建(); restTemplate.setRequestFactory( 新的 HttpComponentsClientHttpRequestFactory(httpClient)); } }
最後,最極端(也不多使用)的選項是建立本身的 RestTemplateBuilder
bean。這將關閉a的自動配置, RestTemplateBuilder
並將阻止使用任何RestTemplateCustomizer
bean。
若是你的類路徑上有Spring WebFlux,你也能夠選擇WebClient
用來調用遠程REST服務; 相比之下RestTemplate
,這個客戶端具備更多的功能感,而且徹底被動。您能夠使用構建器建立本身的客戶端實例,該構建器WebClient.create()
已經提供了良好的開箱即用體驗。請參閱WebClient上的 相關部分。
Spring Boot將爲您建立和預配置這樣的構建器; 例如,客戶端HTTP編解碼器將像服務器同樣配置(請參閱WebFlux HTTP編解碼器自動配置)。
這是一個典型的例子:
@Service public class MyService { 私有 最終 WebClient webClient; public MyBean(WebClient.Builder webClientBuilder){ this .webClient = webClientBuilder.baseUrl(「http://example.org」)。build(); } public Mono <Details> someRestCall(String name){ return this .webClient.get()。url(「/ {name} / details」,name) 。.retrieve()bodyToMono(詳情。類); } }
WebClient
自定義有三種主要方法,具體取決於您但願自定義應用的普遍程度。
要使任何自定義的範圍儘量窄,請注入自動配置 WebClient.Builder
,而後根據須要調用其方法。WebClient.Builder
實例是有狀態的; 對構建器的任何更改都將反映在隨後使用它建立的全部客戶端中。若是您想使用相同的構建器建立多個客戶端,還能夠考慮使用克隆構建器WebClient.Builder other = builder.clone();
。
To make an application-wide, additive customization to all WebClient.Builder
instances, you can declare WebClientCustomizer
beans and change the WebClient.Builder
as you would do locally at the point of injection.
Lastly, you can fall back to the original API and just use WebClient.create()
. In that case, no auto-configuration nor WebClientCustomizer
will be applied.
The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (e.g. Hibernate validator) is on the classpath. This allows bean methods to be annotated with javax.validation
constraints on their parameters and/or on their return value. Target classes with such annotated methods need to be annotated with the @Validated
annotation at the type level for their methods to be searched for inline constraint annotations.
For instance, the following service triggers the validation of the first argument, making sure its size is between 8 and 10
@Service @Validated public class MyBean { public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code, Author author) { ... } }
The Spring Framework provides an easy abstraction for sending email using the JavaMailSender
interface and Spring Boot provides auto-configuration for it as well as a starter module.
Check the reference documentation for a detailed explanation of how you can use |
若是spring.mail.host
和相關庫(由定義的 spring-boot-starter-mail
)可用,JavaMailSender
則建立默認值(若是不存在)。發件人能夠經過spring.mail
命名空間中的配置項進一步自定義,MailProperties
有關詳細信息,請參閱 。
特別是,某些默認超時值是無限的,您可能但願更改它以免線程被無響應的郵件服務器阻止:
spring.mail.properties.mail.smtp.connectiontimeout = 5000 spring.mail.properties.mail.smtp.timeout = 3000 spring.mail.properties.mail.smtp.writetimeout = 5000
Spring Boot使用Atomikos或Bitronix 嵌入式事務管理器支持跨多個XA資源的分佈式JTA事務。部署到合適的Java EE Application Server時,也支持JTA事務。
當檢測到JTA環境時,Spring JtaTransactionManager
將用於管理事務。自動配置的JMS,DataSource和JPA bean將升級爲支持XA事務。您能夠使用標準的Spring慣用語@Transactional
來參與分佈式事務。若是您在JTA環境中並仍想使用本地事務,則能夠將該spring.jta.enabled
屬性設置false
爲禁用JTA自動配置。
Atomikos是一個流行的開源事務管理器,能夠嵌入到Spring Boot應用程序中。您能夠使用spring-boot-starter-jta-atomikos
Starter引入相應的Atomikos庫。Spring Boot將自動配置Atomikos,並確保depends-on
對Spring bean應用適當的設置,以便正確啓動和關閉命令。
默認狀況下,Atomikos事務日誌將寫入transaction-logs
應用程序主目錄(應用程序jar文件所在的目錄)中的目錄。您能夠經過spring.jta.log-dir
在application.properties
文件中設置屬性來自定義此目錄。屬性啓動spring.jta.atomikos.properties
也可用於自定義Atomikos UserTransactionServiceImp
。有關 完整的詳細信息,請參閱 AtomikosProperties
Javadoc。
爲確保多個事務管理器能夠安全地協調相同的資源管理器,必須使用惟一ID配置每一個Atomikos實例。默認狀況下,此ID是運行Atomikos的計算機的IP地址。要確保生產中的惟一性,應 |
Bitronix是流行的開源JTA事務管理器實現。您能夠使用spring-boot-starter-jta-bitronix
starter將適當的Bitronix依賴項添加到項目中。與Atomikos同樣,Spring Boot將自動配置Bitronix並對bean進行後處理,以確保啓動和關閉順序正確。
默認狀況下,Bitronix事務日誌文件(part1.btm
和part2.btm
)將寫入transaction-logs
應用程序主目錄中的目錄。您能夠使用該spring.jta.log-dir
屬性自定義此目錄。屬性啓動 spring.jta.bitronix.properties
也綁定到bitronix.tm.Configuration
bean,容許徹底自定義。有關 詳細信息,請參閱 Bitronix文檔。
爲確保多個事務管理器能夠安全地協調相同的資源管理器,必須爲每一個Bitronix實例配置惟一ID。默認狀況下,此ID是運行Bitronix的計算機的IP地址。要確保生產中的惟一性,應 |
Narayana是JBoss支持的流行的開源JTA事務管理器實現。您能夠使用spring-boot-starter-jta-narayana
starter將相應的Narayana依賴項添加到項目中。與Atomikos和Bitronix同樣,Spring Boot將自動配置Narayana並對bean進行後處理,以確保啓動和關閉順序正確。
默認狀況下,Narayana事務日誌將寫入transaction-logs
應用程序主目錄(應用程序jar文件所在的目錄)中的目錄。您能夠經過spring.jta.log-dir
在application.properties
文件中設置屬性來自定義此目錄。屬性啓動spring.jta.narayana.properties
也可用於自定義Narayana配置。有關 完整的詳細信息,請參閱 NarayanaProperties
Javadoc。
爲確保多個事務管理器能夠安全地協調相同的資源管理器,必須使用惟一ID配置每一個Narayana實例。默認狀況下,此ID設置爲 |
若是您正在打包春季啓動應用程序做爲war
或ear
文件,並將其部署到Java EE應用服務器,您能夠使用內置的事務管理器應用程序服務器。春天開機時會試圖經過尋找共同的JNDI位置(自動配置一個事務管理器java:comp/UserTransaction
, java:comp/TransactionManager
等等)。若是您使用的是應用程序服務器提供的事務服務,一般還須要確保全部資源都由服務器管理並經過JNDI公開。Spring Boot將嘗試經過ConnectionFactory
在JNDI路徑上查找來自動配置JMS,java:/JmsXA
或者java:/XAConnectionFactory
您能夠使用該 spring.datasource.jndi-name
屬性 來配置您的DataSource
。
使用JTA時,主JMS ConnectionFactory
bean將支持XA並參與分佈式事務。在某些狀況下,您可能但願使用非XA處理某些JMS消息ConnectionFactory
。例如,您的JMS處理邏輯可能須要比XA超時更長的時間。
若是你想使用非XA,ConnectionFactory
你能夠注入 nonXaJmsConnectionFactory
bean而不是@Primary
jmsConnectionFactory
bean。爲了保持一致性,jmsConnectionFactory
還使用bean別名提供bean xaJmsConnectionFactory
。
例如:
//注入主(XA感知)ConnectionFactory
@Autowired
私有 ConnectionFactory defaultConnectionFactory; //注入XA感知ConnectionFactory(使用別名並注入與上面相同的內容) @Autowired @Qualifier(「xaJmsConnectionFactory」) private ConnectionFactory xaConnectionFactory; //注入非XA感知的ConnectionFactory @Autowired @Qualifier(「nonXaJmsConnectionFactory」) 私有 ConnectionFactory nonXaConnectionFactory;
該XAConnectionFactoryWrapper
和XADataSourceWrapper
接口可用於支持替代嵌入式事務經理。接口負責包裝XAConnectionFactory
和XADataSource
bean,並將它們做爲常規ConnectionFactory
和DataSource
bean 公開,它們將透明地註冊到分佈式事務中。只要您有一個JtaTransactionManager
bean和在您的域中註冊的相應XA包裝bean,DataSource和JMS自動配置將使用JTA變體ApplicationContext
。
該BitronixXAConnectionFactoryWrapper 和BitronixXADataSourceWrapper 提供瞭如何編寫XA包裝很好的例子。
若是Hazelcast位於類路徑上並找到合適的配置,Spring Boot將自動配置HazelcastInstance
您能夠在應用程序中注入的配置。
You can define a com.hazelcast.config.Config
bean and we’ll use that. If your configuration defines an instance name, we’ll try to locate an existing instance rather than creating a new one.
You could also specify the hazelcast.xml
configuration file to use via configuration:
spring.hazelcast.config=classpath:config/my-hazelcast.xml
Otherwise, Spring Boot tries to find the Hazelcast configuration from the default locations, that is hazelcast.xml
in the working directory or at the root of the classpath. We also check if the hazelcast.config
system property is set. Check the Hazelcast documentation for more details.
If hazelcast-client
is present on the classpath, Spring Boot will first attempt to create a client with similar rules as above, that is:
com.hazelcast.client.config.ClientConfig
beanspring.hazelcast.config
propertyhazelcast.client.config
system propertyhazelcast-client.xml
in the working directory or at the root of the classpath Spring Boot also has an explicit caching support for Hazelcast. The |
Spring Boot offers several conveniences for working with the Quartz scheduler, including the spring-boot-starter-quartz
‘Starter’. If Quartz is available, a Scheduler
will be auto-configured (via the SchedulerFactoryBean
abstraction).
Beans of the following types will be automatically picked up and associated with the the Scheduler
:
JobDetail
: defines a particular Job. JobDetail
instance can easily be built with the JobBuilder
APICalendar
Trigger
:定義什麼時候觸發特定做業默認狀況下,JobStore
將使用內存。可是,若是DataSource
應用程序中有bean,而且相應地spring.quartz.job-store-type
配置了 屬性,則能夠配置基於JDBC的存儲:
spring.quartz.job-store-type = jdbc
使用jdbc存儲時,能夠在啓動時初始化架構:
spring.quartz.jdbc.initialize-schema = true
默認狀況下會檢測數據庫,並使用Quartz庫提供的標準腳本進行初始化。也能夠使用該 |
能夠使用Quartz配置屬性(請參閱參考資料spring.quartz.properties.*
)和SchedulerFactoryBeanCustomizer
容許編程SchedulerFactoryBean
自定義的bean來自定義Quartz Scheduler配置 。
Job能夠定義setter以注入數據映射屬性。也能夠以相似的方式注入常規豆類:
公共 類 SampleJob 擴展了 QuartzJobBean { private MyService myService; 私有字符串名稱; //注入「MyService」bean public void setMyService(MyService myService){...} //注入「name」做業數據屬性 public void setName(String name){...} @Override protected void executeInternal(JobExecutionContext context) 拋出 JobExecutionException { ... } }
Spring Boot提供了一些使用Spring Integration的便利,包括spring-boot-starter-integration
'Starter'。Spring Integration提供了消息傳遞以及其餘傳輸(如HTTP,TCP等)的抽象。若是類路徑上有Spring Integration,它將經過@EnableIntegration
註釋進行初始化 。
Spring Boot還將配置因爲存在其餘Spring Integration模塊而觸發的一些功能。若是'spring-integration-jmx'
也在類路徑上,則將經過JMX發佈消息處理統計信息。若是 'spring-integration-jdbc'
可用,則能夠在啓動時建立默認數據庫模式:
spring.integration.jdbc.initializer.enabled = true
有關 詳細信息,請參閱 IntegrationAutoConfiguration
和IntegrationProperties
類。
Spring Boot provides Spring Session auto-configuration for a wide range of stores:
If Spring Session is available, you must choose the StoreType
that you wish to use to store the sessions. For instance to use JDBC as backend store, you’d configure your application as follows:
spring.session.store-type=jdbc
You can disable Spring Session by setting the |
Each store has specific additional settings. For instance it is possible to customize the name of the table for the jdbc store:
spring.session.jdbc.table-name=SESSIONS
Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default Spring Boot will create an MBeanServer
with bean id ‘mbeanServer’ and expose any of your beans that are annotated with Spring JMX annotations (@ManagedResource
, @ManagedAttribute
, @ManagedOperation
).
See the JmxAutoConfiguration
class for more details.
Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules; spring-boot-test
contains core items, and spring-boot-test-autoconfigure
supports auto-configuration for tests.
Most developers will just use the spring-boot-starter-test
‘Starter’ which imports both Spring Boot test modules as well has JUnit, AssertJ, Hamcrest and a number of other useful libraries.
If you use the spring-boot-starter-test
‘Starter’ (in the test
scope
), you will find the following provided libraries:
These are common libraries that we generally find useful when writing tests. You are free to add additional test dependencies of your own if these don’t suit your needs.
One of the major advantages of dependency injection is that it should make your code easier to unit test. You can simply instantiate objects using the new
operator without even involving Spring. You can also use mock objects instead of real dependencies.
Often you need to move beyond ‘unit testing’ and start ‘integration testing’ (with a Spring ApplicationContext
actually involved in the process). It’s useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure.
The Spring Framework includes a dedicated test module for just such integration testing. You can declare a dependency directly to org.springframework:spring-test
or use the spring-boot-starter-test
‘Starter’ to pull it in transitively.
If you have not used the spring-test
module before you should start by reading the relevant section of the Spring Framework reference documentation.
A Spring Boot application is just a Spring ApplicationContext
, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. One thing to watch out for though is that the external properties, logging and other features of Spring Boot are only installed in the context by default if you use SpringApplication
to create it.
Spring Boot provides a @SpringBootTest
annotation which can be used as an alternative to the standard spring-test
@ContextConfiguration
annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext
used in your tests via SpringApplication
.
You can use the webEnvironment
attribute of @SpringBootTest
to further refine how your tests will run:
MOCK
— Loads a WebApplicationContext
and provides a mock servlet environment. Embedded servlet containers are not started when using this annotation. If servlet APIs are not on your classpath this mode will transparently fallback to creating a regular non-web ApplicationContext
. Can be used in conjunction with@AutoConfigureMockMvc
for MockMvc
-based testing of your application.RANDOM_PORT
— Loads an ServletWebServerApplicationContext
and provides a real servlet environment. Embedded servlet containers are started and listening on a random port.DEFINED_PORT
— Loads an ServletWebServerApplicationContext
and provides a real servlet environment. Embedded servlet containers are started and listening on a defined port (i.e from your application.properties
or on the default port 8080
).NONE
- 加載ApplicationContext
使用SpringApplication
但不提供 任何 servlet環境(模擬或其餘)。 若是您的測試是 |
除了 |
不要忘記也添加 |
若是您熟悉Spring Test Framework,那麼您可能習慣使用 @ContextConfiguration(classes=…)
它來指定@Configuration
要加載的Spring 。或者,您可能常常@Configuration
在測試中使用嵌套類。
在測試Spring Boot應用程序時,一般不須要這樣作。@*Test
只要您沒有明肯定義,Spring Boot的註釋就會自動搜索您的主要配置。
搜索算法從包含測試的包開始工做,直到找到一個 @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(){ ... } }
若是您直接使用 |
If you need to start a full running server for tests, we recommend that you use random ports. If you use @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
an available port will be picked at random each time your test runs.
The @LocalServerPort
annotation can be used to inject the actual port used into your test. For convenience, tests that need to make REST calls to the started server can additionally @Autowire
a TestRestTemplate
which will resolve relative links to the running server.
import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class RandomPortExampleTests { @Autowired private TestRestTemplate restTemplate; @Test public void exampleTest() { String body = this.restTemplate.getForObject("/", String.class); assertThat(body).isEqualTo("Hello World"); } }
It’s sometimes necessary to mock certain components within your application context when running tests. For example, you may have a facade over some remote service that’s unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment.
Spring Boot includes a @MockBean
annotation that can be used to define a Mockito mock for a bean inside your ApplicationContext
. You can use the annotation to add new beans, or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on @Configuration
classes and fields. When used on a field, the instance of the created mock will also be injected. Mock beans are automatically reset after each test method.
This feature is automatically enabled as long as your test uses one of Spring Boot’s test annotations (i.e. @TestExecutionListeners(MockitoTestExecutionListener.class) |
Here’s a typical example where we replace an existing RemoteService
bean with a mock implementation:
import org.junit.*;
import org.junit.runner.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.context.*; import org.springframework.boot.test.mock.mockito.*; import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; @RunWith(SpringRunner.class) @SpringBootTest public class MyTests { @MockBean private RemoteService remoteService; @Autowired private Reverser reverser; @Test public void exampleTest() { // RemoteService has been injected into the reverser bean given(this.remoteService.someCall()).willReturn("mock"); String reverse = reverser.reverseSomeCall(); assertThat(reverse).isEqualTo("kcom"); } }
Additionally you can also use @SpyBean
to wrap any existing bean with a Mockito spy
. See the Javadoc for full details.
Spring Boot’s auto-configuration system works well for applications, but can sometimes be a little too much for tests. It’s often helpful to load only the parts of the configuration that are required to test a ‘slice’ of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you don’t want to involve database calls in those tests; or you might be wanting to test JPA entities, and you’re not interested in web layer when those tests run.
The spring-boot-test-autoconfigure
module includes a number of annotations that can be used to automatically configure such ‘slices’. Each of them works in a similar way, providing a @…Test
annotation that loads the ApplicationContext
and one or more @AutoConfigure…
annotations that can be used to customize auto-configuration settings.
Each slice loads a very restricted set of auto-configuration classes. If you need to exclude one of them, most |
It’s also possible to use the |
To test that Object JSON serialization and deserialization is working as expected you can use the @JsonTest
annotation. @JsonTest
will auto-configure Jackson ObjectMapper
, any @JsonComponent
beans and any Jackson Modules
. It also configures Gson
if you happen to be using that instead of, or as well as, Jackson. If you need to configure elements of the auto-configuration you can use the @AutoConfigureJsonTesters
annotation.
Spring Boot includes AssertJ based helpers that work with the JSONassert and JsonPath libraries to check that JSON is as expected. The JacksonTester
, GsonTester
and BasicJsonTester
classes can be used for Jackson, Gson and Strings respectively. Any helper fields on the test class can be @Autowired
when using @JsonTest
.
import org.junit.*;
import org.junit.runner.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.autoconfigure.json.*; import org.springframework.boot.test.context.*; import org.springframework.boot.test.json.*; import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*; @RunWith(SpringRunner.class) @JsonTest public class MyJsonTests { @Autowired private JacksonTester<VehicleDetails> json; @Test public void testSerialize() throws Exception { VehicleDetails details = new VehicleDetails("Honda", "Civic"); // Assert against a `.json` file in the same package as the test assertThat(this.json.write(details)).isEqualToJson("expected.json"); // Or use JSON path based assertions assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") .isEqualTo("Honda"); } @Test public void testDeserialize() throws Exception { String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; assertThat(this.json.parse(content)) .isEqualTo(new VehicleDetails("Ford", "Focus")); assertThat(this .json.parseObject(content).getMake())。isEqualTo(「Ford」); } }
JSON幫助程序類也能夠直接在標準單元測試中使用。若是您不使用,只需在 |
@JsonTest
能夠 在附錄中找到啓用的自動配置列表。
要測試Spring MVC控制器是否正常工做,您能夠使用@WebMvcTest
註釋。@WebMvcTest
將自動配置Spring MVC的基礎設施和限制掃描豆@Controller
,@ControllerAdvice
,@JsonComponent
,Filter
, WebMvcConfigurer
和HandlerMethodArgumentResolver
。@Component
使用此批註時,不會掃描常規bean。
一般@WebMvcTest
將限於單個控制器並與其結合使用 @MockBean
,以便爲所需的協做者提供模擬實現。
@WebMvcTest
還自動配置MockMvc
。Mock MVC提供了一種快速測試MVC控制器的強大方法,無需啓動完整的HTTP服務器。
您也能夠經過使用註釋來 |
import org.junit。*; import org.junit.runner。*; import org.springframework.beans.factory.annotation。*; import org.springframework.boot.test.autoconfigure.web.servlet。*; import org.springframework.boot.test.mock.mockito。*; import static org.assertj.core.api.Assertions。*; import static org.mockito.BDDMockito。*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders。*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers。*; @RunWith(SpringRunner.class) @WebMvcTest(UserVehicleController.class) public class MyControllerTests { @Autowired 私人 MockMvc mvc; @MockBean private UserVehicleService userVehicleService; @Test public void testExample()拋出異常{ 給定(此 .userVehicleService.getVehicleDetails(「sboot」)) .willReturn(new VehicleDetails(「Honda」,「Civic」)); 這個 .mvc.perform(get(「/ sboot / vehicle」)。accept(MediaType.TEXT_PLAIN)) .andExpect(status()。isOk())。andExpect(content()。string(「Honda Civic」)); } }
若是須要配置自動配置的元素(例如,應該應用servlet過濾器時),則能夠使用 |
若是您使用HtmlUnit或Selenium,自動配置還將提供HTMLUnit WebClient
bean和/或WebDriver
bean。這是一個使用HtmlUnit的示例:
import com.gargoylesoftware.htmlunit。*; import org.junit。*; import org.junit.runner。*; import org.springframework.beans.factory.annotation。*; import org.springframework.boot.test.autoconfigure.web.servlet。*; import org.springframework.boot.test.mock.mockito。*; import static org.assertj.core.api.Assertions。*; import static org.mockito.BDDMockito。*; @RunWith(SpringRunner.class) @WebMvcTest(UserVehicleController.class) public class MyHtmlUnitTests { @Autowired 私有 WebClient webClient; @MockBean private UserVehicleService userVehicleService; @Test public void testExample()拋出異常{ 給定(此 .userVehicleService.getVehicleDetails(「sboot」)) .willReturn(new VehicleDetails(「Honda」,「Civic」)); HtmlPage page = this .webClient.getPage(「/sboot/vehicle.html」); assertThat(page.getBody()。getTextContent())。isEqualTo(「Honda Civic」); } }
默認狀況下,Spring Boot會將 |
@WebMvcTest
能夠 在附錄中找到啓用的自動配置列表。
要測試Spring WebFlux控制器是否正常工做,您能夠使用@WebFluxTest
註釋。@WebFluxTest
將自動配置Spring WebFlux基礎設施和限制掃描豆@Controller
,@ControllerAdvice
,@JsonComponent
,和 WebFluxConfigurer
。@Component
使用此批註時,不會掃描常規bean。
一般@WebFluxTest
將限於單個控制器並與其結合使用 @MockBean
,以便爲所需的協做者提供模擬實現。
@WebFluxTest
還有自動配置WebTestClient
,這提供了一種快速測試WebFlux控制器的強大方法,無需啓動完整的HTTP服務器。
您也能夠經過使用註釋來 |
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @WebFluxTest(UserVehicleController.class) public class MyControllerTests { @Autowired 私有 WebTestClient webClient; @MockBean private UserVehicleService userVehicleService; @Test public void testExample()拋出異常{ 給定(此 .userVehicleService.getVehicleDetails(「sboot」)) .willReturn(new VehicleDetails(「Honda」,「Civic」)); 這個 .webClient.get()。uri(「/ sboot / vehicle」)。accept(MediaType.TEXT_PLAIN) 。交換() .expectStatus()。ISOK() .expectBody(String .class).isEqualTo(「Honda Civic」); } }
A list of the auto-configuration that is enabled by @WebFluxTest
can be found in the appendix.
@DataJpaTest
can be used if you want to test JPA applications. By default it will configure an in-memory embedded database, scan for @Entity
classes and configure Spring Data JPA repositories. Regular @Component
beans will not be loaded into the ApplicationContext
.
Data JPA tests are transactional and rollback at the end of each test by default, see the relevant section in the Spring Reference Documentation for more details. If that’s not what you want, you can disable transaction management for a test or for the whole class as follows:
import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @DataJpaTest @Transactional(propagation = Propagation.NOT_SUPPORTED) public class ExampleNonTransactionalTests { }
數據JPA測試也能夠注入一個 TestEntityManager
bean,它提供了EntityManager
專門爲測試設計的標準JPA的替代方法。若是你想在TestEntityManager
外面使用@DataJpaTests
你也能夠使用@AutoConfigureTestEntityManager
註釋。JdbcTemplate
若是您須要,也能夠使用A.
import org.junit。*; import org.junit.runner。*; import org.springframework.boot.test.autoconfigure.orm.jpa。*; import static org.assertj.core.api.Assertions。*; @RunWith(SpringRunner.class) @DataJpaTest public class ExampleRepositoryTests { @Autowired 私有 TestEntityManager entityManager; @Autowired 私有 UserRepository存儲庫; @Test public void testExample()拋出 Exception { this .entityManager.persist( new User( 「sboot」, 「1234」)); User user = this .repository.findByUsername(「sboot」); assertThat(user.getUsername())。isEqualTo(「sboot」); assertThat(user.getVin())。isEqualTo(「1234」); } }
內存中的嵌入式數據庫一般能夠很好地用於測試,由於它們很快而且不須要任何開發人員安裝。可是,若是您更喜歡對真實數據庫運行測試,則能夠使用@AutoConfigureTestDatabase
註釋:
@RunWith(SpringRunner.class) @DataJpaTest @AutoConfigureTestDatabase(replace = Replace.NONE) public class ExampleRepositoryTests { // ... }
@DataJpaTest
能夠 在附錄中找到啓用的自動配置列表。
@JdbcTest
相似於@DataJpaTest
純jdbc相關測試。默認狀況下,它還將配置內存中的嵌入式數據庫和JdbcTemplate
。常規 @Component
bean不會被加載到ApplicationContext
。
默認狀況下,JDBC測試在每一個測試結束時都是事務性和回滾,有關詳細信息,請參閱Spring Reference Documentation中的相關部分。若是這不是您想要的,您能夠爲測試或整個類禁用事務管理,以下所示:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @JdbcTest @Transactional(propagation = Propagation.NOT_SUPPORTED) public class ExampleNonTransactionalTests { }
若是您但願測試針對真實數據庫運行,則能夠使用與@AutoConfigureTestDatabase
註釋相同的方式使用 註釋DataJpaTest
。
@JdbcTest
能夠 在附錄中找到啓用的自動配置列表。
@JooqTest
能夠以與@JdbcTest
jOOQ相關的測試相似的方式使用。因爲jOOQ嚴重依賴於與數據庫模式相對應的基於Java的模式,所以DataSource
將使用現有模式。若是要經過內存數據庫替換它,能夠使用@AutoconfigureTestDatabase
覆蓋這些設置。
@JooqTest
將配置一個DSLContext
。常規@Component
bean不會加載到ApplicationContext
:
import org.jooq.DSLContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.jooq.JooqTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @JooqTest public class ExampleJooqTests { @Autowired private DSLContext dslContext; }
默認狀況下,JOOQ測試在每一個測試結束時都是事務性和回滾。若是這不是您想要的,您能夠禁用測試或整個測試類的事務管理,如上例所示。
@JooqTest
能夠 在附錄中找到啓用的自動配置列表。
@DataMongoTest
若是要測試MongoDB應用程序,能夠使用它。默認狀況下,它將配置內存中嵌入式MongoDB(若是可用),配置MongoTemplate
,掃描@Document
類並配置Spring Data MongoDB存儲庫。常規 @Component
bean不會加載到ApplicationContext
:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataMongoTest public class ExampleDataMongoTests { @Autowired private MongoTemplate mongoTemplate; // }
In-memory embedded MongoDB generally works well for tests since it is fast and doesn’t require any developer installation. If, however, you prefer to run tests against a real MongoDB server you should exclude the embedded MongoDB auto-configuration:
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class) public class ExampleDataMongoNonEmbeddedTests { }
A list of the auto-configuration that is enabled by @DataMongoTest
can be found in the appendix.
@DataNeo4jTest
can be used if you want to test Neo4j applications. By default, it will use an in-memory embedded Neo4j (if the embedded driver is available), scan for@NodeEntity
classes and configure Spring Data Neo4j repositories. Regular @Component
beans will not be loaded into the ApplicationContext
:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataNeo4jTest public class ExampleDataNeo4jTests { @Autowired private YourRepository repository; // }
Data Neo4j tests are transactional and rollback at the end of each test by default, see the relevant section in the Spring Reference Documentation for more details. If that’s not what you want, you can disable transaction management for a test or for the whole class as follows:
import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @DataNeo4jTest @Transactional(propagation = Propagation.NOT_SUPPORTED) public class ExampleNonTransactionalTests { }
A list of the auto-configuration that is enabled by @DataNeo4jTest
can be found in the appendix.
@DataRedisTest
can be used if you want to test Redis applications. By default, it will scan for @RedisHash
classes and configure Spring Data Redis repositories. Regular @Component
beans will not be loaded into the ApplicationContext
:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataRedisTest public class ExampleDataRedisTests { @Autowired private YourRepository repository; // }
@DataRedisTest
能夠 在附錄中找到啓用的自動配置列表。
@DataLdapTest
若是要測試LDAP應用程序,能夠使用它。默認狀況下,它將配置內存中嵌入式LDAP(若是可用),a LdapTemplate
,掃描@Entry
類並配置Spring Data LDAP存儲庫。常規@Component
bean不會加載到ApplicationContext
:
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; import org.springframework.ldap.core.LdapTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataLdapTest public class ExampleDataLdapTests { @Autowired private LdapTemplate ldapTemplate; // }
內存中嵌入式LDAP一般適用於測試,由於它速度快,不須要任何開發人員安裝。可是,若是您但願針對真實LDAP服務器運行測試,則應排除嵌入式LDAP自動配置:
import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration; import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataLdapTest(excludeAutoConfiguration = EmbeddedLdapAutoConfiguration.class) public class ExampleDataLdapNonEmbeddedTests { }
@DataLdapTest
能夠 在附錄中找到啓用的自動配置列表。
的@RestClientTest
,若是你想測試REST客戶註釋能夠使用。默認狀況下,它將自動配置Jackson和GSON支持,配置RestTemplateBuilder
並添加支持MockRestServiceServer
。應使用value
或components
屬性指定要測試的特定bean @RestClientTest
:
@RunWith(SpringRunner.class) @RestClientTest(RemoteVehicleDetailsService.class) public class ExampleRestClientTest { @Autowired 私有 RemoteVehicleDetailsService服務; @Autowired 私有 MockRestServiceServer服務器; @Test public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() 拋出異常{ this .server.expect(requestTo( 「/ greet / details」)) .andRespond(withSuccess(「hello」,MediaType.TEXT_PLAIN)); String greeting = this .service.callRestService(); 斷言(問候).isEqualTo(「你好」); } }
A list of the auto-configuration that is enabled by @RestClientTest
can be found in the appendix.
The @AutoConfigureRestDocs
annotation can be used if you want to use Spring REST Docs in your tests. It will automatically configure MockMvc
to use Spring REST Docs and remove the need for Spring REST Docs' JUnit rule.
import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(UserController.class) @AutoConfigureRestDocs public class UserDocumentationTests { @Autowired private MockMvc mvc; @Test public void listUsers() throws Exception { this.mvc.perform(get("/users").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()) .andDo(document("list-users")); } }
@AutoConfigureRestDocs
can be used to override the default output directory (target/generated-snippets
if you are using Maven or build/generated-snippets
if you are using Gradle). It can also be used to configure the host, scheme, and port that will appear in any documented URIs. If you require more control over Spring REST Docs' configuration a RestDocsMockMvcConfigurationCustomizer
bean can be used:
@TestConfiguration static class CustomizationConfiguration implements RestDocsMockMvcConfigurationCustomizer { @Override public void customize(MockMvcRestDocumentationConfigurer configurer) { configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); } }
If you want to make use of Spring REST Docs' support for a parameterized output directory, you can create a RestDocumentationResultHandler
bean. The auto-configuration will call alwaysDo
with this result handler, thereby causing each MockMvc
call to automatically generate the default snippets:
@TestConfiguration static class ResultHandlerConfiguration { @Bean public RestDocumentationResultHandler restDocumentation() { return MockMvcRestDocumentation.document("{method-name}"); } }
If you wish to use Spock to test a Spring Boot application you should add a dependency on Spock’s spock-spring
module to your application’s build. spock-spring
integrates Spring’s test framework into Spock. It is recommended that you use Spock 1.1 or later to benefit from a number of recent improvements to Spock’s Spring Framework and Spring Boot integration. Please refer to the documentation for Spock’s Spring module for further details.
A few test utility classes are packaged as part of spring-boot
that are generally useful when testing your application.
ConfigFileApplicationContextInitializer
is an ApplicationContextInitializer
that can apply to your tests to load Spring Boot application.properties
files. You can use this when you don’t need the full features provided by @SpringBootTest
.
@ContextConfiguration(classes = Config.class,
initializers = ConfigFileApplicationContextInitializer.class)
Using |
EnvironmentTestUtils
allows you to quickly add properties to a ConfigurableEnvironment
or ConfigurableApplicationContext
. Simply call it withkey=value
strings:
EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot");
OutputCapture
is a JUnit Rule
that you can use to capture System.out
and System.err
output. Simply declare the capture as a @Rule
then use toString()
for assertions:
import org.junit.Rule;
import org.junit.Test; import org.springframework.boot.test.rule.OutputCapture; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class MyTest { @Rule public OutputCapture capture = new OutputCapture(); @Test public void testName() throws Exception { System.out.println("Hello World!"); assertThat(capture.toString(), containsString("World")); } }
TestRestTemplate
is a convenience alternative to Spring’s RestTemplate
that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case the template will behave in a test-friendly way by not throwing exceptions on server-side errors. It is recommended, but not mandatory, to use Apache HTTP Client (version 4.3.2 or better), and if you have that on your classpath the TestRestTemplate
will respond by configuring the client appropriately. If you do use Apache’s HTTP client some additional test-friendly features will be enabled:
TestRestTemplate
can be instantiated directly in your integration tests:
public class MyTest { private TestRestTemplate template = new TestRestTemplate(); @Test public void testRequest() throws Exception { HttpHeaders headers = template.getForEntity("http://myhost.com/example", String.class).getHeaders(); assertThat(headers.getLocation().toString(), containsString("myotherhost")); } }
Alternatively, if you are using the @SpringBootTest
annotation with WebEnvironment.RANDOM_PORT
or WebEnvironment.DEFINED_PORT
, you can just inject a fully configured TestRestTemplate
and start using it. If necessary, additional customizations can be applied via the RestTemplateBuilder
bean. Any URLs that do not specify a host and port will automatically connect to the embedded server:
@RunWith(SpringRunner.class) @SpringBootTest public class MyTest { @Autowired private TestRestTemplate template; @Test public void testRequest() throws Exception { HttpHeaders headers = template.getForEntity("/example", String.class).getHeaders(); assertThat(headers.getLocation().toString(), containsString("myotherhost")); } @TestConfiguration static class Config { @Bean public RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder() .additionalMessageConverters(...) .customizers(...); } } }
Spring Boot provides WebSockets auto-configuration for embedded Tomcat (8 and 7), Jetty 9 and Undertow. If you’re deploying a war file to a standalone container, Spring Boot assumes that the container will be responsible for the configuration of its WebSocket support.
Spring Framework provides rich WebSocket support that can be easily accessed via the spring-boot-starter-websocket
module.
Spring Boot provides Web Services auto-configuration so that all is required is defining your Endpoints
.
The Spring Web Services features can be easily accessed via the spring-boot-starter-webservices
module.
If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot.
自動配置能夠與「啓動器」相關聯,該「啓動器」提供自動配置代碼以及您將使用它的典型庫。咱們將首先介紹構建本身的自動配置所需的知識,而後咱們將繼續介紹建立自定義啓動器所需的 典型步驟。
能夠使用演示項目 來展現如何逐步建立啓動器。 |
在引擎蓋下,自動配置使用標準@Configuration
類實現。其餘@Conditional
註釋用於約束什麼時候應用自動配置。一般自動配置類使用@ConditionalOnClass
和@ConditionalOnMissingBean
註釋。這可確保自動配置僅在找到相關類時以及未聲明本身的類時應用@Configuration
。
您能夠瀏覽源代碼spring-boot-autoconfigure
以查看@Configuration
咱們提供的類(請參閱 META-INF/spring.factories
文件)。
Spring Boot會檢查META-INF/spring.factories
已發佈jar中是否存在文件。該文件應列出EnableAutoConfiguration
密鑰下的配置類 。
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \ com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\ com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration
若是須要按特定順序應用配置,則能夠使用 @AutoConfigureAfter
或 @AutoConfigureBefore
註釋。例如,若是您提供特定於Web的配置,則可能須要在以後應用您的類 WebMvcAutoConfiguration
。
若是您想訂購某些不該該彼此直接瞭解的自動配置,您也能夠使用@AutoconfigureOrder
。該註釋與常規註釋具備相同的語義,@Order
但爲自動配置類提供了專用順序。
自動配置,必須加載的方式只。確保它們在特定的包空間中定義,而且它們永遠不是組件掃描的目標。 |
您幾乎老是但願@Conditional
在自動配置類中包含一個或多個註釋。這@ConditionalOnMissingBean
是一個常見的示例,用於容許開發人員「覆蓋」自動配置,若是他們對您的默認值不滿意。
Spring Boot包含許多@Conditional
註釋,您能夠經過註釋@Configuration
類或單個@Bean
方法在本身的代碼中重用這些註釋。
The @ConditionalOnClass
and @ConditionalOnMissingClass
annotations allows configuration to be included based on the presence or absence of specific classes. Due to the fact that annotation metadata is parsed using ASM you can actually use the value
attribute to refer to the real class, even though that class might not actually appear on the running application classpath. You can also use the name
attribute if you prefer to specify the class name using a String
value.
If you are using |
The @ConditionalOnBean
and @ConditionalOnMissingBean
annotations allow a bean to be included based on the presence or absence of specific beans. You can use the value
attribute to specify beans by type, or name
to specify beans by name. The search
attribute allows you to limit the ApplicationContext
hierarchy that should be considered when searching for beans.
When placed on a @Bean
method, the target type defaults to the return type of the method, for instance:
@Configuration public class MyAutoConfiguration { @Bean @ConditionalOnMissingBean public MyService myService() { ... } }
In the example above, the myService
bean is going to be created if no bean of type MyService
is already contained in the ApplicationContext
.
You need to be very careful about the order that bean definitions are added as these conditions are evaluated based on what has been processed so far. For this reason, we recommend only using |
|
The @ConditionalOnProperty
annotation allows configuration to be included based on a Spring Environment property. Use the prefix
and name
attributes to specify the property that should be checked. By default any property that exists and is not equal to false
will be matched. You can also create more advanced checks using the havingValue
and matchIfMissing
attributes.
The @ConditionalOnResource
annotation allows configuration to be included only when a specific resource is present. Resources can be specified using the usual Spring conventions, for example, file:/home/user/test.dat
.
The @ConditionalOnWebApplication
and @ConditionalOnNotWebApplication
annotations allow configuration to be included depending on whether the application is a 'web application'. A web application is any application that is using a Spring WebApplicationContext
, defines a session
scope or has a StandardServletEnvironment
.
The @ConditionalOnExpression
annotation allows configuration to be included based on the result of a SpEL expression.
A full Spring Boot starter for a library may contain the following components:
autoconfigure
module that contains the auto-configuration code.starter
模塊提供對autoconfigure模塊以及庫的依賴關係以及一般有用的任何其餘依賴項。簡而言之,添加啓動器應該足以開始使用該庫。 若是您不須要將這兩個問題分開,則能夠將自動配置代碼和依賴關係管理組合在一個模塊中。 |
請確保爲您的啓動器提供適當的命名空間。spring-boot
即便您使用的是其餘Maven groupId,也不要使用它來啓動模塊名稱。咱們可能會爲您未來自動配置的內容提供官方支持。
這是一條經驗法則。假設您正在爲「acme」建立啓動器,將自動配置模塊acme-spring-boot-autoconfigure
和啓動器 命名爲acme-spring-boot-starter
。若是您只有一個模塊將二者合併,請使用 acme-spring-boot-starter
。
此外,若是您的啓動器提供配置密鑰,請爲它們使用適當的命名空間。特別是,不包括你在春天開機使用的命名空間(如按鍵 server
,management
,spring
,等)。這些是「咱們的」,咱們可能會在將來改進/修改它們,這樣可能會破壞你的東西。
確保 觸發元數據生成,以便爲您的密鑰提供IDE幫助。您可能但願查看生成的元數據(META-INF/spring-configuration-metadata.json
)以確保正確記錄您的密鑰。
autoconfigure模塊包含開始使用庫所需的全部內容。它還能夠包含配置鍵定義(@ConfigurationProperties
)和任何可用於進一步自定義組件初始化方式的回調接口。
您應該將庫的依賴項標記爲可選,以便您能夠更輕鬆地在項目中包含autoconfigure模塊。若是你這樣作,將不提供庫,默認狀況下Spring Boot將退回。 |
若是您想了解本節中討論的任何類的更多信息,能夠查看Spring Boot API文檔,也能夠直接瀏覽 源代碼。若是您有具體問題,請查看 操做方法部分。
If you are comfortable with Spring Boot’s core features, you can carry on and read about production-ready features.
Spring Boot includes a number of additional features to help you monitor and manage your application when it’s pushed to production. You can choose to manage and monitor your application using HTTP endpoints or with JMX. Auditing, health and metrics gathering can be automatically applied to your application.
Actuator HTTP endpoints are only available with a Spring MVC-based application. In particular, it will not work with Jersey unless you enable Spring MVC as well.
The spring-boot-actuator
module provides all of Spring Boot’s production-ready features. The simplest way to enable the features is to add a dependency to the spring-boot-starter-actuator
‘Starter’.
To add the actuator to a Maven based project, add the following ‘Starter’ dependency:
<dependencies>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies>
For Gradle, use the declaration:
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}
Actuator endpoints allow you to monitor and interact with your application. Spring Boot includes a number of built-in endpoints and you can also add your own. For example the health
endpoint provides basic application health information.
The way that endpoints are exposed will depend on the type of technology that you choose. Most applications choose HTTP monitoring, where the ID of the endpoint along with a prefix of /application
is mapped to a URL. For example, by default, the health
endpoint will be mapped to /application/health
.
The following technology agnostic endpoints are available:
ID | Description | Sensitive Default |
---|---|---|
|
Provides a hypermedia-based 「discovery page」 for the other endpoints. Requires Spring HATEOAS to be on the classpath. |
true |
|
Exposes audit events information for the current application. |
true |
|
Displays an auto-configuration report showing all auto-configuration candidates and the reason why they ‘were’ or ‘were not’ applied. |
true |
|
Displays a complete list of all the Spring beans in your application. |
true |
|
Displays a collated list of all |
true |
|
Performs a thread dump. |
true |
|
Exposes properties from Spring’s |
true |
|
Shows any Flyway database migrations that have been applied. |
true |
|
Shows application health information (when the application is secure, a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated). |
false |
|
Displays arbitrary application info. |
false |
|
Shows and modifies the configuration of loggers in the application. |
true |
|
Shows any Liquibase database migrations that have been applied. |
true |
|
Shows ‘metrics’ information for the current application. |
true |
|
Displays a collated list of all |
true |
|
Allows the application to be gracefully shutdown (not enabled by default). |
true |
|
Displays trace information (by default the last 100 HTTP requests). |
true |
If you are using Spring MVC, the following additional endpoints can also be used:
ID | Description | Sensitive Default |
---|---|---|
|
Displays documentation, including example requests and responses, for the Actuator’s endpoints. Requires |
false |
|
Returns a GZip compressed |
true |
|
Exposes JMX beans over HTTP (when Jolokia is on the classpath). |
true |
|
Returns the contents of the logfile (if |
true |
Depending on how an endpoint is exposed, the |
Endpoints can be customized using Spring properties. You can change if an endpoint is enabled
, if it is considered sensitive
and even its id
.
For example, here is an application.properties
that changes the sensitivity and id of the beans
endpoint and also enables shutdown
.
endpoints.beans.id=springbeans
endpoints.beans.sensitive=false endpoints.shutdown.enabled=true
The prefix ‟ |
By default, all endpoints except for shutdown
are enabled. If you prefer to specifically 「opt-in」 endpoint enablement you can use the endpoints.enabled
property. For example, the following will disable all endpoints except for info
:
endpoints.enabled=false
endpoints.info.enabled=true
Likewise, you can also choose to globally set the 「sensitive」 flag of all endpoints. By default, the sensitive flag depends on the type of endpoint (see the table above). For example, to mark all endpoints as sensitive except info
:
endpoints.sensitive=true
endpoints.info.sensitive=false
If endpoints.hypermedia.enabled
is set to true
and Spring HATEOAS is on the classpath (e.g. through the spring-boot-starter-hateoas
or if you are usingSpring Data REST) then the HTTP endpoints from the Actuator are enhanced with hypermedia links, and a 「discovery page」 is added with links to all the endpoints. The 「discovery page」 is available on /application
by default. It is implemented as an endpoint, allowing properties to be used to configure its path (endpoints.actuator.path
) and whether or not it is enabled (endpoints.actuator.enabled
).
When a custom management context path is configured, the 「discovery page」 will automatically move from /application
to the root of the management context. For example, if the management context path is /management
then the discovery page will be available from /management
.
若是HAL瀏覽器經過其webjar(org.webjars:hal-browser
)位於類路徑上,或者經過spring-data-rest-hal-browser
HAL瀏覽器的形式經過HTML「發現頁面」提供。
跨源資源共享 (CORS)是一種W3C規範,容許您以靈活的方式指定受權的跨域請求類型。Actuator的MVC端點能夠配置爲支持此類方案。
默認狀況下禁用CORS支持,而且僅endpoints.cors.allowed-origins
在設置了屬性後才啓用CORS支持 。下面許可的配置 GET
和POST
從電話example.com
域:
endpoints.cors.allowed-origins = http://example.com endpoints.cors.allowed-methods = GET,POST
檢查EndpointCorsProperties 以獲取完整的選項列表。 |
若是添加一個@Bean
類型Endpoint
,它將自動經過JMX和HTTP公開(若是有可用的服務器)。能夠經過建立類型的bean來進一步自定義HTTP端點MvcEndpoint
。您MvcEndpoint
不是,@Controller
但它能夠使用@RequestMapping
(和@Managed*
)來公開資源。
若是你這樣作是爲庫特徵考慮增長帶註釋的配置類 |
運行情況信息可用於檢查正在運行的應用程序的狀態。監視軟件常用它來提醒某人生產系統是否出現故障。health
端點公開的默認信息取決於訪問方式。對於安全應用程序中未經身份驗證的鏈接,將返回簡單的「狀態」消息,對於通過身份驗證的鏈接,還會顯示其餘詳細信息(有關HTTP詳細信息,請參見 第50.7節「HTTP健康端點格式和訪問限制」)。
健康信息是從HealthIndicator
您定義的全部bean中收集 的ApplicationContext
。Spring Boot包括一些自動配置 HealthIndicators
,你也能夠編寫本身的。默認狀況下,最終系統狀態是經過 基於有序狀態列表對HealthAggregator
每一個狀態進行排序來派生的HealthIndicator
。排序列表中的第一個狀態用做總體運行情況。若是否,則HealthIndicator
返回已知 HealthAggregator
的UNKNOWN
狀態,則使用狀態。
Information returned by HealthIndicators
is often somewhat sensitive in nature. For example, you probably don’t want to publish details of your database server to the world. For this reason, by default, only the health status is exposed over an unauthenticated HTTP connection. If you are happy for complete health information to always be exposed you can set endpoints.health.sensitive
to false
.
Health responses are also cached to prevent 「denial of service」 attacks. Use the endpoints.health.time-to-live
property if you want to change the default cache period of 1000 milliseconds.
The following HealthIndicators
are auto-configured by Spring Boot when appropriate:
Name | Description |
---|---|
Checks that a Cassandra database is up. |
|
Checks for low disk space. |
|
Checks that a connection to |
|
Checks that an Elasticsearch cluster is up. |
|
Checks that a JMS broker is up. |
|
Checks that a mail server is up. |
|
Checks that a Mongo database is up. |
|
Checks that a Rabbit server is up. |
|
Checks that a Redis server is up. |
|
Checks that a Solr server is up. |
It is possible to disable them all using the |
To provide custom health information you can register Spring beans that implement the HealthIndicator
interface. You need to provide an implementation of the health()
method and return a Health
response. The Health
response should include a status and can optionally include additional details to be displayed.
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down().withDetail("Error Code", errorCode).build(); } return Health.up().build(); } }
給定的標識符 |
除了Spring Boot的預約義Status
類型以外,還能夠Health
返回Status
表示新系統狀態的自定義。在這種狀況下,HealthAggregator
還須要提供接口的自定義實現,或者必須使用management.health.status.order
配置屬性配置默認實現。
例如,假設在您的某個實現中使用了 Status
帶代碼的新代碼。要配置嚴重性順序,請將如下內容添加到應用程序屬性中:FATAL
HealthIndicator
management.health.status.order = FATAL,DOWN,OUT_OF_SERVICE,UNKNOWN,UP
響應中的HTTP狀態代碼反映了總體運行情況(例如,UP
映射到200 OUT_OF_SERVICE
或DOWN
503)。HealthMvcEndpoint
若是經過HTTP訪問運行情況端點,您可能還但願註冊自定義狀態映射。例如,如下映射FATAL
到HttpStatus.SERVICE_UNAVAILABLE
:
endpoints.health.mapping.FATAL = 503
內置狀態的默認狀態映射是:
狀態 | 製圖 |
---|---|
下 |
SERVICE_UNAVAILABLE(503) |
中止服務 |
SERVICE_UNAVAILABLE(503) |
UP |
默認狀況下沒有映射,所以http狀態爲200 |
未知 |
默認狀況下沒有映射,所以http狀態爲200 |
應用程序信息公開從InfoContributor
您的中定義的全部bean 收集的各類信息 ApplicationContext
。Spring Boot包括一些自動配置 InfoContributors
,你也能夠編寫本身的。
InfoContributors
適當時,Spring Boot會自動配置如下內容:
名稱 | 描述 |
---|---|
從鑰匙 |
|
若是 |
|
若是 |
能夠使用 |
您能夠info
經過設置info.*
Spring屬性來自定義端點公開的數據。Environment
信息鍵下的全部屬性都將自動公開。例如,您能夠將如下內容添加到您的application.properties
:
info.app.encoding = UTF-8 info.app.java.source = 1.8 info.app.java.target = 1.8
您能夠在構建時擴展信息屬性,而不是對這些值進行硬編碼 。 假設您正在使用Maven,您能夠按以下方式重寫上面的示例: info.app.encoding =@project.build.sourceEncoding @ info.app.java.source =@java.version @ info.app.java.target =@java.version @ |
info
端點的另外一個有用功能是它可以git
在構建項目時發佈有關源代碼存儲庫狀態的信息。若是 GitProperties
豆可用,git.branch
,git.commit.id
和git.commit.time
屬性將被暴露出來。
若是要顯示完整的git信息(即完整內容 git.properties
),請使用如下management.info.git.mode
屬性:
management.info.git.mode =已滿
info
若是BuildProperties
bean可用,端點還能夠發佈有關構建的信息。若是META-INF/build-info.properties
類路徑中有文件可用,則會發生這種狀況。
要提供自定義應用程序信息,您能夠註冊實現該InfoContributor
接口的Spring bean 。
下面的示例提供了example
具備單個值的條目:
import java.util.Collections;
import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component 公共 類 ExampleInfoContributor實現 InfoContributor { @Override public void contribution(Info.Builder builder){ builder.withDetail(「example」, Collections.singletonMap(「key」,「value」)); } }
若是您點擊info
端點,您應該看到包含如下附加條目的響應:
{
「example」:{ 「key」:「value」 } }
If you are developing a Spring MVC application, Spring Boot Actuator will auto-configure all enabled endpoints to be exposed over HTTP. The default convention is to use the id
of the endpoint with a prefix of /application
as the URL path. For example, health
is exposed as /application/health
.
By default all sensitive HTTP endpoints are secured such that only users that have an ACTUATOR
role may access them. Security is enforced using the standardHttpServletRequest.isUserInRole
method.
Use the |
If you are deploying applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do this by changing the management.security.enabled
property:
application.properties.
management.security.enabled=false
By default, actuator endpoints are exposed on the same port that serves regular HTTP traffic. Take care not to accidentally expose sensitive information if you change the |
If you’re deploying applications publicly, you may want to add ‘Spring Security’ to handle user authentication. When ‘Spring Security’ is added, by default ‘basic’ authentication will be used with the username user
and a generated password (which is printed on the console when the application starts).
Generated passwords are logged as the application starts. Search for ‘Using default security password’. |
您能夠使用Spring屬性更改用戶名和密碼,以及更改訪問端點所需的安全角色。例如,您能夠在如下位置設置如下內容application.properties
:
security.user.name = admin security.user.password = secret management.security.roles = SUPERUSER
若是您的應用程序具備自定義安全配置,而且您但願無需身份驗證便可訪問全部執行器端點,則須要在安全配置中明確配置該端點。除此以外,您還須要將management.security.enabled
屬性更改爲false
。
若是您的自定義安全配置能夠保護您的執行器端點,則還須要確保通過身份驗證的用戶具備指定的角色