Spring Boot文檔

本文來自於springboot官方文檔

地址:https://docs.spring.io/spring-boot/docs/current/reference/html/css

Spring Boot參考指南

做者

菲利普· 韋伯戴夫 Syer約什 斯特凡 尼科爾羅布 絞車安迪· 威爾金森馬塞爾 Overdijk基督教 杜普伊斯塞巴斯蒂安· 德勒茲邁克爾· 西蒙斯韋德蘭Pavić

2.0.0.M3html

本文件的副本可供您本身使用和分發給他人,前提是您不對此類副本收取任何費用,而且每份副本均包含本版權聲明,不管是以印刷版仍是電子版分發。java


目錄node

I. Spring Boot文檔
1.關於文檔
2.得到幫助
3.第一步
4.使用Spring Boot
5.瞭解Spring Boot功能
6.轉向生產
7.高級主題
II。入門
8.介紹Spring Boot
9.系統要求
9.1。Servlet容器
10.安裝Spring Boot
10.1。Java開發人員的安裝說明
10.1.1。Maven安裝
10.1.2。Gradle安裝
10.2。安裝Spring Boot CLI
10.2.1。手動安裝
10.2.2。使用SDKMAN安裝!
10.2.3。OSX Homebrew安裝
10.2.4。MacPorts安裝
10.2.5。命令行完成
10.2.6。快速啓動Spring CLI示例
10.3。從早期版本的Spring Boot升級
11.開發您的第一個Spring Boot應用程序
11.1。建立POM
11.2。添加類路徑依賴項
11.3。編寫代碼
11.3.1。@RestController和@RequestMapping註釋
11.3.2。@EnableAutoConfiguration註釋
11.3.3。「主要」方法
11.4。運行示例
11.5。建立一個可執行jar
12.接下來要讀什麼
III。使用Spring Boot
13.構建系統
13.1。依賴管理
13.2。Maven的
13.2.1。繼承啓動父級
13.2.2。在沒有父POM的狀況下使用Spring Boot
13.2.3。使用Spring Boot Maven插件
13.3。搖籃
13.4。螞蟻
13.5。首發
14.構建代碼
14.1。使用「默認」包
14.2。找到主應用程序類
15.配置類
15.1。導入其餘配置類
15.2。導入XML配置
16.自動配置
16.1。逐漸取代自動配置
16.2。禁用特定的自動配置
17. Spring Beans和依賴注入
18.使用@SpringBootApplication批註
19.運行您的應用程序
19.1。從IDE運行
19.2。做爲打包應用程序運行
19.3。使用Maven插件
19.4。使用Gradle插件
19.5。熱交換
20.開發人員工具
20.1。屬性默認值
20.2。自動重啓
20.2.1。不包括資源
20.2.2。看着額外的路徑
20.2.3。禁用重啓
20.2.4。使用觸發器文件
20.2.5。自定義重啓類加載器
20.2.6。已知限制
20.3。LiveReload
20.4。全局設置
20.5。遠程應用
20.5.1。運行遠程客戶端應用程序
20.5.2。遠程更新
21.打包您的應用程序進行生產
22.接下來要讀什麼
IV。Spring Boot功能
23. SpringApplication
23.1。啓動失敗
23.2。自定義橫幅
23.3。自定義SpringApplication
23.4。流暢的構建器API
23.5。應用程序事件和偵聽器
23.6。網絡環境
23.7。訪問應用程序參數
23.8。使用ApplicationRunner或CommandLineRunner
23.9。申請退出
23.10。管理功能
24.外部化配置
24.1。配置隨機值
24.2。訪問命令行屬性
24.3。應用屬性文件
24.4。特定於配置文件的屬性
24.5。佔位符屬性
24.6。使用YAML代替Properties
24.6.1。加載YAML
24.6.2。在Spring環境中公開YAML做爲屬性
24.6.3。多個YAML文檔
24.6.4。YAML的缺點
24.6.5。合併YAML列表
24.7。類型安全的配置屬性
24.7.1。第三方配置
24.7.2。輕鬆綁定
24.7.3。屬性轉換
24.7.4。@ConfigurationProperties驗證
24.7.5。@ConfigurationProperties與@Value
25.簡介
25.1。添加活動配置文件
25.2。以編程方式設置配置
25.3。特定於配置文件的配置文件
26.記錄
26.1。日誌格式
26.2。控制檯輸出
26.2.1。彩色編碼輸出
26.3。文件輸出
26.4。日誌級別
26.5。自定義日誌配置
26.6。Logback擴展
26.6.1。特定於配置文件的配置
26.6.2。環境屬性
27.開發Web應用程序
27.1。'Spring Web MVC框架'
27.1.1。Spring MVC自動配置
27.1.2。HttpMessageConverters
27.1.3。自定義JSON序列化程序和反序列化程序
27.1.4。MessageCodesResolver的信息
27.1.5。靜態內容
27.1.6。自定義Favicon
27.1.7。ConfigurableWebBindingInitializer
27.1.8。模板引擎
27.1.9。錯誤處理
自定義錯誤頁面
映射Spring MVC以外的錯誤頁面
WebSphere Application Server上的錯誤處理
10年1月27日。春天的HATEOAS
11年1月27日。CORS支持
27.2。'Spring WebFlux框架'
27.2.1。Spring WebFlux自動配置
27.2.2。帶有HttpMessageReaders和HttpMessageWriters的HTTP編解碼器
27.2.3。靜態內容
27.2.4。模板引擎
27.3。JAX-RS和澤西島
27.4。嵌入式servlet容器支持
27.4.1。Servlet,過濾器和監聽器
將Servlet,過濾器和偵聽器註冊爲Spring bean
27.4.2。Servlet上下文初始化
掃描Servlet,過濾器和偵聽器
27.4.3。ServletWebServerApplicationContext
27.4.4。自定義嵌入式servlet容器
程序化定製
直接自定義ConfigurableServletWebServerFactory
27.4.5。JSP限制
28.安全
28.1。的OAuth2
28.1.1。受權服務器
28.1.2。資源服務器
28.2。令牌輸入用戶信息
28.3。自定義用戶信息RestTemplate
28.3.1。客戶
28.3.2。單點登陸
28.4。執行器安全
29.使用SQL數據庫
29.1。配置數據源
29.1.1。嵌入式數據庫支持
29.1.2。鏈接到生產數據庫
29.1.3。鏈接到JNDI數據源
29.2。使用JdbcTemplate
29.3。JPA和'Spring Data'
29.3.1。實體類
29.3.2。Spring Data JPA存儲庫
29.3.3。建立和刪除JPA數據庫
29.3.4。在View中打開EntityManager
29.4。使用H2的Web控制檯
29.4.1。更改H2控制檯的路徑
29.4.2。確保H2控制檯的安全
29.5。使用jOOQ
29.5.1。代碼生成
29.5.2。使用DSLContext
29.5.3。jOOQ SQL方言
29.5.4。自定義jOOQ
30.使用NoSQL技術
30.1。Redis的
30.1.1。鏈接到Redis
30.2。MongoDB的
30.2.1。鏈接到MongoDB數據庫
30.2.2。MongoTemplate
30.2.3。Spring Data MongoDB存儲庫
30.2.4。嵌入式Mongo
30.3。Neo4j的
30.3.1。鏈接到Neo4j數據庫
30.3.2。使用嵌入模式
30.3.3。Neo4jSession
30.3.4。Spring Data Neo4j存儲庫
30.3.5。存儲庫示例
30.4。的GemFire
30.5。Solr的
30.5.1。鏈接到Solr
30.5.2。Spring Data Solr存儲庫
30.6。Elasticsearch
30.6.1。使用Jest鏈接到Elasticsearch
30.6.2。使用Spring Data鏈接到Elasticsearch
30.6.3。Spring Data Elasticsearch存儲庫
30.7。卡桑德拉
30.7.1。鏈接到卡桑德拉
30.7.2。Spring Data Cassandra存儲庫
30.8。Couchbase
30.8.1。鏈接到Couchbase
30.8.2。Spring Data Couchbase存儲庫
30.9。LDAP
30.9.1。鏈接到LDAP服務器
30.9.2。Spring Data LDAP存儲庫
30.9.3。嵌入式內存LDAP服務器
30.10。InfluxDB
30.10.1。鏈接到InfluxDB
31.緩存
31.1。支持的緩存提供商
31.1.1。通用
31.1.2。JCache(JSR-107)
31.1.3。EhCache 2.x
31.1.4。Hazelcast
31.1.5。Infinispan的
31.1.6。Couchbase
31.1.7。Redis的
31.1.8。咖啡因
31.1.9。簡單
10年1月31日。沒有
32.消息傳遞
32.1。JMS
32.1.1。ActiveMQ支持
32.1.2。阿爾忒彌斯的支持
32.1.3。使用JNDI ConnectionFactory
32.1.4。發送消息
32.1.5。收到消息
32.2。AMQP
32.2.1。RabbitMQ支持
32.2.2。發送消息
32.2.3。收到消息
32.3。Apache Kafka支持
32.3.1。發送消息
32.3.2。收到消息
32.3.3。其餘Kafka Properties
33.使用'RestTemplate'調用REST服務
33.1。RestTemplate定製
34.使用'WebClient'調用REST服務
34.1。WebClient自定義
35.驗證
36.發送電子郵件
37.使用JTA的分佈式事務
37.1。使用Atomikos事務管理器
37.2。使用Bitronix事務管理器
37.3。使用Narayana事務管理器
37.4。使用Java EE託管事務管理器
37.5。混合XA和非XA JMS鏈接
37.6。支持替代嵌入式事務管理器
38. Hazelcast
39. Quartz Scheduler
40.春季整合
41.春季會議
42.對JMX的監督和管理
43.測試
43.1。測試範圍依賴性
43.2。測試Spring應用程序
43.3。測試Spring Boot應用程序
43.3.1。檢測測試配置
43.3.2。排除測試配置
43.3.3。使用隨機端口
43.3.4。嘲弄和間諜豆
43.3.5。自動配置的測試
43.3.6。自動配置的JSON測試
43.3.7。自動配置的Spring MVC測試
43.3.8。自動配置Spring WebFlux測試
43.3.9。自動配置的數據JPA測試
43.3.10。自動配置的JDBC測試
43.3.11。自動配置的jOOQ測試
43.3.12。自動配置的數據MongoDB測試
43.3.13。自動配置數據Neo4j測試
43.3.14。自動配置的Data Redis測試
43.3.15。自動配置的數據LDAP測試
43.3.16。自動配置的REST客戶端
43.3.17。自動配置的Spring REST Docs測試
43.3.18。使用Spock測試Spring Boot應用程序
43.4。測試工具
43.4.1。ConfigFileApplicationContextInitializer
43.4.2。EnvironmentTestUtils
43.4.3。OutputCapture
43.4.4。TestRestTemplate
44. WebSockets
45.網絡服務
46.建立本身的自動配置
46.1。瞭解自動配置的bean
46.2。找到自動配置候選項
46.3。條件註釋
46.3.1。班級條件
46.3.2。豆條件
46.3.3。物業條件
46.3.4。資源條件
46.3.5。Web應用程序條件
46.3.6。SpEL表達條件
46.4。建立本身的啓動器
46.4.1。命名
46.4.2。自動配置模塊
46.4.3。入門模塊
47.接下來要讀什麼
V.彈簧啓動執行器:生產就緒功能
48.啓用生產就緒功能
49.終點
49.1。自定義端點
49.2。用於執行器MVC端點的超媒體
49.3。CORS支持
49.4。添加自定義端點
49.5。健康信息
49.6。HealthIndicators的安全性
49.6.1。自動配置的HealthIndicators
49.6.2。編寫自定義HealthIndicators
49.7。應用信息
49.7.1。自動配置的InfoContributors
49.7.2。自定義應用信息信息
49.7.3。Git提交信息
49.7.4。創建信息
49.7.5。編寫自定義InfoContributors
50.經過HTTP監控和管理
50.1。訪問敏感端點
50.2。自定義管理端點路徑
50.3。自定義管理服務器端口
50.4。配置特定於管理的SSL
50.5。自定義管理服務器地址
50.6。禁用HTTP端點
50.7。HTTP健康端點格式和訪問限制
51.對JMX的監督和管理
51.1。自定義MBean名稱
51.2。禁用JMX端點
51.3。經過HTTP使用Jolokia for JMX
51.3.1。定製Jolokia
51.3.2。禁用Jolokia
記錄器
52.1。配置記錄器
53.度量標準
53.1。系統指標
53.2。DataSource指標
53.3。緩存指標
53.4。Tomcat會話指標
53.5。記錄您本身的指標
53.6。添加您本身的公共指標
53.7。指標編寫者,出口者和聚合
53.7.1。示例:導出到Redis
53.7.2。示例:導出到Open TSDB
53.7.3。示例:導出到Statsd
53.7.4。示例:導出到JMX
53.8。彙總來自多個來源的指標
53.9。Dropwizard指標
53.10。消息通道集成
54.審計
55.追查
55.1。自定義跟蹤
56.進程監測
56.1。擴展配置
56.2。編程
57. Cloud Foundry支持
57.1。禁用擴展的Cloud Foundry執行器支持
57.2。Cloud Foundry自簽名證書
57.3。自定義安全配置
58.接下來要讀什麼
VI。部署Spring Boot應用程序
59.部署到雲端
59.1。Cloud Foundry
59.1.1。綁定服務
59.2。Heroku的
59.3。OpenShift
59.4。亞馬遜網絡服務(AWS)
59.4.1。AWS Elastic Beanstalk
使用Tomcat平臺
使用Java SE平臺
最佳作法
59.4.2。摘要
59.5。Boxfuse和亞馬遜網絡服務
59.6。谷歌雲
60.安裝Spring Boot應用程序
60.1。支持的操做系統
60.2。Unix / Linux服務
60.2.1。做爲init.d服務安裝(系統V)
保護init.d服務
60.2.2。做爲systemd服務安裝
60.2.3。自定義啓動腳本
在編寫腳本時自定義腳本
運行時自定義腳本
60.3。Microsoft Windows服務
61.接下來要讀什麼
七。Spring Boot CLI
62.安裝CLI
63.使用CLI
63.1。使用CLI運行應用程序
63.1.1。推斷「抓住」依賴
63.1.2。推斷「抓住」座標
63.1.3。默認導入語句
63.1.4。自動主要方法
63.1.5。自定義依賴管理
63.2。具備多個源文件的應用程序
63.3。打包您的應用程序
63.4。初始化一個新項目
63.5。使用嵌入式shell
63.6。添加CLI擴展
64.使用Groovy bean DSL開發應用程序
65.使用settings.xml配置CLI
66.接下來要讀什麼
八。構建工具插件
67. Spring Boot Maven插件
67.1。包括插件
67.2。打包可執行jar和war文件
68. Spring Boot Gradle插件
69. Spring Boot AntLib模塊
69.1。Spring Boot Ant任務
69.1.1。春季啓動:exejar
69.1.2。例子
69.2。春季啓動:findmainclass
69.2.1。例子
70.支持其餘構建系統
70.1。從新打包檔案
70.2。嵌套庫
70.3。尋找一個主要的課程
70.4。從新打包實施示例
71.接下來要讀什麼
IX。'如何'指南
72. Spring Boot應用程序
72.1。建立本身的FailureAnalyzer
72.2。排除自動配置故障
72.3。在啓動以前自定義Environment或ApplicationContext
72.4。構建ApplicationContext層次結構(添加父或根上下文)
72.5。建立非Web應用程序
73.屬性和配置
73.1。在構建時自動擴展屬性
73.1.1。使用Maven自動擴展屬性
73.1.2。使用Gradle自動擴展屬性
73.2。外化SpringApplication的配置
73.3。更改應用程序的外部屬性的位置
73.4。使用'short'命令行參數
73.5。使用YAML做爲外部屬性
73.6。設置活動的Spring配置文件
73.7。根據環境更改配置
73.8。發現外部屬性的內置選項
74.嵌入式Web服務器
74.1。使用其餘Web服務器
74.2。配置Jetty
74.3。嚮應用程序添加Servlet,過濾器或監聽器
74.3.1。使用Spring bean添加Servlet,Filter或Listener
禁用Servlet或Filter的註冊
74.3.2。使用類路徑掃描添加Servlet,過濾器和偵聽器
74.4。更改HTTP端口
74.5。使用隨機未分配的HTTP端口
74.6。在運行時發現HTTP端口
74.7。配置SSL
74.8。配置訪問日誌記錄
74.9。在前端代理服務器後面使用
74.9.1。自定義Tomcat的代理配置
74.10。配置Tomcat
74.11。使用Tomcat啓用多個鏈接器
74.12。使用Tomcat的LegacyCookieProcessor
74.13。配置Undertow
74.14。使用Undertow啓用多個偵聽器
74.15。使用@ServerEndpoint建立WebSocket端點
74.16。啓用HTTP響應壓縮
75. Spring MVC
75.1。編寫JSON REST服務
75.2。編寫XML REST服務
75.3。自定義Jackson ObjectMapper
75.4。自定義@ResponseBody渲染
75.5。處理多部分文件上載
75.6。關閉Spring MVC DispatcherServlet
75.7。關閉默認MVC配置
75.8。自定義ViewResolvers
76. HTTP客戶端
76.1。配置RestTemplate以使用代理
77.記錄
77.1。配置Logback以進行日誌記錄
77.1.1。配置僅文件輸出的回溯
77.2。配置Log4j進行日誌記錄
77.2.1。使用YAML或JSON配置Log4j 2
78.數據訪問
78.1。配置自定義DataSource
78.2。配置兩個DataSource
78.3。使用Spring Data存儲庫
78.4。從Spring配置中分離@Entity定義
78.5。配置JPA屬性
78.6。配置Hibernate命名策略
78.7。使用自定義EntityManagerFactory
78.8。使用兩個EntityManagers
78.9。使用傳統的persistence.xml
78.10。使用Spring Data JPA和Mongo存儲庫
78.11。將Spring Data存儲庫公開爲REST端點
78.12。配置JPA使用的組件
79.數據庫初始化
79.1。使用JPA初始化數據庫
79.2。使用Hibernate初始化數據庫
79.3。使用Spring JDBC初始化數據庫
79.4。初始化Spring Batch數據庫
79.5。使用更高級別的數據庫遷移工具
79.5.1。在啓動時執行Flyway數據庫遷移
79.5.2。在啓動時執行Liquibase數據庫遷移
80.消息傳遞
80.1。禁用事務處理的JMS會話
81.批量申請
81.1。在啓動時執行Spring Batch做業
82.執行器
82.1。更改執行器端點的HTTP端口或地址
82.2。自定義「whitelabel」錯誤頁面
82.3。執行器和澤西島
83.安全
83.1。關閉Spring Boot安全配置
83.2。更改AuthenticationManager並添加用戶賬戶
83.3。在代理服務器後面運行時啓用HTTPS
84.熱插拔
84.1。從新加載靜態內容
84.2。從新加載模板而不從新啓動容器
84.2.1。Thymeleaf模板
84.2.2。FreeMarker模板
84.2.3。Groovy模板
84.3。快速應用程序重啓
84.4。從新加載Java類,而無需從新啓動容器
85.創建
85.1。生成構建信息
85.2。生成git信息
85.3。自定義依賴項版本
85.4。使用Maven建立可執行JAR
85.5。使用Spring Boot應用程序做爲依賴項
85.6。可執行jar運行時提取特定庫
85.7。使用排除項建立不可執行的JAR
85.8。遠程調試使用Maven啓動的Spring Boot應用程序
85.9。不使用spring-boot-antlib從Ant構建可執行歸檔文件
86.傳統部署
86.1。建立可部署的war文件
86.2。爲舊的servlet容器建立可部署的war文件
86.3。將現有應用程序轉換爲Spring Boot
86.4。將WAR部署到WebLogic
86.5。在舊(Servlet 2.5)容器中部署WAR
86.6。使用生菜而不是Jedis
X.附錄
A.常見應用程序屬性
B.配置元數據
B.1。元數據格式
B.1.1。組屬性
B.1.2。屬性屬性
B.1.3。提示屬性
B.1.4。重複的元數據項
B.2。提供手動提示
B.2.1。價值提示
B.2.2。價值提供者
任何
類參考
處理爲
記錄器名稱
Spring bean引用
Spring配置文件名稱
B.3。使用註釋處理器生成您本身的元數據
B.3.1。嵌套屬性
B.3.2。添加其餘元數據
C.自動配置類
C.1。來自「spring-boot-autoconfigure」模塊
C.2。來自「彈簧 - 啓動 - 執行器」模塊
D.測試自動配置註釋
E.可執行jar格式
E.1。嵌套的JAR
E.1.1。可執行jar文件結構
E.1.2。可執行的war文件結構
E.2。Spring Boot的「JarFile」類
E.2.1。與標準Java「JarFile」的兼容性
E.3。啓動可執行jar
E.3.1。啓動器清單
E.3.2。爆炸檔案
E.4。PropertiesLauncher功能
E.5。可執行jar限制
E.5.1。Zip條目壓縮
E.5.2。系統類加載器
E.6。替代單罐解決方案
F.依賴版本

第一部分Spring Boot文檔

 

本節簡要概述了Spring Boot參考文檔。將其視爲文檔其他部分的映射。您能夠以線性方式閱讀本參考指南,或者若是您不感興趣,能夠跳過章節。mysql

1.關於文檔

Spring Boot參考指南以html, pdf 和epub文檔的形式提供。最新的副本可在docs.spring.io/spring-boot/docs/current/reference上找到react

本文件的副本可供您本身使用和分發給他人,前提是您不對此類副本收取任何費用,而且每份副本均包含本版權聲明,不管是以印刷版仍是電子版分發。jquery

2.得到幫助

遇到Spring Boot問題,咱們想幫忙!nginx

[注意]

全部Spring Boot都是開源的,包括文檔!若是您發現文檔有問題; 或者若是你只是想改進它們,請參與其中git

3.第一步

若是您剛剛開始使用Spring Boot,或者通常來講 「Spring」,那麼 這就是開始的地方!

4.使用Spring Boot

準備好開始使用Spring Boot了嗎?咱們已經爲您提供保障

5.瞭解Spring Boot功能

須要有關Spring Boot核心功能的更多細節? 這是給你的

6.轉向生產

當您準備好將Spring Boot應用程序推向生產時,咱們有 一些您可能喜歡的技巧

7.高級主題

最後,咱們爲更高級的用戶提供了一些主題。

第二部分。入門

 

若是您剛開始使用Spring Boot,或者通常來講是「Spring」,那麼這就是您的選擇!在這裏,咱們回答基本的「什麼?」,「如何?」和「爲何?」的問題。您將找到Spring Boot的簡要介紹以及安裝說明。而後咱們將構建咱們的第一個Spring Boot應用程序,討論一些核心原則。

8.介紹Spring Boot

Spring Boot能夠輕鬆建立獨立的,生產級的基於Spring的應用程序,您能夠「運行」。咱們對Spring平臺和第三方庫採起了自覺得是的觀點,所以您能夠儘可能少開始。大多數Spring Boot應用程序只須要不多的Spring配置。

您能夠使用Spring Boot建立能夠使用java -jar 或更多傳統戰爭部署啓動的Java應用程序咱們還提供了一個運行「spring腳本」的命令行工具。

咱們的主要目標是:

  • 爲全部Spring開發提供從根本上更快且可普遍訪問的入門體驗。
  • 開箱即用,但隨着需求開始偏離默認值而迅速擺脫困境。
  • 提供大類項目常見的一系列非功能性功能(例如嵌入式服務器,安全性,指標,運行情況檢查,外部化配置)。
  • 絕對沒有代碼生成,也不須要XML配置。

9.系統要求

Spring Boot 2.0.0.M3須要Java 8和Spring Framework 5.0.0.RC3或更高版本。爲Maven(3.2+)和Gradle 3(3.4或更高版本)提供顯式構建支持。

9.1 Servlet容器

開箱即用支持如下嵌入式servlet容器:

名稱 Servlet版本

Tomcat 8.5

3.1

碼頭9.4

3.1

承諾1.3

3.1

您還能夠將Spring Boot應用程序部署到任何Servlet 3.0+兼容容器。

10.安裝Spring Boot

Spring Boot能夠與「經典」Java開發工具一塊兒使用,也能夠做爲命令行工具安裝。不管如何,您將須要Java SDK v1.8或更高版本。您應該在開始以前檢查當前的Java安裝:

$ java -version

If you are new to Java development, or if you just want to experiment with Spring Boot you might want to try the Spring Boot CLI first, otherwise, read on for 「classic」 installation instructions.

10.1 Installation instructions for the Java developer

You can use Spring Boot in the same way as any standard Java library. Simply include the appropriate spring-boot-*.jar files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor; and there is nothing special about a Spring Boot application, so you can run and debug as you would any other Java program.

Although you could just copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).

10.1.1 Maven installation

Spring Boot is compatible with Apache Maven 3.2 or above. If you don’t already have Maven installed you can follow the instructions at maven.apache.org.

[小費]

On many operating systems Maven can be installed via a package manager. If you’re an OSX Homebrew user try brew install maven. Ubuntu users can run sudo apt-get install maven. Windows users with Chocolatey can run choco install maven from an elevated prompt.

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-starter-parent是使用Spring Boot的好方法,但它可能並不適合全部時間。有時您可能須要從不一樣的父POM繼承,或者您可能不喜歡咱們的默認設置。有關使用 範圍的替代解決方案,請參見 第13.2.2節「在沒有父POM的狀況下使用Spring Boot」import

10.1.2 Gradle安裝

Spring Boot與Gradle 3(3.4或更高版本)兼容。若是您還沒有安裝Gradle,則能夠按照www.gradle.org/上的說明進行操做

Spring Boot依賴項能夠使用org.springframework.boot group一般,您的項目將聲明依賴於一個或多個 「Starters」Spring Boot提供了一個有用的Gradle插件 ,可用於簡化依賴聲明和建立可執行jar。

這是一個典型的build.gradle文件:

buildscript {
    存儲庫{
        jcenter()
        maven {url'http ://repo.spring.io/snapshot' } maven {url'http ://repo.spring.io/milestone' } } 依賴{ classpath'org.springframework.boot :spring-boot-gradle-plugin:2.0.0.M3' } }  apply plugin:' java'apply plugin:'org.springframework.boot'apply plugin:'io.spring.dependency-management'  jar { baseName = 'myproject'version = '0.0.1-SNAPSHOT' }  存儲庫{ jcenter() maven {url 「http://repo.spring.io/snapshot」 } maven {url 「http://repo.spring.io/milestone」 } }  依賴{ 編譯(「org.springframework.boot:spring-boot-starter-web」 testCompile(「org.springframework.boot:spring-boot-starter-test」 }

10.2安裝Spring Boot CLI

Spring Boot CLI是一個命令行工具,若是您想快速使用Spring進行原型設計,能夠使用它。它容許您運行Groovy腳本,這意味着您有一個熟悉的相似Java的語法,沒有太多的樣板代碼。

您不須要使用CLI來使用Spring Boot,但它絕對是實現Spring應用程序的最快方法。

10.2.1手動安裝

您能夠從Spring軟件庫下載Spring CLI發行版:

還提供最早進的快照分發

下載完成後,請按照 解壓縮的存檔中INSTALL.txt說明進行操做。總結:文件中的目錄中有一個spring腳本(spring.bat對於Windows),或者您也能夠使用文件(腳本能夠幫助您確保正確設置類路徑)。bin/.zipjava -jar.jar

10.2.2使用SDKMAN安裝!

SDKMAN!(軟件開發工具包管理器)可用於管理各類二進制SDK的多個版本,包括Groovy和Spring Boot CLI。獲取SDKMAN!來自sdkman.io並安裝Spring Boot

$ sdk install springboot
$ spring --version
Spring Boot v2.0.0.M3

若是您正在爲CLI開發功能並但願輕鬆訪問剛構建的版本,請遵循這些額外說明。

$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.0.0.M3-bin/spring-2.0.0.M3/
$ sdk默認springboot dev
$ spring --version
Spring CLI v2.0.0.M3

這將安裝一個spring名爲dev實例的本地實例。它指向您的目標構建位置,所以每次重建Spring Boot時,spring都將是最新的。

你能夠經過這樣作看到它:

$ sdk ls springboot

================================================== ==============================
可用的Springboot版本
================================================== ==============================
> + dev
* 2.0.0.M3

================================================== ==============================
+  - 本地版本
*  - 已安裝
>  - 目前正在使用中
================================================== ==============================

10.2.3 OSX Homebrew安裝

若是您使用的是Mac並使用Homebrew,那麼安裝Spring Boot CLI所須要作的就是:

$ brew tap pivotal / tap
$ brew install springboot

Homebrew將安裝spring/usr/local/bin

[注意]

若是您沒有看到公式,那麼您的brew安裝可能已過期。只需執行brew update並再試一次。

10.2.4安裝MacPorts

若是您使用的是Mac並使用MacPorts,那麼安裝Spring Boot CLI所須要作的就是:

$ sudo port install spring-boot-cli

10.2.5命令行完成

Spring Boot CLI附帶了爲BASH和 zsh shell 提供命令完成的腳本 您能夠在任何shell中建立source腳本(也稱爲 spring),或者將其放在我的或系統範圍的bash完成初始化中。在Debian系統上,系統範圍的腳本都在,/shell-completion/bash 而且當新shell啓動時,該目錄中的全部腳本都會被執行。要手動運行腳本,例如,若是已使用SDKMAN安裝!

$。〜/ .sdkman /候選人/ springboot /電流/殼完成/慶典/彈簧
$ spring <HIT TAB HERE>
  抓住幫助jar運行測試版
[注意]

若是使用Homebrew或MacPorts安裝Spring Boot CLI,命令行完成腳本將自動註冊到shell。

10.2.6快速啓動Spring CLI示例

這是一個很是簡單的Web應用程序,可用於測試您的安裝。建立一個名爲的文件app.groovy

@RestController
 ThisWillActuallyRun {

    @RequestMapping( 「/」) String home(){
        「你好,世界!」 }  }

而後只需從shell運行它:

$ spring run app.groovy
[注意]

首次運行應用程序時須要一些時間,由於下載了依賴項。後續運行會更快。

在您喜歡的Web瀏覽器中打開localhost:8080,您應該看到如下輸出:

你好,世界!

10.3從早期版本的Spring Boot升級

若是要從早期版本的Spring Boot升級,請檢查項目維基上託管的「發行說明」 您將找到升級說明以及每一個版本的「新的和值得注意的」功能列表。

要升級現有CLI安裝,請使用相應的軟件包管理器命令(例如brew upgrade),或者,若是手動安裝CLI,請按照 標準說明記住更新PATH環境變量以刪除任何舊引用。

11.開發您的第一個Spring Boot應用程序

讓咱們用Java開發一個簡單的「Hello World!」Web應用程序,它突出了一些Spring Boot的主要功能。咱們將使用Maven來構建這個項目,由於大多數IDE都支持它。

[小費]

spring.io網站包含使用Spring的引導許多「入門」指南。若是你想解決一個特定的問題; 先檢查那裏。

您能夠經過轉到start.spring.ioweb從依賴關係搜索器中選擇 啓動器來快捷執行如下步驟這將自動生成一個新的項目結構,以便您能夠當即開始編碼查看文檔以獲取更多詳細信息

在開始以前,打開終端以檢查您是否安裝了有效的Java和Maven版本。

$ java -version
java版「1.8.0_102」
Java(TM)SE運行時環境(版本1.8.0_102-b14)
Java HotSpot(TM)64位服務器VM(版本25.102-b14,混合模式)
$ mvn -v
Apache Maven 3.3.9(bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47 + 00:00)
Maven home:/usr/local/Cellar/maven/3.3.9/libexec
Java版本:1.8.0_102,供應商:Oracle Corporation
[注意]

此示例須要在其本身的文件夾中建立。後續說明假定您已建立合適的文件夾,而且它是您的「當前目錄」。

11.1建立POM

咱們須要從建立Maven pom.xml文件開始。pom.xml是用於構建項目的配方。打開您喜歡的文本編輯器並添加如下內容:

<?xml version =「1.0」encoding =「UTF-8」?> 
<project xmlns = 「http://maven.apache.org/POM/4.0.0」 xmlns:xsi = 「http://www.w3 .org / 2001 / XMLSchema-instance「 xsi:schemaLocation = 」http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd「 > <modelVersion> 4.0.0 </ modelVersion> <groupId> com.example </ groupId> <artifactId> myproject </ artifactId> <version> 0.0.1-SNAPSHOT </ version> <parent> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.0.0.M3 </ version> </ parent> <! - 這裏要添加的其餘行...... - > <! - (若是您使用的是.RELEASE版本,則不須要此項) - > <repositories> <repository> <id> spring-snapshots </ id> <url> http://repo.spring。 io / snapshot </ url> <snapshots> <enabled> true </ enabled> </ snapshots> </ repository> <repository> <id> spring-milestones </ id> <url> http://repo.spring。 io / milestone </ url> </ repository> </ repositories> <pluginRepositories> <pluginRepository> <id> spring-snapshots </ id> <url> http://repo.spring.io/snapshot </ url> </ pluginRepository> <pluginRepository> <id> spring-milestones </ id> <url> http://repo.spring.io/milestone </ url> </ pluginRepository> </ pluginRepositories> </ project>

這應該給你一個工做的構建,你能夠經過運行測試它mvn package(你能夠忽略「jar將是空的 - 沒有內容被標記爲包含!」警告如今)。

[注意]

此時,您能夠將項目導入IDE(大多數現代Java IDE包含對Maven的內置支持)。爲簡單起見,咱們將繼續爲此示例使用純文本編輯器。

11.2添加類路徑依賴項

Spring Boot提供了許多「Starters」,能夠輕鬆地將jar添加到類路徑中。咱們的示例應用程序已經spring-boot-starter-parentparentPOM部分中使用過 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.xmlspring-boot-starter-web在該parent部分下面添加依賴項

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

若是mvn dependency:tree再次運行,您將看到如今有許多其餘依賴項,包括Tomcat Web服務器和Spring Boot自己。

11.3編寫代碼

要完成咱們的應用程序,咱們須要建立一個Java文件。Maven將src/main/java默認編譯源代碼,所以您須要建立該文件夾結構,而後添加一個名爲的文件src/main/java/Example.java

import org.springframework.boot。*; import org.springframework.boot.autoconfigure。*; import org.springframework.stereotype。*; import org.springframework.web.bind.annotation。*; @RestController  @EnableAutoConfiguration 公共 示例{ @RequestMapping( 「/」) String home(){ 返回 「Hello World!」 ; } public static void main(String [] args)throws Exception { SpringApplication.run(例如.class,args); }  }

雖然這裏的代碼很少,但仍是有不少代碼。讓咱們逐步完成重要部分。

11.3.1 @RestController和@RequestMapping註釋

咱們Example班上的第一個註釋@RestController這被稱爲 構造型註釋。它爲閱讀代碼的人提供了提示,對於Spring,該類扮演着特定的角色。在這種狀況下,咱們的類是一個Web,@Controller因此Spring在處理傳入的Web請求時會考慮它。

@RequestMapping註釋提供「路由」的信息。它告訴Spring,任何帶有路徑「/」的HTTP請求都應該映射到該home方法。該 @RestController註解告訴Spring使獲得的字符串直接返回給調用者。

[小費]

@RestController@RequestMapping註解是Spring MVC的註解(他們並非專門針對春季啓動)。有關更多詳細信息,請參閱Spring參考文檔中MVC部分

11.3.2 @EnableAutoConfiguration註釋

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to 「guess」 how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.

11.3.3 The 「main」 method

The final part of our application is the main method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication class by calling runSpringApplication will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server. We need to pass Example.class as an argument to the run method to tell SpringApplication which is the primary Spring component. The args array is also passed through to expose any command-line arguments.

11.4 Running the example

At this point our application should work. Since we have used the spring-boot-starter-parent POM we have a useful run goal that we can use to start the application. Type mvn spring-boot:run from the root project directory to start the application:

$ mvn spring-boot:run
____ _ __ _ _
 / \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
(()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \ \\ / ___)| | _)| | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / /
 ========= | _ | ============== | ___ / = / _ / _ / _ /
 :: Spring Boot ::(v2.0.0.M3) .......  ....... (此處輸出日誌) ....... 
........ 2.222秒啓動示例(JVM運行6.514)

若是您打開到localhost:8080的Web瀏覽器,您應該看到如下輸出:

你好,世界!

要優雅地退出應用程序命中ctrl-c

11.5建立可執行jar

讓咱們經過建立一個徹底自包含的可執行jar文件來完成咱們的示例,咱們能夠在生產中運行它。可執行jar(有時稱爲「fat jar」)是包含已編譯類以及代碼須要運行的全部jar依賴項的歸檔。

要建立一個可執行jar,咱們須要添加spring-boot-maven-plugin到咱們的 pom.xml在該dependencies部分正下方插入如下行

<build> 
    <plugins> <plugin> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build>
[注意]

所述spring-boot-starter-parentPOM包括<executions>配置以結合repackage目標。若是您不使用父POM,則須要本身聲明此配置。有關詳細信息,請參閱插件文檔

保存pom.xml並從命令行運行mvn package

$ mvn包

[INFO]掃描項目......
[信息]
[INFO] ----------------------------------------------- -------------------------
[INFO]構建myproject 0.0.1-SNAPSHOT
[INFO] ----------------------------------------------- -------------------------
[INFO] ....
[INFO] --- maven-jar-plugin:2.4:jar(default-jar)@ myproject ---
[INFO]構建jar:/Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[信息]
[INFO] --- spring-boot-maven-plugin:2.0.0.M3:從新打包(默認)@ myproject ---
[INFO] ----------------------------------------------- -------------------------
[信息]創建成功
[INFO] ----------------------------------------------- -------------------------

若是你查看target目錄,你應該看到myproject-0.0.1-SNAPSHOT.jar該文件大小應爲10 MB左右。若是你想偷看內部,你能夠使用jar tvf

$ jar tvf target / myproject-0.0.1-SNAPSHOT.jar

您還應該看到目錄中命名myproject-0.0.1-SNAPSHOT.jar.original 的文件小得多target這是Maven在Spring Boot從新打包以前建立的原始jar文件。

要運行該應用程序,請使用如下java -jar命令:

$ java -jar target / myproject-0.0.1-SNAPSHOT.jar
____ _ __ _ _
 / \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
(()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \ \\ / ___)| | _)| | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / /
 ========= | _ | ============== | ___ / = / _ / _ / _ /
 :: Spring Boot ::(v2.0.0.M3) .......  ....... (此處輸出日誌) ....... 
........ 2.536秒啓動示例(JVM運行2.864)

和之前同樣,優雅地退出應用程序命中ctrl-c

12.接下來要讀什麼

但願本節爲您提供了一些Spring Boot基礎知識,並幫助您編寫本身的應用程序。若是您是面向任務的開發人員類型,您可能須要跳轉到spring.io並查看一些 入門指南,這些指南解決了具體的「如何使用Spring執行此操做」問題; 咱們還有Spring Boot特定 的操做方法參考文檔。

春季啓動庫也有 一堆樣品能夠運行。樣本獨立於其他代碼(即您無需構建其他代碼來運行或使用示例)。

不然,下一個邏輯步驟是閱讀第III部分「使用Spring Boot」若是你真的不耐煩,你也能夠跳過去閱讀 Spring Boot功能

第三部分。使用Spring Boot

 

本節詳細介紹瞭如何使用Spring Boot。它涵蓋了諸如構建系統,自動配置以及如何運行應用程序等主題。咱們還介紹了一些Spring Boot最佳實踐。雖然Spring Boot沒有什麼特別之處(它只是你能夠使用的另外一個庫),但有一些建議,若是遵循這些建議,將使您的開發過程更容易一些。

若是您剛剛開始使用Spring Boot,那麼在深刻了解本節以前,您應該閱讀「 入門指南」

13.構建系統

強烈建議您選擇支持依賴關係管理的構建系統 ,而且能夠使用發佈到「Maven Central」存儲庫的工件。咱們建議您選擇Maven或Gradle。可讓Spring Boot與其餘構建系統(例如Ant)一塊兒工做,但它們不會獲得特別好的支持。

13.1依賴管理

每一個版本的Spring Boot都提供了它支持的依賴項的精選列表。實際上,您不須要爲構建配置中的任何這些依賴項提供版本,由於Spring Boot正在爲您管理這些依賴項。當您升級Spring Boot時,這些依賴項也將以一致的方式升級。

[注意]

You can still specify a version and override Spring Boot’s recommendations if you feel that’s necessary.

The curated list contains all the spring modules that you can use with Spring Boot as well as a refined list of third party libraries. The list is available as a standard Bills of Materials (spring-boot-dependencies) that can be used with both Maven and Gradle.

[警告]

Each release of Spring Boot is associated with a base version of the Spring Framework so we highly recommend you to not specify its version on your own.

13.2 Maven

Maven users can inherit from the spring-boot-starter-parent project to obtain sensible defaults. The parent project provides the following features:

  • Java 1.8 as the default compiler level.
  • UTF-8 source encoding.
  • Dependency Management section, allowing you to omit <version> tags for common dependencies, inherited from the spring-boot-dependencies POM.
  • Sensible resource filtering.
  • Sensible plugin configuration (exec pluginsurefireGit commit IDshade).
  • Sensible resource filtering for 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).

13.2.1 Inheriting the starter parent

To configure your project to inherit from the spring-boot-starter-parent simply set the parent:

<!-- Inherit defaults from Spring Boot -->
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.M3</version> </parent>
[注意]

You should only need to specify the Spring Boot version number on this dependency. If you import additional starters, you can safely omit the version number.

With that setup, you can also override individual dependencies by overriding a property in your own project. For instance, to upgrade to another Spring Data release train you’d add the following to your pom.xml.

<properties>
    <spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version> </properties>
[小費]

Check the spring-boot-dependencies pom for a list of supported properties.

13.2.2 Using Spring Boot without the parent POM

Not everyone likes inheriting from the spring-boot-starter-parent POM. You may have your own corporate standard parent that you need to use, or you may just prefer to explicitly declare all your Maven configuration.

If you don’t want to use the spring-boot-starter-parent, you can still keep the benefit of the dependency management (but not the plugin management) by using a scope=import dependency:

<dependencyManagement>
     <dependencies> <dependency> <!-- Import dependency management from Spring Boot --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.0.0.M3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>

That setup does not allow you to override individual dependencies using a property as explained above. To achieve the same result, you’d need to add an entry in thedependencyManagement of your project before the spring-boot-dependencies entry. For instance, to upgrade to another Spring Data release train you’d add the following to your pom.xml.

<dependencyManagement> 
    <dependencies> <! - 覆蓋Spring Boot提供的Spring Data版本系列 - > <dependency> <groupId> org.springframework.data </ groupId> <artifactId> spring-data-releasetrain </ artifactId> < version> Fowler-SR2 </ version> <scope> import </ scope> <type> pom </ type> </ dependency> <dependency> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot -dependencies </ artifactId> <version>2.0.0.M3 </ version> <type> pom</ type> <scope> import </ scope> </ dependency> </ dependencies> </ dependencyManagement>
[注意]

在上面的示例中,咱們指定了BOM,可是能夠經過這種方式覆蓋任何依賴關係類型。

13.2.3使用Spring Boot Maven插件

Spring Boot包含一個Maven插件 ,能夠將項目打包爲可執行jar。<plugins> 若是要使用它,請將插件添加到您的部分:

<build> 
    <plugins> <plugin> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build>
[注意]

若是使用Spring Boot啓動程序父pom,則只需添加插件,除非要更改父項中定義的設置,不然無需對其進行配置。

13.3 Gradle

要了解如何將Spring Boot與Gradle一塊兒使用,請參閱Spring Boot的Gradle插件的文檔:

13.4螞蟻

能夠使用Apache Ant + Ivy構建Spring Boot項目。該 spring-boot-antlib「的antlib」模塊還能夠幫助螞蟻建立可執行的JAR文件。

要聲明依賴項,典型ivy.xml文件將以下所示:

<ivy-module  version = 「2.0」 > <info organization = 「org.springframework.boot」 module = 「spring-boot-sample-ant」 /> <configurations> <conf name = 「compile」 description = 「所需的一切編譯此模塊「 /> <conf name = 」runtime「 extends = 」compile「 description = 」運行此模塊所需的一切「 /> </ configurations> <dependencies> <依賴 org =「org.springframework.boot」 name = 「spring-boot-starter」 rev = 「$ {spring-boot.version}」 conf = 「compile」 /> </ dependencies> </ ivy-module>

典型的build.xml看起來像這樣:

<project 
    xmlns:ivy = 「antlib:org.apache.ivy.ant」 xmlns:spring-boot = 「antlib:org.springframework.boot.ant」 name = 「myapp」 default = 「build」 > <property name = 「spring-boot.version」 value = 「1.3.0.BUILD-SNAPSHOT」 /> <target name = 「resolve」 description = 「 - >使用常春藤檢索依賴關係」 > <ivy:retrieve pattern = 「lib / [conf] / [artifact] - [type] - [revision]。[ext]」 /> </目標> <target name = 「classpaths」 depends = 「resolve」 > <path id = 「compile.classpath」 > <fileset dir = 「lib / compile」 includes = 「* .jar」 /> </ path> </ target> <target name = 「init」 depends = 「classpaths」 > <mkdir dir = 「build / classes」 /> </ target> <target name = 「compile」 depends = 「init」 description = 「compile」 > <javac srcdir = 「src / main / java」 destdir = 「build / classes」 classpathref = 「compile.classpath」 /> </ target> <target name = 「build」 depends = 「compile」 > <spring-boot:exejar destfile = 「build / myapp.jar」 classes = 「build / classes」 > <spring-boot:lib> <fileset dir = 「lib / runtime「 /> </ spring-boot:lib> </ spring-boot:exejar> </ target> </ project>
[小費]

若是您不想使用該模塊請參見第85.9節「從Ant構建可執行存檔而不使用spring-boot-antlib」 「操做方法」 spring-boot-antlib

13.5初學者

啓動器是一組方便的依賴關係描述符,您能夠在應用程序中包含這些描述符。您能夠得到所需的全部Spring和相關技術的一站式服務,而無需搜索示例代碼並複製粘貼的依賴描述符。例如,若是您想開始使用Spring和JPA進行數據庫訪問,只需spring-boot-starter-data-jpa在項目中包含依賴項,就能夠了

啓動器包含許多依賴項,這些依賴項是使項目快速啓動和運行所需的依賴項,以及一組受支持的託管傳遞依賴項。

如下應用程序啓動程序由Spring Boot在org.springframework.boot下提供 

Table 13.1. Spring Boot application starters

Name Description Pom

spring-boot-starter

Core starter, including auto-configuration support, logging and YAML

Pom

spring-boot-starter-activemq

Starter for JMS messaging using Apache ActiveMQ

Pom

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ

Pom

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ

Pom

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

Pom

spring-boot-starter-batch

Starter for using Spring Batch

Pom

spring-boot-starter-cache

Starter for using Spring Framework’s caching support

Pom

spring-boot-starter-cloud-connectors

Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku

Pom

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

Pom

spring-boot-starter-data-cassandra-reactive

Starter for using Cassandra distributed database and Spring Data Cassandra Reactive

Pom

spring-boot-starter-data-couchbase

Starter for using Couchbase document-oriented database and Spring Data Couchbase

Pom

spring-boot-starter-data-elasticsearch

Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch

Pom

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

Pom

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

Pom

spring-boot-starter-data-mongodb

Starter for using MongoDB document-oriented database and Spring Data MongoDB

Pom

spring-boot-starter-data-mongodb-reactive

Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive

Pom

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

Pom

spring-boot-starter-data-redis

Starter for using Redis key-value data store with Spring Data Redis and the Jedis client

Pom

spring-boot-starter-data-redis-reactive

Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client

Pom

spring-boot-starter-data-rest

Starter for exposing Spring Data repositories over REST using Spring Data REST

Pom

spring-boot-starter-data-solr

Starter for using the Apache Solr search platform with Spring Data Solr

Pom

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views

Pom

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

Pom

spring-boot-starter-hateoas

Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS

Pom

spring-boot-starter-integration

Starter for using Spring Integration

Pom

spring-boot-starter-jdbc

Starter for using JDBC with the Tomcat JDBC connection pool

Pom

spring-boot-starter-jersey

Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web

Pom

spring-boot-starter-jooq

Starter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc

Pom

spring-boot-starter-jta-atomikos

Starter for JTA transactions using Atomikos

Pom

spring-boot-starter-jta-bitronix

Starter for JTA transactions using Bitronix

Pom

spring-boot-starter-jta-narayana

Spring Boot Narayana JTA Starter

Pom

spring-boot-starter-mail

Starter for using Java Mail and Spring Framework’s email sending support

Pom

spring-boot-starter-mobile

Starter for building web applications using Spring Mobile

Pom

spring-boot-starter-mustache

Starter for building web applications using Mustache views

Pom

spring-boot-starter-quartz

Spring Boot Quartz Starter

Pom

spring-boot-starter-security

Starter for using Spring Security

Pom

spring-boot-starter-social-facebook

Starter for using Spring Social Facebook

Pom

spring-boot-starter-social-linkedin

Stater for using Spring Social LinkedIn

Pom

spring-boot-starter-social-twitter

Starter for using Spring Social Twitter

Pom

spring-boot-starter-test

Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito

Pom

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views

Pom

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator

Pom

spring-boot-starter-web

Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container

Pom

spring-boot-starter-web-services

Starter for using Spring Web Services

Pom

spring-boot-starter-webflux

Starter for building WebFlux applications using Spring Framework’s Reactive Web support

Pom

spring-boot-starter-websocket

Starter for building WebSocket applications using Spring Framework’s WebSocket support

Pom


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

spring-boot-starter-actuator

Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application

Pom


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

spring-boot-starter-jetty

Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat

Pom

spring-boot-starter-json

Starter for reading and writing json

Pom

spring-boot-starter-log4j2

Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging

Pom

spring-boot-starter-logging

Starter for logging using Logback. Default logging starter

Pom

spring-boot-starter-reactor-netty

Starter for using Reactor Netty as the embedded reactive HTTP server.

Pom

spring-boot-starter-tomcat

Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web

Pom

spring-boot-starter-undertow

Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat

Pom


[小費]

有關其餘社區的列表貢獻首先,看 README文件中 spring-boot-startersGitHub上的模塊。

14.構建代碼

Spring Boot不須要任何特定的代碼佈局,可是,有一些最佳實踐能夠提供幫助。

14.1使用「默認」包

當一個類不包含package聲明時,它被認爲是在「默認包」中。一般不鼓勵使用「默認包」,應該避免使用。這可能會致使使用Spring的啓動應用程序的特殊問題@ComponentScan@EntityScan@SpringBootApplication註解,由於從每個罐子每個類,將被讀取。

[小費]

咱們建議您遵循Java推薦的包命名約定並使用反向域名(例如,com.example.project)。

14.2找到主應用程序類

咱們一般建議您將主應用程序類放在其餘類之上的根包中。@EnableAutoConfiguration註解每每放在你的主類,它隱含地定義爲某些項目一基地「搜索包」。例如,若是您正在編寫JPA應用程序,@EnableAutoConfiguration則將使用帶註釋的類的包 來搜索@Entity項目。

使用根包還容許使用@ComponentScan註釋而無需指定basePackage屬性。@SpringBootApplication若是主類位於根包中,也能夠使用 註釋。

這是一個典型的佈局:

COM
 +  - 例子
     +  -  myproject
         +  -  Application.java
         |
         +  - 域名 | + - Customer.java | + - CustomerRepository.java
         |
         +  - 服務 | + - CustomerService.java
         |
         +  - 網絡
             +  -  CustomerController.java

Application.java文件將聲明該main方法以及基本方法 @Configuration

package com.example.myproject;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration  @EnableAutoConfiguration  @ComponentScan  public class Application { public static void main(String [] args){ SpringApplication.run(Application.class, args); } }

15. Configuration classes

Spring Boot favors Java-based configuration. Although it is possible to use SpringApplication with an XML sources, we generally recommend that your primary source is a single @Configuration class. Usually the class that defines the main method is also a good candidate as the primary @Configuration.

[小費]

Many Spring configuration examples have been published on the Internet that use XML configuration. Always try to use the equivalent Java-based configuration if possible. Searching for Enable* annotations can be a good starting point.

15.1 Importing additional configuration classes

You don’t need to put all your @Configuration into a single class. The @Import annotation can be used to import additional configuration classes. Alternatively, you can use @ComponentScan to automatically pick up all Spring components, including @Configuration classes.

15.2 Importing XML configuration

If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration class. You can then use an additional @ImportResource annotation to load XML configuration files.

16. Auto-configuration

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDBis 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 @Configurationclasses.

[小費]

You should only ever add one @EnableAutoConfiguration annotation. We generally recommend that you add it to your primary @Configuration class.

16.1 Gradually replacing auto-configuration

Auto-configuration is noninvasive, at any point you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own DataSource bean, the default embedded database support will back away.

If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug switch. This will enable debug logs for a selection of core loggers and log an auto-configuration report to the console.

16.2禁用特定的自動配置

若是您發現正在應用您不想要的特定自動配置類,則能夠使用exclude屬性@EnableAutoConfiguration來禁用它們。

import org.springframework.boot.autoconfigure。*; import org.springframework.boot.autoconfigure.jdbc。*; import org.springframework.context.annotation。*; @Configuration  @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})  public class MyConfiguration { }

若是類不在類路徑上,則能夠使用excludeName註釋屬性並指定徹底限定名稱。最後,您還能夠控制要經過spring.autoconfigure.exclude屬性排除的自動配置類列表 

[小費]

您能夠在註釋級別和使用屬性定義排除項。

17. Spring Beans和依賴注入

您能夠自由地使用任何標準的Spring Framework技術來定義bean及其注入的依賴項。爲簡單起見,咱們常常發現使用@ComponentScan 找到你的bean,結合@Autowired構造函數注入效果很好。

若是按照上面的建議構建代碼(在根包中定位應用程序類),則能夠添加@ComponentScan不帶任何參數的代碼。您的全部應用程序組件(的@Component@Service@Repository@Controller等)將自動註冊爲春豆。

下面是一個示例@ServiceBean,它使用構造函數注入來獲取所需的RiskAssessorbean。

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; } // ...  }
[小費]

請注意使用構造函數注入如何將riskAssessor字段標記爲final,表示沒法隨後更改。

18.使用@SpringBootApplication批註

許多春季引導開發者老是有其主類註解爲@Configuration, @EnableAutoConfiguration@ComponentScan因爲這些註釋常常一塊兒使用(特別是若是您遵循 上面最佳實踐),Spring Boot提供了一個方便的@SpringBootApplication替代方案。

@SpringBootApplication註解至關於使用@Configuration, @EnableAutoConfiguration@ComponentScan與他們的默認屬性:

package com.example.myproject;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication  //與@Configuration相同@EnableAutoConfiguration @ComponentScan public class Application { public static void main(String [] args){ SpringApplication.run(Application .class,args); }  }
[注意]

@SpringBootApplication還提供了別名定製的屬性 @EnableAutoConfiguration@ComponentScan

19.運行您的應用程序

將應用程序打包爲jar並使用嵌入式HTTP服務器的最大優點之一是,您能夠像運行任何其餘應用程序同樣運行應用程序。調試Spring Boot應用程序也很容易; 您不須要任何特殊的IDE插件或擴展。

[注意]

本節僅介紹基於jar的打包,若是選擇將應用程序打包爲war文件,則應參閱服務器和IDE文檔。

19.1從IDE運行

您能夠從IDE運行Spring Boot應用程序做爲簡單的Java應用程序,可是,首先您須要導入項目。導入步驟將根據您的IDE和構建系統而有所不一樣。大多數IDE能夠直接導入Maven項目,例如Eclipse用戶能夠菜單中選擇Import…​→ Existing Maven ProjectsFile

若是沒法將項目直接導入IDE,則能夠使用構建插件生成IDE元數據。Maven包含Eclipse和 IDEA的插件 Gradle提供各類IDE的插件

[小費]

若是您不當心運行Web應用程序兩次,您將看到「端口已在使用中」錯誤。STS用戶能夠使用該Relaunch按鈕而不是Run確保關閉任何現有實例。

19.2做爲打包應用程序運行

若是您使用Spring Boot Maven或Gradle插件來建立可執行jar,則能夠使用它來運行您的應用程序java -jar例如:

$ java -jar target / myproject-0.0.1-SNAPSHOT.jar

也能夠運行啓用了遠程調試支持的打包應用程序。這容許您將調試器附加到打包的應用程序:

$ java -Xdebug -Xrunjdwp:server = y,transport = dt_socket,address = 8000,suspend = n \
       -jar target / myproject-0.0.1-SNAPSHOT.jar

19.3使用Maven插件

Spring Boot Maven插件包含一個run可用於快速編譯和運行應用程序的目標。應用程序以分解形式運行,就像在IDE中同樣。

$ mvn spring-boot:run

您可能還想使用有用的操做系統環境變量:

$ export MAVEN_OPTS = -Xmx1024m

19.4使用Gradle插件

Spring Boot Gradle插件還包含一個bootRun任務,可用於以爆炸形式運行您的應用程序。bootRun每當你應用的任務添加org.springframework.bootjava插件:

$ gradle bootRun

您可能還想使用此有用的操做系統環境變量:

$ export JAVA_OPTS = -Xmx1024m

19.5熱插拔

因爲Spring Boot應用程序只是普通的Java應用程序,所以JVM熱交換應該是開箱即用的。JVM熱交換在某種程度上受限於它能夠替換的字節碼,由於能夠使用更完整的解決方案 JRebel該 spring-boot-devtools模塊還包括對快速應用程序重啓的支持。

有關詳細信息,請參閱下面的第20章「 開發人員工具」部分和 熱交換「操做方法」

20.開發人員工具

Spring Boot包含一組額外的工具,能夠使應用程序開發體驗更加愉快。spring-boot-devtools模塊能夠包含在任何項目中,以提供額外的開發時間功能。要包含devtools支持,只需將模塊依賴項添加到您的構建:

Maven的。 

<dependencies> 
    <dependency> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-devtools </ artifactId> <optional> true </ optional> </ dependency> </ dependencies>

 

搖籃。 

依賴{
    compile(「org.springframework.boot:spring-boot-devtools」 }

 

[注意]

運行徹底打包的應用程序時會自動禁用開發人員工具。若是您的應用程序是使用啓動的,java -jar或者若是它是使用特殊的類加載器啓動的,那麼它將被視爲「生產應用程序」。將依賴項標記爲可選是防止devtools使用您的項目傳遞應用於其餘模塊的最佳實踐。Gradle不支持optional 開箱即用的依賴項,所以您可能但願propdeps-plugin在此期間查看 

[小費]

從新打包的歸檔默認狀況下不包含devtools。若是要使用 某些遠程devtools功能,則須要禁用 excludeDevtoolsbuild屬性以包含它。該屬性由Maven和Gradle插件支持。

20.1財產違約

Several of the libraries supported by Spring Boot use caches to improve performance. For example, template engines will cache compiled templates to avoid repeatedly parsing template files. Also, Spring MVC can add HTTP caching headers to responses when serving static resources.

Whilst caching is very beneficial in production, it can be counter productive during development, preventing you from seeing the changes you just made in your application. For this reason, spring-boot-devtools will disable those caching options by default.

Cache options are usually configured by settings in your application.properties file. For example, Thymeleaf offers the spring.thymeleaf.cache property. Rather than needing to set these properties manually, the spring-boot-devtools module will automatically apply sensible development-time configuration.

[小費]

For a complete list of the properties that are applied see DevToolsPropertyDefaultsPostProcessor.

20.2 Automatic restart

Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.

[注意]

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 (SpringApplication.setRegisterShutdownHook(false)).

[注意]

When deciding if an entry on the classpath should trigger a restart when it changes, DevTools automatically ignores projects named spring-bootspring-boot-devtoolsspring-boot-autoconfigurespring-boot-actuator, and spring-boot-starter.

[注意]

DevTools needs to customize the ResourceLoader used by the ApplicationContext: if your application provides one already, it is going to be wrapped. Direct override of the getResource method on the ApplicationContext is not supported.

20.2.1 Excluding resources

Certain resources don’t necessarily need to trigger a restart when they are changed. For example, Thymeleaf templates can just be edited in-place. By default changing resources in /META-INF/maven/META-INF/resources ,/resources ,/static ,/public or /templates will not trigger a restart but will trigger a live reload. If you want to customize these exclusions you can use the spring.devtools.restart.exclude property. For example, to exclude only /static and /public you would set the following:

spring.devtools.restart.exclude=static/**,public/**
[小費]

if you want to keep those defaults and add additional exclusions, use the spring.devtools.restart.additional-exclude property instead.

20.2.2 Watching additional paths

You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath. To do so, use thespring.devtools.restart.additional-paths property to configure additional paths to watch for changes. You can use the spring.devtools.restart.excludeproperty described above to control whether changes beneath the additional paths will trigger a full restart or just a live reload.

20.2.3 Disabling restart

If you don’t want to use the restart feature you can disable it using the spring.devtools.restart.enabled property. In most cases you can set this in yourapplication.properties (this will still initialize the restart classloader but it won’t watch for file changes).

If you need to completely disable restart support, for example, because it doesn’t work with a specific library, you need to set a System property before callingSpringApplication.run(…​). For example:

public static void main(String[] args) { System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(MyApp.class, args); }

20.2.4 Using a trigger file

若是使用不斷編譯已更改文件的IDE,則可能更喜歡僅在特定時間觸發從新啓動。爲此,您能夠使用「觸發器文件」,這是一個特殊文件,當您想要實際觸發從新啓動檢查時,必須對其進行修改。更改文件只會觸發檢查,只有在Devtools檢測到必須執行某些操做時纔會從新啓動。觸發器文件能夠手動更新,也能夠經過IDE插件更新。

要使用觸發器文件,請使用該spring.devtools.restart.trigger-file屬性。

[小費]

您可能但願將其設置spring.devtools.restart.trigger-file爲 全局設置,以便全部項目的行爲方式相同。

20.2.5自定義重啓類加載器

上面Restart vs Reload部分所述,使用兩個類加載器實現了重啓功能。對於大多數應用程序,此方法頗有效,但有時它可能會致使類加載問題。

默認狀況下,IDE中的任何打開項目都將使用「restart」類加載器加載,任何常規.jar文件都將使用「base」類加載器加載。若是您處理多模塊項目,而不是將每一個模塊導入IDE,則可能須要自定義項目。爲此,您能夠建立一個META-INF/spring-devtools.properties文件。

spring-devtools.properties文件能夠包含restart.exclude.和 restart.include.前綴屬性。include元素是應該被拉高到「重啓」的類加載器的項目,以及exclude要素是應該向下推入「基地」類加載器的項目。屬性的值是將應用於類路徑的正則表達式模式。

例如:

restart.exclude.companycommonlibs = / MyCorp的共用- [\\瓦特- ]。+ \罐子 restart.include.projectcommon = / MyCorp的-的Myproj - [\\瓦特- ]。+ \罐
[注意]

全部屬性鍵必須是惟一的。只要房產開始 restart.include.restart.exclude.將被考慮。

[小費]

META-INF/spring-devtools.properties將加載全部類路徑。您能夠將文件打包到項目中,也能夠打包在項目使用的庫中。

20.2.6已知限制

對於使用標準反序列化的對象,從新啓動功能不起做用ObjectInputStream若是你須要反序列化的數據,你可能須要使用Spring的ConfigurableObjectInputStream結合 Thread.currentThread().getContextClassLoader()

不幸的是,幾個第三方庫反序列化而不考慮上下文類加載器。若是您發現此類問題,則須要向原始做者請求修復。

20.3 LiveReload

spring-boot-devtools模塊包括一個嵌入式LiveReload服務器,可用於在更改資源時觸發瀏覽器刷新。LiveReload瀏覽器擴展程序可從livereload.com免費用於Chrome,Firefox和Safari 

若是您不想在應用程序運行時啓動LiveReload服務器,則能夠將spring.devtools.livereload.enabled屬性設置false

[注意]

您一次只能運行一個LiveReload服務器。在啓動應用程序以前,請確保沒有其餘LiveReload服務器正在運行。若是從IDE啓動多個應用程序,則只有第一個應用程序具備LiveReload支持。

20.4全局設置

您能夠經過添加一個文件名爲配置全局devtools設置 .spring-boot-devtools.properties你的$HOME文件夾(注意:文件名開頭「」)。添加到此文件的任何屬性都將應用於計算機上使用devtools的全部 Spring Boot應用程序。例如,要將restart配置爲始終使用觸發器文件,請添加如下內容:

〜/ .spring引導-devtools.properties。 

spring.devtools.reload.trigger-file = .reloadtrigger

 

20.5遠程應用程序

Spring Boot開發人員工具不只限於本地開發。遠程運行應用程序時,您還能夠使用多個功能。遠程支持是選擇加入,要啓用它,您須要確保它devtools包含在從新打包的存檔中:

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

而後你須要設置一個spring.devtools.remote.secret屬性,例如:

spring.devtools.remote.secret = mysecret
[警告]

spring-boot-devtools在遠程應用程序上啓用存在安全風險。您永遠不該該在生產部署上啓用支持。

遠程devtools支持分爲兩部分; 有一個接受鏈接的服務器端端點,以及在IDE中運行的客戶端應用程序。spring.devtools.remote.secret設置屬性後,將自動啓用服務器組件必須手動啓動客戶端組件。

20.5.1運行遠程客戶端應用程序

遠程客戶端應用程序旨在從IDE中運行。您須要org.springframework.boot.devtools.RemoteSpringApplication使用與要鏈接的遠程項目相同的類路徑運行 傳遞給應用程序非選項參數應該是您要鏈接的遠程URL。

例如,若是您使用的是Eclipse或STS,而且您有一個名爲my-app已部署到Cloud Foundry的項目,那麼您將執行如下操做:

  • 選擇Run Configurations…​Run菜單。
  • 建立一個新的Java Application「啓動配置」。
  • 瀏覽my-app項目。
  • org.springframework.boot.devtools.RemoteSpringApplication做主類。
  • 添加https://myapp.cfapps.ioProgram 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 spring.devtools.remote.secret property is read and passed to the server for authentication.

[小費]

It’s always advisable to use https:// as the connection protocol so that traffic is encrypted and passwords cannot be intercepted.

[小費]

If you need to use a proxy to access the remote application, configure the spring.devtools.remote.proxy.host and spring.devtools.remote.proxy.port properties.

20.5.2 Remote update

The remote client will monitor your application classpath for changes in the same way as the local restart. Any updated resource will be pushed to the remote application and (if required) trigger a restart. This can be quite helpful if you are iterating on a feature that uses a cloud service that you don’t have locally. Generally remote updates and restarts are much quicker than a full rebuild and deploy cycle.

[注意]

Files are only monitored when the remote client is running. If you change a file before starting the remote client, it won’t be pushed to the remote server.

21. Packaging your application for production

Executable jars can be used for production deployment. As they are self-contained, they are also ideally suited for cloud-based deployment.

For additional 「production ready」 features, such as health, auditing and metric REST or JMX end-points; consider adding spring-boot-actuator. See Part V, 「Spring Boot Actuator: Production-ready features」 for details.

22. What to read next

您如今應該很好地理解如何使用Spring Boot以及您應該遵循的一些最佳實踐。您如今能夠繼續深刻瞭解特定的 Spring Boot功能,或者您能夠跳過並閱讀Spring Boot 的「 生產就緒 」方面。

第四部分。Spring Boot功能

 

本節深刻介紹Spring Boot的詳細信息。在這裏,您能夠了解要使用和自定義的主要功能。若是您尚未,可能須要閱讀第II部分「入門」和 第III部分「使用Spring Boot」部分,以便您掌握基礎知識。

23. SpringApplication

SpringApplication類提供了一個方便的方式來引導,未來自啓動Spring應用程序main()的方法。在許多狀況下,您能夠委託靜態SpringApplication.run方法:

public  static void main(String [] args){ SpringApplication.run(MySpringConfiguration ,參數); }

當您的應用程序啓動時,您應該看到相似於如下內容:

____ _ __ _ _
 / \\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
(()\ ___ |'_ |'_ | |'_ \ / _` | \ \ \ \ \\ / ___)| | _)| | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __,| / / / / /
 ========= | _ | ============== | ___ / = / _ / _ / _ /
 :: Spring Boot :: v2.0.0.M3

2013-07-31 00:08:16.117 INFO 56603 --- [main] osbsapp.SampleApplication:在個人計算機上使用PID 56603啓動SampleApplication v0.1.0(/ apps / myapp.jar由pwebb啓動)
2013-07-31 00:08:16.166 INFO 56603 --- [main] ationConfigServletWebServerApplicationContext:刷新org.springframework.boot.web.ser vlet.context.AnnotationConfigServletWebServerApplicationContext @ 6e5a8246:啓動日期[Wed Jul 31 00:08:16 PDT 2013]; 上下文層次結構的根
2014-03-04 13:09:54.912 INFO 41370 --- [main] .t.TomcatServletWebServerFactory:服務器初始化端口:8080
2014-03-04 13:09:56.501 INFO 41370 --- [main] osbsapp.SampleApplication:在2.992秒內啓動SampleApplication(JVM運行3.658)

默認狀況下,INFO將顯示日誌消息,包括一些相關的啓動詳細信息,例如啓動應用程序的用戶。

23.1啓動失敗

若是您的應用程序沒法啓動,則已註冊FailureAnalyzers有機會提供專用錯誤消息和具體操做來解決問題。例如,若是您在端口上啓動Web應用程序8080而且該端口已在使用中,您應該看到相似於如下內容的內容:

***************************
應用程序未能啓動
***************************

描述:
 嵌入式servlet容器沒法啓動。8080端口已經投入使用。

行動:

識別並中止正在偵聽端口8080的進程或將此應用程序配置爲偵聽另外一個端口。
[注意]

Spring Boot提供了許多FailureAnalyzer實現,您能夠 很是輕鬆地添加本身的實現。

若是沒有故障分析器可以處理異常,您仍然能夠顯示完整的自動配置報告,以更好地瞭解出現了什麼問題。要作到這一點,你須要 使debug財產或 啓用DEBUG日誌記錄的 org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

例如,若是您使用的是運行應用程序,則java -jar能夠debug按以下方式啓用該 屬性:

$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug

23.2自定義橫幅

The banner that is printed on start up can be changed by adding a banner.txt file to your classpath, or by setting banner.location to the location of such a file. If the file has an unusual encoding you can set banner.charset (default is UTF-8). In addition to a text file, you can also add a banner.gifbanner.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

${application.version}

The version number of your application as declared in MANIFEST.MF. For exampleImplementation-Version: 1.0 is printed as 1.0.

${application.formatted-version}

MANIFEST.MF格式化顯示的應用程序的版本號(用括號括起來並帶有前綴v)。例如(v1.0)

${spring-boot.version}

您正在使用的Spring Boot版本。例如2.0.0.M3

${spring-boot.formatted-version}

您正在使用的Spring Boot版本用於顯示(用括號括起來並帶有前綴v)。例如(v2.0.0.M3)

${Ansi.NAME}(或${AnsiColor.NAME}${AnsiBackground.NAME}${AnsiStyle.NAME}

NAMEANSI轉義碼的名稱在哪裏詳情AnsiPropertySource請見。

${application.title}

您申請的標題MANIFEST.MF例如Implementation-Title: MyApp打印爲MyApp


[小費]

SpringApplication.setBanner(…​)若是要以編程方式生成橫幅,則能夠使用方法。使用org.springframework.boot.Banner界面並實現本身的printBanner()方法。

您還能夠使用該spring.main.banner-mode屬性來肯定是否必須使用配置的記錄器(打印System.outconsole),log或者根本不打印橫幅off)。

打印的橫幅將在名稱下注冊爲單個bean springBootBanner

[注意]

YAML映射off到,false所以若是要在應用程序中禁用橫幅,請確保添加引號。

spring main banner-mode「off」

23.3自定義SpringApplication

若是SpringApplication默認值不符合您的須要,您能夠建立一個本地實例並進行自定義。例如,要關閉您要寫的橫幅:

public  static void main(String [] args){ SpringApplication應用=  SpringApplication(MySpringConfiguration。); app.setBannerMode(Banner.Mode.OFF); app.run(參數); }
[注意]

傳遞給的構造函數參數SpringApplication是spring bean的配置源。在大多數狀況下,這些將是對@Configuration類的引用,但它們也能夠是對XML配置或應掃描的包的引用。

也能夠配置SpringApplication使用application.properties 文件。有關詳細信息請參見第24章,外部化配置

有關配置選項的完整列表,請參閱 SpringApplicationJavadoc

23.4 Fluent構建器API

若是您須要構建ApplicationContext層次結構(具備父/子關係的多個上下文),或者您只是喜歡使用'流暢'構建器API,則能夠使用SpringApplicationBuilder

SpringApplicationBuilder讓您鏈在一塊兒的多個方法調用,包括parentchild,讓您建立一個層次結構的方法。

例如:

新的 SpringApplicationBuilder() .sources(家長。 .child(申請。 .bannerMode(Banner.Mode.OFF) .RUN(參數);
[注意]

建立ApplicationContext層次結構時存在一些限制,例如,Web組件必須包含在子上下文中,而且相同的內容Environment 將用於父上下文和子上下文。有關詳細信息,請參閱 SpringApplicationBuilder Javadoc

23.5應用程序事件和監聽器

除了一般的Spring Framework事件以外,例如 ContextRefreshedEventSpringApplication發送一些額外的應用程序事件。

[注意]

某些事件實際上ApplicationContext是在建立以前觸發的,所以您沒法在這些事件上註冊偵聽器@Bean您能夠經過SpringApplication.addListeners(…​)SpringApplicationBuilder.listeners(…​) 方法註冊它們 

若是您但願自動註冊這些偵聽器而無論應用程序的建立方式如何,您能夠將META-INF/spring.factories文件添加到項目中並使用org.springframework.context.ApplicationListener 鍵引用偵聽器

org.springframework.context.ApplicationListener = com.example.project.MyListener

應用程序運行時,應按如下順序發送應用程序事件:

  1. 一個ApplicationStartingEvent是在一個運行開始發送,但除了聽衆和初始化的登記任何處理以前。
  2. 一個ApplicationEnvironmentPreparedEvent當被髮送Environment到在上下文已知被使用,可是在建立上下文以前。
  3. 一個ApplicationPreparedEvent被髮送刷新開始以前,但通過bean定義已經被加載。
  4. ApplicationReadyEvent在刷新以後發送一個而且已經處理了任何相關的回調以指示應用程序已準備好服務請求。
  5. 一個ApplicationFailedEvent若是在啓動時異常發送。
[小費]

您一般不須要使用應用程序事件,但知道它們存在可能很方便。在內部,Spring Boot使用事件來處理各類任務。

23.6 Web環境

SpringApplication將嘗試ApplicationContext表明您建立正確的類型默認狀況下,將使用AnnotationConfigApplicationContextAnnotationConfigServletWebServerApplicationContext將使用,具體取決於您是否正在開發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 setWebEnvironment(false) when using SpringApplication within a JUnit test.

23.7 Accessing application arguments

If you need to access the application arguments that were passed to SpringApplication.run(…​) you can inject aorg.springframework.boot.ApplicationArguments bean. The ApplicationArguments interface provides access to both the raw String[] arguments as well as parsed option and non-option arguments:

import org.springframework.boot.*
import org.springframework.beans.factory.annotation.* import org.springframework.stereotype.* @Component public class MyBean { @Autowired public MyBean(ApplicationArguments args) { boolean debug = args.containsOption("debug"); List<String> files = args.getNonOptionArgs(); // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] } }
[小費]

Spring Boot will also register a CommandLinePropertySource with the Spring Environment. This allows you to also inject single application arguments using the @Value annotation.

23.8 Using the ApplicationRunner or CommandLineRunner

If you need to run some specific code once the SpringApplication has started, you can implement the ApplicationRunner or CommandLineRunner interfaces. Both interfaces work in the same way and offer a single run method which will be called just before SpringApplication.run(…​) completes.

The CommandLineRunner interfaces provides access to application arguments as a simple string array, whereas the ApplicationRunner uses the ApplicationArguments interface discussed above.

import org.springframework.boot.*
import org.springframework.stereotype.* @Component public class MyBean implements CommandLineRunner { public void run(String... args) { // Do something... } }

You can additionally implement the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation if several CommandLineRunner or ApplicationRunner beans are defined that must be called in a specific order.

23.9 Application exit

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when SpringApplication.exit() is called. This exit code can then be passed to System.exit() to return it as a status code.

@SpringBootApplication
public class ExitCodeApplication { @Bean public ExitCodeGenerator exitCodeGenerator() { return () -> 42; } public static void main(String[] args) { System.exit(SpringApplication .exit(SpringApplication.run(ExitCodeApplication ,參數))); }  }

此外,ExitCodeGenerator能夠經過例外來實現接口。遇到這種異常時,Spring Boot將返回實現getExitCode()方法提供的退出代碼

23.10管理員功能

能夠經過指定spring.application.admin.enabled屬性爲應用程序啓用與管理相關的功能 這暴露 SpringApplicationAdminMXBean 了平臺MBeanServer您能夠使用此功能遠程管理Spring Boot應用程序。這對任何服務包裝器實現也頗有用。

[小費]

若是您想知道應用程序正在運行的HTTP端口,請使用密鑰獲取屬性local.server.port

[注意]

啓用此功能時要當心,由於MBean公開了一種關閉應用程序的方法。

24.外部化配置

Spring Boot容許您外部化配置,以便在不一樣環境中使用相同的應用程序代碼。您能夠使用屬性文件,YAML文件,環境變量和命令行參數來外部化配置。能夠使用@Value註釋將屬性值直接注入到bean中,經過Spring的Environment抽象訪問或 經過綁定到結構化對象@ConfigurationProperties

Spring Boot使用一種很是特殊的PropertySource順序,旨在容許合理地覆蓋值。按如下順序考慮屬性:

  1. Devtools 主目錄上的全局設置屬性~/.spring-boot-devtools.properties當devtools處於活動狀態時)。
  2. @TestPropertySource 你的測試註釋。
  3. @SpringBootTest#properties 測試中的註釋屬性。
  4. 命令行參數。
  5. 屬性SPRING_APPLICATION_JSON(嵌入在環境變量或系統屬性中的內聯JSON)
  6. ServletConfig init參數。
  7. ServletContext init參數。
  8. JNDI屬性來自java:comp/env
  9. Java系統屬性(System.getProperties())。
  10. OS環境變量。
  11. 一個RandomValuePropertySource只有屬性的random.*
  12. 打包jar以外的特定於配置文件的應用程序屬性application-{profile}.properties以及YAML變體)
  13. 打包在jar中的特定於配置文件的應用程序屬性application-{profile}.properties 和YAML變體)
  14. 打包jar以外的應用程序屬性(application.properties以及YAML變體)。
  15. 打包在jar中的應用程序屬性(application.properties和YAML變體)。
  16. @PropertySource 你的@Configuration上的註釋
  17. 默認屬性(使用指定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屬性能夠以環境變量在命令行上被供給。例如在UN * X shell中:

$ SPRING_APPLICATION_JSON ='{「foo」:{「bar」:「spam」}}'java -jar myapp.jar

在這個例子中,你將foo.bar=spam在Spring中 結束Environment您還能夠spring.application.json在System變量中提供JSON 

$ java -Dspring.application.json ='{「foo」:「bar」}'-jar myapp.jar

或命令行參數:

$ java -jar myapp.jar --spring.application.json ='{「foo」:「bar」}'

或者做爲JNDI變量java:comp/env/spring.application.json

24.1配置隨機值

RandomValuePropertySource對於注入隨機值(例如,進入祕密或測試用例)很是有用。它能夠產生整數,長整數,uuids或字符串,例如

my.secret = $ {random.value} my.number = $ {random.int} my.bignumber = $ {random.long} my.uuid = $ {random.uuid} my.number.less.than.ten = $ {random.int(10)} my.number.in.range = $ {random.int [1024,65536]}

random.int*語法是OPEN value (,max) CLOSE其中的OPEN,CLOSE任何字符和value,max是整數。若是max提供則value是最小值而且max是最大值(不包括)。

24.2訪問命令行屬性

默認狀況下,SpringApplication將任何命令行選項參數(以' - '開頭,例如--server.port=9000)轉換爲a property並將其添加到Spring Environment如上所述,命令行屬性始終優先於其餘屬性源。

若是您不但願將命令行屬性添加到Environment您能夠使用它們禁用它們SpringApplication.setAddCommandLineProperties(false)

24.3應用程序屬性文件

SpringApplication將從application.properties如下位置的文件加載屬性並將它們添加到Spring Environment

  1. 一個/config當前目錄下的子目錄。
  2. 當前目錄
  3. 一個classpath /config
  4. 類路徑根

列表按優先級排序(在列表中較高位置定義的屬性將覆蓋在較低位置中定義的屬性)。

[注意]

您還能夠使用YAML('。mil')文件替代'.properties'。

若是您不喜歡application.properties配置文件名,能夠經過指定spring.config.name環境屬性切換到另外一個您還能夠使用spring.config.locationenvironment屬性(以逗號分隔的目錄位置列表或文件路徑)來引用顯式位置

$ java -jar myproject.jar --spring.config.name = myproject

要麼

$ java -jar myproject.jar --spring.config.location = classpath:/default.properties,classpath:/override.properties
[警告]

spring.config.name而且spring.config.location很早就用它來肯定必須加載哪些文件,所以必須將它們定義爲環境屬性(一般是OS env,系統屬性或命令行參數)。

若是spring.config.location包含目錄(而不是文件),則它們應該以/(而且將附加spring.config.name在加載以前生成的名稱,包括特定於配置文件的文件名)附加指定的文件 spring.config.location按原樣使用,不支持特定於配置文件的變體,並將被任何特定於配置文件的屬性覆蓋。

以相反的順序搜索配置位置。默認狀況下,配置的位置是 classpath:/,classpath:/config/,file:./,file:./config/生成的搜索順序爲:

  1. file:./config/
  2. file:./
  3. classpath:/config/
  4. classpath:/

配置自定義配置位置時,除默認位置外,還會使用它們。在默認位置以前搜索自定義位置。例如,若是classpath:/custom-config/,file:./custom-config/配置了自定義位置,則搜索順序將變爲:

  1. file:./custom-config/
  2. classpath:custom-config/
  3. file:./config/
  4. file:./
  5. classpath:/config/
  6. 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. SPRING_CONFIG_NAME instead of spring.config.name).

[注意]

If you are running in a container then JNDI properties (in java:comp/env) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties.

24.4 Profile-specific properties

In addition to application.properties files, profile-specific properties can also be defined using the naming convention application-{profile}.properties. TheEnvironment has a set of default profiles (by default [default]) which are used if no active profiles are set (i.e. if no profiles are explicitly activated then properties from application-default.properties are loaded).

Profile-specific properties are loaded from the same locations as standard application.properties, with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.

If several profiles are specified, a last wins strategy applies. For example, profiles specified by the spring.profiles.active property are added after those configured via the SpringApplication API and therefore take precedence.

[注意]

若是您已指定任何文件spring.config.location,則不會考慮這些文件的特定配置文件的變體。spring.config.location若是您還想使用特定於配置文件的屬性,請使用目錄 

24.5佔位符屬性

當使用它們時,application.properties將經過現有過濾這些值,Environment以便您能夠返回先前定義的值(例如,從系統屬性)。

app.name = MyApp app.description = $ {app.name}是一個Spring Boot應用程序
[小費]

您還能夠使用此技術建立現有Spring Boot屬性的「短」變體。有關詳細信息,請參見第73.4節「使用'短'命令行參數」操做方法。

24.6使用YAML代替屬性

YAML是JSON的超集,所以是用於指定分層配置數據的很是方便的格式。SpringApplication課程將自動支持YAML做爲一種替代性,只要你有 SnakeYAML在classpath庫。

[注意]

若是您使用'Starters',將自動提供SnakeYAML spring-boot-starter

24.6.1加載YAML

Spring Framework提供了兩個方便的類,可用於加載YAML文檔。YamlPropertiesFactoryBean將加載YAML做爲Properties和 YamlMapFactoryBean將加載YAML做爲Map

例如,如下YAML文檔:

環境 dev url:http://dev.bar.com  名稱:Developer Setup  prod url:http://foo.bar.com  name:My Cool App

將轉化爲這些屬性:

environments.dev.url = http://dev.bar.com environments.dev.name =開發人員設置 environment.prod.url = http://foo.bar.com environments.prod.name =個人酷應用

YAML列表表示爲具備[index]解除引用的屬性鍵,例如此YAML:

個人 服務器 - dev.bar.com - foo.bar.com

將轉化爲這些屬性:

my.servers [0] = dev.bar.com my.servers [1] = foo.bar.com

要使用Spring DataBinder實用程序綁定到相似的屬性(這是什麼 @ConfigurationProperties),您須要在類型java.util.List(或Set的目標bean中具備屬性, 而且您須要提供一個setter,或者使用可變值初始化它,例如this將綁定到上面的屬性

@ConfigurationProperties(prefix =「my」)
 public  class Config { private List <String> servers = new ArrayList <String>(); public List <String> getServers(){ return this .servers; } }
[注意]

配置列表時須要格外當心,由於覆蓋將沒法正常工做。在上面的示例中,當my.servers在多個位置從新定義,各個元素的目標是覆蓋,而不是列表。要確保 PropertySource具備更高優先級的a能夠覆蓋列表,您須要將其定義爲單個屬性:

個人 服務器:dev.bar.com,foo.bar.com

24.6.2在Spring環境中公開YAML做爲屬性

YamlPropertySourceLoader類可用於暴露YAML做爲PropertySource 在春節Environment這容許您使用熟悉的@Value註釋和佔位符語法來訪問YAML屬性。

24.6.3多輪廓的YAML文檔

您能夠使用spring.profiles鍵指定文檔什麼時候適用,從而在單個文件中指定多個特定於配置文件的YAML文檔例如:

服務器 地址192.1681.100 --- spring profiles:開發 服務器 地址127.00.1 --- spring profiles:生產 服務器 地址192.1681.120

在上面的示例中,若是 配置文件處於活動狀態,則server.address屬性爲。若是 啓用配置文件,則屬性的值將爲127.0.0.1developmentdevelopmentproduction192.168.1.100

若是在應用程序上下文啓動時沒有顯式活動,則激活默認配置文件。所以,在這個YAML咱們設定的值security.user.password是 可在「默認」的我的資料:

server port8000 --- spring profiles:默認 安全 user 密碼:弱

whereas in this example, the password is always set because it isn’t attached to any profile, and it would have to be explicitly reset in all other profiles as necessary:

server:
 port: 8000 security:  user:  password: weak

Spring profiles designated using the "spring.profiles" element may optionally be negated using the ! character. If both negated and non-negated profiles are specified for a single document, at least one non-negated profile must match and no negated profiles may match.

24.6.4 YAML shortcomings

YAML files can’t be loaded via the @PropertySource annotation. So in the case that you need to load values that way, you need to use a properties file.

24.6.5 Merging YAML lists

As we have seen above, any YAML content is ultimately transformed to properties. That process may be counter intuitive when overriding 「list」 properties via a profile.

For example, assume a MyPojo object with name and description attributes that are null by default. Let’s expose a list of MyPojo from FooProperties:

@ConfigurationProperties("foo")
public class FooProperties { private final List<MyPojo> list = new ArrayList<>(); public List<MyPojo> getList() { return this.list; } }

Consider the following configuration:

foo list - name:my name  description:my description --- spring profiles:dev foo list - name:my another name

若是dev配置文件未激活,FooProperties.list將包含一個MyPojo如上定義的條目。dev可是,若是啓用配置文件,list仍將 只包含一個條目(名稱爲「個人另外一個名稱」和描述null)。此配置不會MyPojo向列表添加第二個實例,也不會合並項目。

在多個配置文件中指定集合時,將使用具備最高優先級的集合(而且僅使用該集合):

foo list - name:my name  description:my description  - name:another name  description:another description --- spring profiles:dev foo list - name:my another name

在上面的示例中,考慮到dev配置文件處於活動狀態,FooProperties.list 將包含一個 MyPojo條目(名稱爲「個人另外一個名稱」和描述null)。

24.7類型安全配置屬性

使用@Value("${property}")註釋注入配置屬性有時會很麻煩,尤爲是在使用多個屬性或數據本質上是分層的狀況下。Spring Boot提供了一種使用屬性的替代方法,容許強類型bean管理和驗證應用程序的配置。

 com.example;

import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(「foo」) 公共  FooProperties { private boolean enabled; private InetAddress remoteAddress; private final Security security = new Security(); public boolean isEnabled(){...} public void setEnabled(boolean enabled){...} public InetAddress getRemoteAddress(){...} public void setRemoteAddress(InetAddress remoteAddress){...} 公共安全 getSecurity(){...} public static class Security { 私有 String用戶名; 私有字符串密碼; private List <String> roles = new ArrayList <>(Collections.singleton(「USER」)); public String getUsername(){...} public void setUsername(String username){...} public String getPassword(){...} public void setPassword(String password){...} public List <String> getRoles(){...} public void setRoles(List <String> roles){...}  } }

上面的POJO定義瞭如下屬性:

  • foo.enabledfalse默認狀況下
  • foo.remote-address,具備能夠強制的類型 String
  • foo.security.username,帶有嵌套的「安全性」,其名稱由屬性名稱決定。特別是那裏根本沒有使用返回類型SecurityProperties
  • foo.security.password
  • foo.security.roles,收集 String
[注意]

getter和setter一般是必需的,由於綁定是經過標準的Java Beans屬性描述符,就像在Spring MVC中同樣。有些狀況下可能會省略setter:

  • 映射,只要它們被初始化,就須要一個getter但不必定是setter,由於它們能夠被綁定器變異。
  • 能夠經過索引(一般使用YAML)或使用單個逗號分隔值(屬性)訪問集合和數組。在後一種狀況下,必須設置一個setter。咱們建議始終爲這些類型添加setter。若是初始化集合,請確保它不是不可變的(如上例所示)
  • If nested POJO properties are initialized (like the Security field in the example above), a setter is not required. If you want the binder to create the instance on-the-fly using its default constructor, you will need a 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.

You also need to list the properties classes to register in the @EnableConfigurationProperties annotation:

@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class MyConfiguration { }
[注意]

When @ConfigurationProperties bean is registered that way, the bean will have a conventional name: <prefix>-<fqn>, where <prefix> is the environment key prefix specified in the @ConfigurationProperties annotation and <fqn> the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used.

The bean name in the example above will be foo-com.example.FooProperties.

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 @ConfigurationProperties also allows you to generate meta-data files that can be used by IDEs to offer auto-completion for your own keys, see the Appendix B, Configuration meta-data appendix for details.

24.7.1 Third-party configuration

As well as using @ConfigurationProperties to annotate a class, you can also use it on public @Bean methods. This can be particularly useful when you want to bind properties to third-party components that are outside of your control.

To configure a bean from the Environment properties, add @ConfigurationProperties to its bean registration:

@ConfigurationProperties(prefix = "bar")
@Bean
public BarComponent barComponent() {
    ...
}

Any property defined with the bar prefix will be mapped onto that BarComponent bean in a similar manner as the FooProperties example above.

24.7.2 Relaxed binding

Spring Boot uses some relaxed rules for binding Environment properties to @ConfigurationProperties beans, so there doesn’t need to be an exact match between the Environment property name and the bean property name. Common examples where this is useful include dashed separated (e.g. context-path binds to contextPath), and capitalized (e.g. PORT binds to port) environment properties.

For example, given the following @ConfigurationProperties class:

@ConfigurationProperties(prefix =「person」)
 public  class OwnerProperties { private String firstName; public String getFirstName(){ return this .firstName; } public void setFirstName(String firstName){ this .firstName = firstName; }  }

能夠使用如下屬性名稱:

表24.1。輕鬆綁定

屬性 注意

person.firstName

標準的駝峯案例語法。

person.first-name

烤肉串,建議用於.properties.yml文件。

person.first_name

下劃線表示法,用於.properties.yml文件的替代格式

PERSON_FIRSTNAME

大寫格式。建議在使用系統環境變量時使用。


[注意]

prefix註釋值必須是kebab-case,即小寫並以其分隔-

表24.2。每一個屬性源放寬綁定規則

物業來源 簡單 名單

屬性文件

駱駝箱,烤肉串或下劃線表示法

標準列表語法使用[ ]或逗號分隔值

YAML文件

駱駝箱,烤肉串或下劃線表示法

標準YAML列表語法或逗號分隔值

環境變量

大寫格式,下劃線做爲分隔符。_不該在屬性名稱中使用

下劃線包圍的數字值。例如:MY_FOO_1_BAR = my.foo[1].bar

系統屬性

駱駝箱,烤肉串或下劃線表示法

標準列表語法使用[ ]或逗號分隔值


[小費]

咱們建議,若是可能,屬性以小寫kebab格式存儲。my.property-name=foo

24.7.3屬性轉換

Spring will attempt to coerce the external application properties to the right type when it binds to the @ConfigurationProperties beans. If you need custom type conversion you can provide a ConversionService bean (with bean id conversionService) or custom property editors (via a CustomEditorConfigurer bean) or custom Converters (with bean definitions annotated as @ConfigurationPropertiesBinding).

[注意]

As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your ConversionService is using. Typically, any dependency that you require may not be fully initialized at creation time. You may want to rename your custom ConversionService if it’s not required for configuration keys coercion and only rely on custom converters qualified with @ConfigurationPropertiesBinding.

24.7.4 @ConfigurationProperties Validation

Spring Boot will attempt to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation. You can use JSR-303 javax.validation constraint annotations directly on your configuration class. Simply ensure that a compliant JSR-303 implementation is on your classpath, then add constraint annotations to your fields:

@ConfigurationProperties(prefix="foo")
@Validated
public class FooProperties { @NotNull private InetAddress remoteAddress; // ... getters and setters }

In order to validate values of nested properties, you must annotate the associated field as @Valid to trigger its validation. For example, building upon the aboveFooProperties example:

@ConfigurationProperties(prefix="connection")
@Validated
public class FooProperties { @NotNull private InetAddress remoteAddress; @Valid private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty public String username; // ... getters and setters } }

您還能夠Validator經過建立名爲的bean定義 來添加自定義Spring configurationPropertiesValidator@Bean應聲明方法static配置屬性驗證器是在應用程序生命週期的早期建立的,並將該@Bean方法聲明爲static,容許建立bean而無需實例化@Configuration該類。這避免了早期實例化可能致使的任何問題。有一個 屬性驗證示例,您能夠看到如何設置。

[小費]

spring-boot-actuator模塊包括一個暴露全部@ConfigurationPropertiesbean 的端點 只需將Web瀏覽器指向/configprops 或使用等效的JMX端點便可。請參閱 生產就緒功能部分了解詳情。

24.7.5 @ConfigurationProperties與@Value

@Value是一個核心容器功能,它不提供與類型安全的配置屬性相同的功能。下表彙總了支持的功能@ConfigurationProperties@Value

特徵 @ConfigurationProperties @Value

輕鬆綁定

沒有

元數據支持

沒有

SpEL 評測

沒有

若是爲本身的組件定義一組配置鍵,咱們建議您將它們分組到帶註釋的POJO中@ConfigurationProperties另請注意,因爲@Value不支持寬鬆綁定,所以若是須要使用環境變量提供值,則不是一個很好的選擇。

最後,雖然您能夠編寫SpEL表達式@Value,但不會從Application屬性文件處理此類表達式

25.簡介

Spring Profiles提供了一種隔離應用程序配置部分並使其僅在特定環境中可用的方法。任何@Component@Configuration能夠標記@Profile以限制什麼時候加載:

@Configuration 
@Profile(「production」)
公共  ProductionConfiguration { // ...  }

在常規Spring方式中,您能夠使用spring.profiles.active Environment屬性指定哪些配置文件處於活動狀態。您能夠經過任何經常使用方式指定屬性,例如,您能夠將其包含在application.properties

spring.profiles.active = dev,hsqldb

或使用開關在命令行上指定--spring.profiles.active=dev,hsqldb

25.1添加活動配置文件

spring.profiles.active物業遵循與其餘物業相同的訂購規則,最高PropertySource將獲勝。這意味着您能夠指定活動配置文件,application.properties而後使用命令行開關替換它們。

有時,特定於配置文件的屬性添加到活動配置文件而不是替換它們是有用的spring.profiles.include屬性可用於無條件添加活動配置文件。SpringApplication入口點還設置額外的配置文件(即對那些被激活頂部的Java API的 spring.profiles.active屬性):看setAdditionalProfiles()方法。

例如,當與如下屬性的應用程序正在使用開關運行 --spring.profiles.active=prodproddbprodmq輪廓也將被激活:

--- 
my.property:fromyamlfile --- spring.profiles:PROD spring.profiles.include - proddb - prodmq
[注意]

請記住,spring.profiles能夠在YAML文檔中定義屬性,以肯定此特定文檔什麼時候包含在配置中。有關更多詳細信息請參見 第73.7節「根據環境更改配置」

25.2以編程方式設置配置文件

您能夠SpringApplication.setAdditionalProfiles(…​)在應用程序運行以前經過調用以編程方式設置活動配置文 也能夠使用Spring的ConfigurableEnvironment界面激活配置文件

25.3特定於配置文件的配置文件

特定於配置文件的application.properties(或application.yml)和引用的文件的變體@ConfigurationProperties被視爲加載文件。有關詳細信息請參見第24.4節「特定配置文件的屬性」

26.記錄

Spring Boot使用Commons Logging進行全部內部日誌記錄,但保留底層日誌實現。Java Util Logging, Log4J2Logback提供了默認配置 在每種狀況下,記錄器都預先配置爲使用控制檯輸出,而且還提供可選的文件輸出。

默認狀況下,若是使用「啓動器」,則將使用Logback進行日誌記錄。還包括適當的Logback路由,以確保使用Java Util Logging,Commons Logging,Log4J或SLF4J的依賴庫都能正常工做。

[小費]

Java有不少日誌框架可供使用。若是以上列表看起來使人困惑,請不要擔憂。一般,您不須要更改日誌記錄依賴項,Spring Boot默認值也能夠正常工做。

26。1日誌格式

Spring Boot的默認日誌輸出以下所示:

2014-03-05 10:57:51.112 INFO 45469 --- [main] org.apache.catalina.core.StandardEngine:啓動Servlet引擎:Apache Tomcat / 7.0.52
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] oaccC [Tomcat]。[localhost]。[/]:初始化Spring嵌入式WebApplicationContext
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] osweb.context.ContextLoader:Root WebApplicationContext:初始化在1358 ms完成
2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] osbceServletRegistrationBean:將servlet:'dispatcherServlet'映射到[/]
2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean:映射過濾器:'hiddenHttpMethodFilter'到:[/ *]

輸出如下項目:

  • 日期和時間 - 毫秒精度,易於排序。
  • 日誌級別- ,  ERRORWARN INFODEBUGTRACE
  • 進程ID。
  • 一個---分離器來區分實際日誌消息的開始。
  • 線程名稱 - 括在方括號中(可能會截斷控制檯輸出)。
  • Logger name — This is usually the source class name (often abbreviated).
  • The log message.
[注意]

Logback does not have a FATAL level (it is mapped to ERROR)

26.2 Console output

The default log configuration will echo messages to the console as they are written. By default ERRORWARN 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 debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a 「trace」 mode by starting your application with a --trace flag (or trace=true in your application.properties). This will enable trace logging for a selection of core loggers (embedded container, Hibernate schema generation and the whole Spring portfolio).

26.2.1 Color-coded output

If your terminal supports ANSI, color output will be used to aid readability. You can set spring.output.ansi.enabled to a supported value to override the auto detection.

Color coding is configured using the %clr conversion word. In its simplest form the converter will color the output according to the log level, for example:

%clr(%5p)

The mapping of log level to a color is as follows:

Level Color

FATAL

Red

ERROR

Red

WARN

Yellow

INFO

Green

DEBUG

Green

TRACE

Green

Alternatively, you can specify the color or style that should be used by providing it as an option to the conversion. For example, to make the text yellow:

%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}

The following colors and styles are supported:

  • blue
  • cyan
  • faint
  • green
  • magenta
  • red
  • yellow

26.3 File output

By default, Spring Boot will only log to the console and will not write log files. If you want to write log files in addition to the console output you need to set alogging.file or logging.path property (for example in your application.properties).

The following table shows how the logging.* properties can be used together:

Table 26.1. Logging properties

logging.file logging.path Example Description

(none)

(none)

 

Console only logging.

Specific file

(none)

my.log

Writes to the specified log file. Names can be an exact location or relative to the current directory.

(none)

Specific directory

/var/log

寫入spring.log指定的目錄。名稱能夠是精確位置或相對於當前目錄。


日誌文件將在達到10 MB時旋轉,而且與控制檯輸出同樣ERRORWARN 而且INFO默認狀況下會記錄級別消息。

[注意]

日誌記錄系統在應用程序生命週期的早期初始化,所以在經過@PropertySource 註釋加載的屬性文件中找不到這樣的日誌記錄屬性

[小費]

日誌記錄屬性獨立於實際的日誌記錄基礎結構。所以,logback.configurationFilespring Boot無論理特定的配置鍵(例如Logback)。

26。4日誌級別

全部受支持的日誌記錄系統均可以使用'logging.level。* = LEVEL'在Spring中設置記錄器級別 Environment(例如application.properties),其中'LEVEL'是TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF之一。root記錄器能夠經過如下方式配置logging.level.root示例application.properties

logging.level.root = WARN logging.level.org.springframework.web = DEBUG logging.level.org.hibernate = ERROR
[注意]

默認狀況下,Spring Boot會從新映射Thymeleaf INFO消息,以便在DEBUG級別上記錄它們 這有助於下降標準日誌輸出中的噪音。有關LevelRemappingAppender 如何在本身的配置中應用從新映射的詳細信息,請參閱 

26.5自定義日誌配置

能夠經過在類路徑中包含適當的庫來激活各類日誌記錄系統,並經過在類路徑的根目錄中或Spring Environment屬性 指定的位置提供合適的配置文件來進一步自定義logging.config

您能夠使用org.springframework.boot.logging.LoggingSystem系統屬性強制Spring Boot使用特定的日誌記錄系統 該值應該是實現的徹底限定類名LoggingSystem您還能夠經過使用值來徹底禁用Spring Boot的日誌記錄配置none

[注意]

因爲記錄被初始化以前ApplicationContext建立,這是不可能控制來自伐木@PropertySources春季@Configuration文件。系統屬性和傳統的Spring Boot外部配置文件均可以正常工做。)

根據您的日誌記錄系統,將加載如下文件:

記錄系統 定製

的logback

logback-spring.xmllogback-spring.groovylogback.xml或者logback.groovy

Log4j2

log4j2-spring.xml 要麼 log4j2.xml

JDK(Java Util Logging)

logging.properties

[注意]

若是可能,咱們建議您使用-spring變量進行日誌記錄配置(例如,logback-spring.xml而不是logback.xml)。若是使用標準配置位置,Spring沒法徹底控制日誌初始化。

[警告]

Java Util Logging存在已知的類加載問題,從「可執行jar」運行時會致使問題。咱們建議您儘量避免使用它。

爲了幫助定製,一些其餘屬性從Spring轉移 Environment到System屬性:

春天的環境 系統屬性 評論

logging.exception-conversion-word

LOG_EXCEPTION_CONVERSION_WORD

記錄異常時使用的轉換字。

logging.file

LOG_FILE

若是已定義,則用於默認日誌配置。

logging.path

LOG_PATH

若是已定義,則用於默認日誌配置。

logging.pattern.console

CONSOLE_LOG_PATTERN

要在控制檯上使用的日誌模式(stdout)。(僅支持默認的logback設置。)

logging.pattern.file

FILE_LOG_PATTERN

要在文件中使用的日誌模式(若是啓用了LOG_FILE)。(僅支持默認的logback設置。)

logging.pattern.level

LOG_LEVEL_PATTERN

用於呈現日誌級別的格式(默認%5p)。(僅支持默認的logback設置。)

PID

PID

當前進程ID(若是可能,則在未定義爲OS環境變量時發現)。

支持的全部日誌記錄系統在解析其配置文件時均可以參考系統屬性。有關spring-boot.jar示例,請參閱默認配置

[小費]

若是要在日誌記錄屬性中使用佔位符,則應使用 Spring Boot的語法而不是底層框架的語法。值得注意的是,若是您使用的是Logback,則應將其 :用做屬性名稱與其默認值之間的分隔符,而不是:-

[小費]

您能夠經過僅覆蓋LOG_LEVEL_PATTERN(或logging.pattern.level使用Logback)將MDC和其餘臨時內容添加到日誌行例如,若是您使用,logging.pattern.level=user:%X{user} %5p則默認日誌格式將包含「user」的MDC條目(若是存在),例如

2015-09-30 12:30:04.031用戶:juergen INFO 22174 --- [nio-8080-exec-0] demo.Controller
處理通過身份驗證的請

26.6 Logback擴展

Spring Boot包含許多Logback擴展,能夠幫助進行高級配置。您能夠在logback-spring.xml配置文件中使用這些擴展名

[注意]

您不能在標準logback.xml配置文件中使用擴展,由於它過早加載。您須要使用logback-spring.xml或定義 logging.config屬性。

[警告]

擴展不能與Logback的 配置掃描一塊兒使用若是您嘗試這樣作,更改配置文件將致使相似於如下記錄之一的錯誤:

ch.qos.logback.core.joran.spi.Interpreter@4中的錯誤:71  -  [springProperty]沒有適用的操做,當前的ElementPath是[[configuration] [springProperty]]ch.qos.logback.core.joran.spi.Interpreter@4中的 錯誤:71  -  [springProfile]沒有適用的操做,當前的ElementPath是[[configuration] [springProfile]]

26.6.1特定於配置文件的配置

<springProfile>標籤容許您有選擇地包括或排除基於主動春型材配置的部分。<configuration>元素內的任何位置都支持配置文件節使用該name屬性指定哪一個配置文件接受配置。能夠使用逗號分隔列表指定多個配置文件。

<springProfile  name = 「staging」 > <! - 「暫存」配置文件處於活動狀態時啓用的配置 - > </ springProfile> <springProfile name = 「dev,staging」 > <! - 在「dev」或「staging」配置文件處於活動狀態時啓用的配置 - > </ springProfile> <springProfile name = 「!production」 > <! - 「生產」配置文件未激活時要啓用的配置 - > </ springProfile>

26.6.2環境屬性

The <springProperty> tag allows you to surface properties from the Spring Environment for use within Logback. This can be useful if you want to access values from your application.properties file in your logback configuration. The tag works in a similar way to Logback’s standard <property> tag, but rather than specifying a direct value you specify the source of the property (from the Environment). You can use the scope attribute if you need to store the property somewhere other than in local scope. If you need a fallback value in case the property is not set in the Environment, you can use the defaultValue attribute.

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host" defaultValue="localhost"/> <appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender"> <remoteHost>${fluentHost}</remoteHost> ... </appender>
[注意]

The source must be specified using kebab-case (my.property-name). However, properties can be added to the Environment using the relaxed rules.

27. Developing web applications

Spring Boot is well suited for web application development. You can easily create a self-contained HTTP server using embedded Tomcat, Jetty, Undertow, or Netty. Most web applications will use the spring-boot-starter-web module to get up and running quickly. You can also choose to use to build reactive web applications by using the spring-boot-starter-webflux module.

If you haven’t yet developed a Spring Boot web application you can follow the "Hello World!" example in the Getting started section.

27.1 The ‘Spring Web MVC framework’

Spring Web MVC框架(一般簡稱爲「Spring MVC」)是一個豐富的「模型視圖控制器」Web框架。Spring MVC容許您建立特殊@Controller 或@RestControllerbean來處理傳入的HTTP請求。控制器中的方法使用@RequestMapping註釋映射到HTTP 

如下是@RestController提供JSON數據的典型示例

@RestController 
@RequestMapping(value =「/ users」)
 public  class MyRestController { @RequestMapping(value =「/ {user}」,method = RequestMethod.GET)  public User getUser( @PathVariable Long user){  // ... } @RequestMapping(value =「/ {user} / customers」,method = RequestMethod.GET) List <Customer> getUserCustomers( @PathVariable Long user){  // ... } @RequestMapping(value =「/ {user}」,method = RequestMethod.DELETE)  public User deleteUser( @PathVariable Long user){  // ... }  }

Spring MVC是核心Spring Framework的一部分,詳細信息可在參考文檔中找到Spring.io/guides還提供了幾個涵蓋Spring MVC的指南。

27.1.1 Spring MVC自動配置

Spring Boot爲Spring MVC提供自動配置,適用於大多數應用程序。

自動配置在Spring的默認值之上添加了如下功能:

  • 包含ContentNegotiatingViewResolverBeanNameViewResolver豆類。
  • 支持提供靜態資源,包括對WebJars的支持(見下文)。
  • 自動登記ConverterGenericConverterFormatter豆類。
  • 支持HttpMessageConverters(見下文)。
  • 自動註冊MessageCodesResolver(見下文)。
  • 靜態index.html支持。
  • 自定義Favicon支持(見下文)。
  • 自動使用ConfigurableWebBindingInitializerbean(見下文)。

若是你想保留Spring Boot MVC功能,而且你只想添加額外的MVC配置(攔截器,格式化程序,視圖控制器等),你能夠添加本身的@Configuration類類型WebMvcConfigurer,但沒有 @EnableWebMvc若是您但願提供自定義實例RequestMappingHandlerMappingRequestMappingHandlerAdapter或者ExceptionHandlerExceptionResolver您能夠聲明WebMvcRegistrationsAdapter 提供此類組件實例。

若是您想徹底控制Spring MVC,能夠添加本身的@Configuration 註釋@EnableWebMvc

27.1.2 HttpMessageConverters

Spring MVC使用該HttpMessageConverter接口來轉換HTTP請求和響應。靈敏的默認值包含在開箱即用中,例如,對象能夠自動轉換爲JSON(使用Jackson庫)或XML(若是可用則使用Jackson XML擴展,不然使用JAXB)。字符串UTF-8默認使用

若是您須要添加或自定義轉換器,能夠使用Spring Boot的 HttpMessageConverters類:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation。*; import org.springframework.http.converter。*; @Configuration 公共  MyConfiguration { @Bean  public HttpMessageConverters customConverters(){ HttpMessageConverter<?> additional = ... HttpMessageConverter<?> another = ... return new HttpMessageConverters(additional, another); } }

Any HttpMessageConverter bean that is present in the context will be added to the list of converters. You can also override default converters that way.

27.1.3 Custom JSON Serializers and Deserializers

If you’re using Jackson to serialize and deserialize JSON data, you might want to write your own JsonSerializer and JsonDeserializer classes. Custom serializers are usually registered with Jackson via a Module, but Spring Boot provides an alternative @JsonComponent annotation which makes it easier to directly register Spring Beans.

You can use @JsonComponent directly on JsonSerializer or JsonDeserializer implementations. You can also use it on classes that contains serializers/deserializers as inner-classes. For example:

import java.io.*;
import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import org.springframework.boot.jackson.*; @JsonComponent public class Example { public static class Serializer extends JsonSerializer<SomeObject> { // ... } public static class Deserializer extends JsonDeserializer<SomeObject> { // ... } }

All @JsonComponent beans in the ApplicationContext will be automatically registered with Jackson, and since @JsonComponent is meta-annotated with @Component, the usual component-scanning rules apply.

Spring Boot also provides JsonObjectSerializer and JsonObjectDeserializer base classes which provide useful alternatives to the standard Jackson versions when serializing Objects. See the Javadoc for details.

27.1.4 MessageCodesResolver

Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: MessageCodesResolver. Spring Boot will create one for you if you set the spring.mvc.message-codes-resolver.format property PREFIX_ERROR_CODE or POSTFIX_ERROR_CODE (see the enumeration in DefaultMessageCodesResolver.Format).

27.1.5 Static Content

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurerand 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 src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar.

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 webjars-locator-jboss-vfs dependency instead of the webjars-locator; otherwise all Webjars resolve as a 404.

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 ResourceUrlEncodingFilter, auto-configured for Thymeleaf and FreeMarker. You should manually declare this filter when using JSPs. Other template engines aren’t automatically supported right now, but can be with custom template macros/helpers and the use of the ResourceUrlProvider.

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 Framework的參考文檔中進行了詳細描述 

27.1.6自定義Favicon

Spring Boot favicon.ico在配置的靜態內容位置和類路徑的根(按此順序)中查找a 若是存在此類文件,則會自動將其用做應用程序的favicon。

27.1.7 ConfigurableWebBindingInitializer

Spring MVC使用a WebBindingInitializer來初始化WebDataBinder特定請求。若是您本身建立ConfigurableWebBindingInitializer @Bean,Spring Boot將自動配置Spring MVC以使用它。

27.1.8模板引擎

除REST Web服務外,您還能夠使用Spring MVC來提供動態HTML內容。Spring MVC支持各類模板技術,包括Thymeleaf,FreeMarker和JSP。許多其餘模板引擎也提供本身的Spring MVC集成。

Spring Boot包括對如下模板引擎的自動配置支持:

[小費]

若是可能,應該避免使用JSP,將它們與嵌入式servlet容器一塊兒使用時有幾個 已知的限制

當您使用默認配置的其中一個模板引擎時,您的模板將自動從中獲取src/main/resources/templates

[小費]

IntelliJ IDEA根據您運行應用程序的方式對類路徑進行不一樣的排序。經過主方法在IDE中運行應用程序將致使與使用Maven或Gradle或其打包的jar運行應用程序時的順序不一樣。這可能致使Spring Boot沒法在類路徑中找到模板。若是您受此問題的影響,能夠在IDE中從新排序類路徑,以便首先放置模塊的類和資源。或者,您能夠配置模板前綴以搜索類路徑上的每一個模板目錄:classpath*:/templates/

27.1.9錯誤處理

Spring Boot /error默認提供映射,以合理的方式處理全部錯誤,並在servlet容器中註冊爲「全局」錯誤頁面。對於機器客戶端,它將生成一個JSON響應,其中包含錯誤,HTTP狀態和異常消息的詳細信息。對於瀏覽器客戶端,有一個「whitelabel」錯誤視圖,它以HTML格式呈現相同的數據(要自定義它,只需添加一個View解析爲'錯誤'的數據)。要徹底替換默認行爲,您能夠實現 ErrorController並註冊該類型的bean定義,或者只是添加類型的bean ErrorAttributes以使用現有機制但替換內容。

[小費]

BasicErrorController能夠用做自定義基類ErrorController若是要爲新內容類型添加處理程序(默認狀況下是text/html專門處理併爲其餘全部內容提供後備),這將特別有用爲此,只需擴展BasicErrorController並添加@RequestMapping具備produces屬性的公共方法 ,並建立新類型的bean。

您還能夠定義一個@ControllerAdvice自定義JSON文檔以返回特定控制器和/或異常類型。

@ControllerAdvice(basePackageClasses = FooController.class)
公共  FooControllerAdvice擴展 ResponseEntityExceptionHandler { @ExceptionHandler(YourException.class) @ResponseBody ResponseEntity <?> handleControllerException(HttpServletRequest request,Throwable ex){ HttpStatus status = getStatus(request); 返回 新的 ResponseEntity <>(new CustomErrorType(status.value(),ex.getMessage()),status); } private HttpStatus getStatus(HttpServletRequest request){ 整數statusCode =(整數)request.getAttribute(「javax.servlet.error.status_code」); if(statusCode == null){ return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); }  }

在上面的示例中,若是YourException由在同一個包中定義的控制器拋出,則將使用POJO FooController的json表示CustomerErrorType而不是ErrorAttributes表示。

自定義錯誤頁面

若是要爲給定的狀態代碼顯示自定義HTML錯誤頁面,請將文件添加到文件/error夾。錯誤頁面能夠是靜態HTML(即添加到任何靜態資源文件夾下),也能夠使用模板構建。文件名應該是確切的狀態代碼或系列掩碼。

例如,要映射404到靜態HTML文件,您的文件夾結構將以下所示:

SRC /
 +  - 主要/
     +  -  java / | + <源代碼>
     +  - 資源/
         +  - 公共/
             +  - 錯誤/ | + - 404.html
             +  -  <其餘公共資產>

5xx使用FreeMarker模板映射全部錯誤,您將擁有以下結構:

SRC /
 +  - 主要/
     +  -  java / | + <源代碼>
     +  - 資源/
         +  - 模板/
             +  - 錯誤/ | + - 5xx.ftl
             +  -  <其餘模板>

對於更復雜的映射,您還能夠添加實現該ErrorViewResolver 接口的bean 

公共  MyErrorViewResolver 實現 ErrorViewResolver { @覆蓋 公共的ModelAndView resolveErrorView(HttpServletRequest的請求, HttpStatus狀態,Map <String,Object> model){ //使用請求或狀態可選擇返回ModelAndView 返回 ... }  }

您還能夠使用常規的Spring MVC功能,如 @ExceptionHandler方法和 @ControllerAdvice而後,ErrorController 將會發現任何未處理的異常。

映射Spring MVC以外的錯誤頁面

對於不使用Spring MVC的應用程序,能夠使用該ErrorPageRegistrar 接口直接註冊ErrorPages這種抽象直接與底層嵌入式servlet容器一塊兒工做,即便你沒有Spring MVC也能工做 DispatcherServlet

@Bean
 public ErrorPageRegistrar errorPageRegistrar(){  return new MyErrorPageRegistrar(); } // ... 私有 靜態  MyErrorPageRegistrar 實現 ErrorPageRegistrar { @Override  public void registerErrorPages(ErrorPageRegistry registry){ registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST,「/ 400」)); }  }

注意若是你註冊的ErrorPage路徑最終會被a處理 Filter(例如,像一些非Spring網頁框架同樣常見,好比Jersey和Wicket),那麼Filter必須明確註冊爲ERROR調度程序,例如

@Bean
 public FilterRegistrationBean myFilter(){ FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new MyFilter()); ... registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); return registration; }

(the default FilterRegistrationBean does not include the ERROR dispatcher type).

Error Handling on WebSphere Application Server

When deployed to a servlet container, a Spring Boot uses its error page filter to forward a request with an error status to the appropriate error page. The request can only be forwarded to the correct error page if the response has not already been committed. By default, WebSphere Application Server 8.0 and later commits the response upon successful completion of a servlet’s service method. You should disable this behaviour by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false

27.1.10 Spring HATEOAS

若是您正在開發一個使用超媒體的RESTful API,Spring Boot爲Spring HATEOAS提供了自動配置,適用於大多數應用程序。自動配置取代了使用@EnableHypermediaSupport和註冊多個bean 的須要,以便於構建基於超媒體的應用程序,包括 LinkDiscoverers(用於客戶端支持)和ObjectMapper配置爲正確地將響應編組到所需表示中。ObjectMapper將根據定製spring.jackson.*的屬性或者Jackson2ObjectMapperBuilder若是存在豆。

您能夠使用控制Spring HATEOAS的配置 @EnableHypermediaSupport請注意,這將禁用上述ObjectMapper自定義。

27.1.11 CORS支持

跨源資源共享 (CORS)是大多數瀏覽器實現 W3C規範,容許您以靈活的方式指定受權何種類型的跨域請求,而不是使用一些安全性較低且功能較弱的方法,如IFRAME或JSONP。

從版本4.2開始,Spring MVC 支持開箱即用的CORS 在Spring Boot應用程序中使用帶有 註釋的控制器方法CORS配置@CrossOrigin不須要任何特定配置。 能夠經過使用自定義 方法註冊bean 來定義全局CORS配置WebMvcConfigureraddCorsMappings(CorsRegistry)

@Configuration
公共  MyConfiguration { @Bean  public WebMvcConfigurer corsConfigurer(){  return new WebMvcConfigurer(){  @  Override public void addCorsMappings(CorsRegistry registry){ registry.addMapping(「/ api / **」); } }; } }

27.2'Spring WebFlux框架'

Spring WebFlux是Spring Framework 5.0中引入的新的響應式Web框架。與Spring MVC不一樣,它不須要Servlet API,徹底異步且無阻塞,並 經過Reactor項目實現Reactive Streams規範

Spring WebFlux有兩種版本 - 基於註釋的版本與咱們所知道的Spring MVC模型很是接近:

@RestController 
@RequestMapping(「/ users」)
公共  MyRestController { @GetMapping(「/ {user}」)  public Mono <User> getUser( @PathVariable Long user){  // ... } @GetMapping(「/ {user} / customers」) Flux <Customer> getUserCustomers( @PathVariable Long user){  // ... } @DeleteMapping(「/ {user}」)  public Mono <User> deleteUser( @PathVariable Long user){  // ... }  }

'WebFlux.fn'是功能變體,它將路由配置與請求的實際處理分開:

@Configuration
public class RoutingConfiguration { @Bean public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) { return route(GET("/{user}").and(accept(APPLICATION_JSON)), userHandler::getUser) .andRoute(GET("/{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers) .andRoute(DELETE("/{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser); } } @Component public class UserHandler { public Mono<ServerResponse> getUser(ServerRequest request) { // ... } public Mono<ServerResponse> getUserCustomers(ServerRequest request) { // ... } public Mono<ServerResponse> deleteUser(ServerRequest request) { // ... } }

WebFlux is part of the Spring Framework and detailed information is available in the reference documentation.

To get started, add the spring-boot-starter-webflux module to your application.

[注意]

Adding both spring-boot-starter-web and spring-boot-starter-webflux modules in your application will result in Spring Boot auto-configuring Spring MVC, not WebFlux. This behavior has been chosen because many Spring developers will add spring-boot-starter-webflux to their Spring MVC application to use the reactive WebCLient. You can still enforce your choice by setting the chosen application type likeSpringApplication.setWebApplicationType(WebApplicationType.REACTIVE).

27.2.1 Spring WebFlux auto-configuration

Spring Boot provides auto-configuration for Spring WebFlux that works well with most applications.

The auto-configuration adds the following features on top of Spring’s defaults:

  • Configuring codecs for HttpMessageReader and HttpMessageWriter instances (see below).
  • Support for serving static resources, including support for WebJars (see below).

If you want to keep Spring Boot WebFlux features, and you just want to add additional WebFlux configuration you can add your own @Configuration class of type WebFluxConfigurer, but without @EnableWebFlux.

If you want to take complete control of Spring WebFlux, you can add your own @Configuration annotated with @EnableWebFlux.

27.2.2 HTTP codecs with HttpMessageReaders and HttpMessageWriters

Spring WebFlux uses the HttpMessageReader and HttpMessageWriter interface to convert HTTP requests and responses. They are configured with CodecConfigurer with sensible defaults, by looking at the libraries available in your classpath.

Spring Boot will apply further customization using CodecCustomizer instances. For example, spring.jackson.* configuration keys will be applied to the Jackson codec.

若是須要添加或自定義編解碼器,能夠建立自定義CodecCustomizer 組件:

import org.springframework.boot.web.codec.CodecCustomizer;

@Configuration
公共  MyConfiguration { @Bean  public CodecCustomizer myCodecCustomizer(){  return codecConfigurer - > {  // ... } }  }

您還能夠利用Boot的自定義JSON序列化程序和反序列化程序

27.2.3靜態內容

默認狀況下,Spring Boot將從類路徑中名爲/static( /public/resources/META-INF/resources的目錄中提供靜態內容它使用ResourceWebHandlerSpring WebFlux,所以您能夠經過添加本身WebFluxConfigureraddResourceHandlers方法來修改該行爲並覆蓋該 方法。

默認狀況下,會映射資源,/**但您能夠經過調整該 資源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而且不使用該src/main/webapp目錄。

27.2.4模板引擎

除REST Web服務外,您還能夠使用Spring WebFlux來提供動態HTML內容。Spring WebFlux支持各類模板技術,包括Thymeleaf,FreeMarker和Mustache。

Spring Boot包括對如下模板引擎的自動配置支持:

當您使用默認配置的其中一個模板引擎時,您的模板將自動從中獲取src/main/resources/templates

27.3 JAX-RS和澤西島

If you prefer the JAX-RS programming model for REST endpoints you can use one of the available implementations instead of Spring MVC. Jersey 1.x and Apache CXF work quite well out of the box if you just register their Servlet or Filter as a @Bean in your application context. Jersey 2.x has some native Spring support so we also provide auto-configuration support for it in Spring Boot together with a starter.

To get started with Jersey 2.x just include the spring-boot-starter-jersey as a dependency and then you need one @Bean of type ResourceConfig in which you register all the endpoints:

@Component
public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(Endpoint.class); } }
[警告]

Jersey’s support for scanning executable archives is rather limited. For example, it cannot scan for endpoints in a package found in WEB-INF/classeswhen running an executable war file. To avoid this limitation, the packages method should not be used and endpoints should be registered individually using the register method as shown above.

You can also register an arbitrary number of beans implementing ResourceConfigCustomizer for more advanced customizations.

All the registered endpoints should be @Components with HTTP resource annotations (@GET etc.), e.g.

@Component
@Path("/hello")
public class Endpoint { @GET public String message() { return "Hello"; } }

Since the Endpoint is a Spring @Component its lifecycle is managed by Spring and you can @Autowired dependencies and inject external configuration with @Value. The Jersey servlet will be registered and mapped to /* by default. You can change the mapping by adding @ApplicationPath to your ResourceConfig.

By default Jersey will be set up as a Servlet in a @Bean of type ServletRegistrationBean named jerseyServletRegistration. By default, the servlet will be initialized lazily but you can customize it with spring.jersey.servlet.load-on-startup .You can disable or override that bean by creating one of your own with the same name. You can also use a Filter instead of a Servlet by setting spring.jersey.type=filter (in which case the @Bean to replace or override isjerseyFilterRegistration). The servlet has an @Order which you can set with spring.jersey.filter.order. Both the Servlet and the Filter registrations can be given init parameters using spring.jersey.init.* to specify a map of properties.

There is a Jersey sample so you can see how to set things up. There is also a Jersey 1.x sample. Note that in the Jersey 1.x sample that the spring-boot maven plugin has been configured to unpack some Jersey jars so they can be scanned by the JAX-RS implementation (because the sample asks for them to be scanned in its Filter registration). You may need to do the same if any of your JAX-RS resources are packaged as nested jars.

27.4 Embedded servlet container support

Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. Most developers will simply use the appropriate ‘Starter’ to obtain a fully configured instance. By default the embedded server will listen for HTTP requests on port 8080.

[警告]

If you choose to use Tomcat on CentOS be aware that, by default, a temporary directory is used to store compiled JSPs, file uploads etc. This directory may be deleted by tmpwatch while your application is running leading to failures. To avoid this, you may want to customize your tmpwatch configuration so that tomcat.* directories are not deleted, or configure server.tomcat.basedir so that embedded Tomcat uses a different location.

27.4.1 Servlets, Filters, and listeners

When using an embedded servlet container you can register Servlets, Filters and all the listeners from the Servlet spec (e.g. HttpSessionListener) either by using Spring beans or by scanning for Servlet components.

Registering Servlets, Filters, and listeners as Spring beans

Any ServletFilter 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 ServletRegistrationBeanFilterRegistrationBean and ServletListenerRegistrationBean classes for complete control.

27.4.2 Servlet Context Initialization

Embedded servlet containers will not directly execute the Servlet 3.0+ javax.servlet.ServletContainerInitializer interface, or Spring’sorg.springframework.web.WebApplicationInitializer interface. This is an intentional design decision intended to reduce the risk that 3rd party libraries designed to run inside a war will break Spring Boot applications.

If you need to perform servlet context initialization in a Spring Boot application, you should register a bean that implements theorg.springframework.boot.web.servlet.ServletContextInitializer interface. The single onStartup method provides access to the ServletContext, and can easily be used as an adapter to an existing WebApplicationInitializer if necessary.

Scanning for Servlets, Filters, and listeners

When using an embedded container, automatic registration of @WebServlet@WebFilter, and @WebListener annotated classes can be enabled using @ServletComponentScan.

[小費]

@ServletComponentScan will have no effect in a standalone container, where the container’s built-in discovery mechanisms will be used instead.

27.4.3 The ServletWebServerApplicationContext

Under the hood Spring Boot uses a new type of ApplicationContext for embedded servlet container support. The ServletWebServerApplicationContext is a special type of WebApplicationContext that bootstraps itself by searching for a single ServletWebServerFactory bean. Usually a TomcatServletWebServerFactoryJettyServletWebServerFactory, 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 ApplicationContextand ServletWebServerFactory will be created on your behalf.

27.4.4 Customizing embedded servlet containers

Common servlet container settings can be configured using Spring Environment properties. Usually you would define the properties in your application.properties file.

Common server settings include:

  • Network settings: listen port for incoming HTTP requests (server.port), interface address to bind to server.address, etc.
  • Session settings: whether the session is persistent (server.session.persistence), session timeout (server.session.timeout), location of session data (server.session.store-dir) and session-cookie configuration (server.session.cookie.*).
  • Error management: location of the error page (server.error.path), etc.
  • SSL
  • HTTP compression

Spring Boot tries as much as possible to expose common settings but this is not always possible. For those cases, dedicated namespaces offer server-specific customizations (see server.tomcat and server.undertow). For instance, access logs can be configured with specific features of the embedded servlet container.

[小費]

See the ServerProperties class for a complete list.

Programmatic customization

If you need to configure your embedded servlet container programmatically you can register a Spring bean that implements the WebServerFactoryCustomizerinterface. WebServerFactoryCustomizer provides access to the ConfigurableServletWebServerFactory which includes numerous customization setter methods. Dedicated variants exists for Tomcat, Jetty and Undertow.

import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.stereotype.Component; @Component 公共  CustomizationBean實現 WebServerFactoryCustomizer <ConfigurableServletWebServerFactory> { @Override  public void customize(ConfigurableServletWebServerFactory server){ server.setPort(9000); }  }

直接自定義ConfigurableServletWebServerFactory

若是上面的自定義方法太有限,你能夠註冊 TomcatServletWebServerFactoryJettyServletWebServerFactory或 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。若是您須要作一些更具異國情調的事情,還會提供幾種受保護的方法「掛鉤」。有關詳細信息,請參閱源代碼文檔。

27.4.5 JSP限制

運行使用嵌入式servlet容器的Spring Boot應用程序(並打包爲可執行存檔)時,JSP支持存在一些限制。

  • 使用Tomcat它應該能夠使用war包裝,便可執行的war會起做用,而且也能夠部署到標準容器(不限於但包括Tomcat)。因爲Tomcat中的硬編碼文件模式,可執行jar將沒法工做。
  • 使用Jetty它應該能夠使用war包裝,便可執行的war會起做用,而且也能夠部署到任何標準容器。
  • Undertow不支持JSP。
  • 建立自定義error.jsp頁面將不會覆蓋缺省視圖 錯誤處理, 自定義錯誤頁應改成使用。

有一個JSP示例,您能夠看到如何設置。

28.安全

若是Spring Security位於類路徑上,則默認狀況下Web應用程序將在全部HTTP端點上使用「基本」身份驗證。要向Web應用程序添加方法級安全性,您還能夠@EnableGlobalMethodSecurity使用所需的設置進行添加其餘信息能夠在Spring Security Reference中找到

默認設置AuthenticationManager只有一個用戶('用戶'用戶名和隨機密碼,在應用程序啓動時以INFO級別打印)

使用默認安全密碼:78fa095d-3f4c-48b1-ad50-e24c31d5cf35
[注意]

若是您對日誌記錄配置進行微調,請確保將 org.springframework.boot.autoconfigure.security類別設置爲記錄INFO消息,不然將不會打印默認密碼。

您能夠經過提供一個來更改密碼security.user.password此屬性和其餘有用屬性經過SecurityProperties (屬性前綴「security」)外部化 

默認安全配置在SecurityAutoConfiguration從那裏導入的類中實現SpringBootWebSecurityConfiguration對於Web安全性和AuthenticationManagerConfiguration用於非Web應用程序中相關的身份驗證配置)。要徹底關閉默認Web應用程序安全配置,您能夠添加一個bean @EnableWebSecurity(這不會禁用身份驗證管理器配置或Actuator的安全性)。要自定義它,一般使用外部屬性和類型的bean WebSecurityConfigurerAdapter(例如,添加基於表單的登陸)。

[注意]

若是添加@EnableWebSecurity並禁用Actuator安全性,除非添加自定義,不然將得到整個應用程序的默認基於表單的登陸WebSecurityConfigurerAdapter

要關閉身份驗證管理器配置,您能夠添加類型的bean AuthenticationManager,或者AuthenticationManager經過自動裝配AuthenticationManagerBuilder到其中一個@Configuration類中的方法來配置全局Spring Boot示例中有幾個安全的應用程序能夠幫助您開始使用常見的用例。

您在Web應用程序中開箱即用的基本功能包括:

  • AuthenticationManager具備內存存儲和單個用戶bean(請參閱用戶 SecurityProperties.User的屬性)。
  • 常見的靜態資源位置忽略(不安全的)路徑(/css/**/js/**, /images/**/webjars/****/favicon.ico)。
  • 全部其餘端點的HTTP基本安全性。
  • 發佈到Spring的安全事件ApplicationEventPublisher(成功和不成功的身份驗證和訪問被拒絕)。
  • Spring Security提供的常見低級功能(HSTS,XSS,CSRF,緩存)默認啓用。

以上全部內容均可以使用外部屬性(security.*打開或關閉或修改要覆蓋訪問規則不改變任何其它的自動配置功能添加@BeanWebSecurityConfigurerAdapter與 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)並對其進行配置,以知足您的需求。

[注意]

默認狀況下,a WebSecurityConfigurerAdapter將匹配任何路徑。若是您不想徹底覆蓋Spring Boot的自動配置訪問規則,則適配器必須顯式配置您要覆蓋的路徑。

28.1 OAuth2

若是您具備spring-security-oauth2類路徑,則能夠利用某些自動配置來輕鬆設置受權或資源服務器。有關完整詳細信息,請參閱「 Spring Security OAuth 2開發人員指南」

28.1.1受權服務器

要建立受權服務器並授予訪問令牌,您須要使用 @EnableAuthorizationServer和提供security.oauth2.client.client-idsecurity.oauth2.client.client-secret]屬性。客戶端將在內存存儲庫中爲您註冊。

完成後,您將可以使用客戶端憑據建立訪問令牌,例如:

$ curl client:secret @ localhost :8080 / oauth / token -d grant_type = password -d username = user -d password = pwd

/token端點的基自己份驗證憑據client-id和 client-secret用戶憑據是正常的Spring Security用戶詳細信息(在Spring Boot中默認爲「user」和隨機密碼)。

要關閉自動配置並自行配置受權服務器功能,只需添加一種@Bean類型AuthorizationServerConfigurer

28.1.2資源服務器

To use the access token you need a Resource Server (which can be the same as the Authorization Server). Creating a Resource Server is easy, just add@EnableResourceServer and provide some configuration to allow the server to decode access tokens. If your application is also an Authorization Server it already knows how to decode tokens, so there is nothing else to do. If your app is a standalone service then you need to give it some more configuration, one of the following options:

  • security.oauth2.resource.user-info-uri to use the /me resource (e.g. https://uaa.run.pivotal.io/userinfo on PWS)
  • security.oauth2.resource.token-info-uri to use the token decoding endpoint (e.g. https://uaa.run.pivotal.io/check_token on PWS).

If you specify both the user-info-uri and the token-info-uri then you can set a flag to say that one is preferred over the other (prefer-token-info=true is the default).

Alternatively (instead of user-info-uri or token-info-uri) if the tokens are JWTs you can configure a security.oauth2.resource.jwt.key-value to decode them locally (where the key is a verification key). The verification key value is either a symmetric secret or PEM-encoded RSA public key. If you don’t have the key and it’s public you can provide a URI where it can be downloaded (as a JSON object with a 「value」 field) with security.oauth2.resource.jwt.key-uri. E.g. on PWS:

$ curl https://uaa.run.pivotal.io/token_key
{"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"}
[警告]

If you use the security.oauth2.resource.jwt.key-uri the authorization server needs to be running when your application starts up. It will log a warning if it can’t find the key, and tell you what to do to fix it.

OAuth2 resources are protected by a filter chain with order security.oauth2.resource.filter-order and the default is after the filter protecting the actuator endpoints by default (so actuator endpoints will stay on HTTP Basic unless you change the order).

28.2 Token Type in User Info

Google, and certain other 3rd party identity providers, are more strict about the token type name that is sent in the headers to the user info endpoint. The default is 「Bearer」 which suits most providers and matches the spec, but if you need to change it you can set security.oauth2.resource.token-type.

28.3 Customizing the User Info RestTemplate

If you have a user-info-uri, the resource server features use an OAuth2RestTemplate internally to fetch user details for authentication. This is provided as a @Bean of type UserInfoRestTemplateFactory. The default should be fine for most providers, but occasionally you might need to add additional interceptors, or change the request authenticator (which is how the token gets attached to outgoing requests). To add a customization just create a bean of type UserInfoRestTemplateCustomizer - it has a single method that will be called after the bean is created but before it is initialized. The rest template that is being customized here is only used internally to carry out authentication. Alternatively, you could define your own UserInfoRestTemplateFactory @Bean to take full control.

[小費]

To set an RSA key value in YAML use the 「pipe」 continuation marker to split it over multiple lines (「|」) and remember to indent the key value (it’s a standard YAML language feature). Example:

security:
 oauth2:  resource:  jwt:  keyValue: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC... -----END PUBLIC KEY-----

28.3.1 Client

To make your web-app into an OAuth2 client you can simply add @EnableOAuth2Client and Spring Boot will create a OAuth2ClientContext and OAuth2ProtectedResourceDetails that are necessary to create an OAuth2RestOperations. Spring Boot does not automatically create such bean but you can easily create your own:

@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
        OAuth2ProtectedResourceDetails details) {
    return new OAuth2RestTemplate(details, oauth2ClientContext); }
[注意]

You may want to add a qualifier and review your configuration as more than one RestTemplate may be defined in your application.

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 security.oauth2.client.client-authentication-scheme which defaults to 「header」 (but you might need to set it to 「form」 if, like Github for instance, your OAuth2 provider doesn’t like header authentication). In fact, the security.oauth2.client.* properties are bound to an instance of AuthorizationCodeResourceDetails so all its properties can be specified.

[小費]

In a non-web application you can still create an OAuth2RestOperations and it is still wired into the security.oauth2.client.* configuration. In this case it is a 「client credentials token grant」 you will be asking for if you use it (and there is no need to use @EnableOAuth2Client or @EnableOAuth2Sso). To prevent that infrastructure to be defined, just remove the security.oauth2.client.client-id from your configuration (or make it the empty string).

28.3.2 Single Sign On

An OAuth2 Client can be used to fetch user details from the provider (if such features are available) and then convert them into an Authentication token for Spring Security. The Resource Server above support this via the user-info-uri property This is the basis for a Single Sign On (SSO) protocol based on OAuth2, and Spring Boot makes it easy to participate by providing an annotation @EnableOAuth2Sso. The Github client above can protect all its resources and authenticate using the Github /user/ endpoint, by adding that annotation and declaring where to find the endpoint (in addition to the security.oauth2.client.* configuration already listed above):

application.yml. 

security:
 oauth2: ...  resource:  userInfoUri: https://api.github.com/user  preferTokenInfo: false

 

Since all paths are secure by default, there is no 「home」 page that you can show to unauthenticated users and invite them to login (by visiting the /login path, or the path specified by security.oauth2.sso.login-path).

To customize the access rules or paths to protect, so you can add a 「home」 page for instance, @EnableOAuth2Sso can be added to a WebSecurityConfigurerAdapter and the annotation will cause it to be decorated and enhanced with the necessary pieces to get the /login path working. For example, here we simply allow unauthenticated access to the home page at "/" and keep the default for everything else:

@Configuration
static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override public void init(WebSecurity web) { web.ignoring().antMatchers("/"); } @Override protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/**").authorizeRequests().anyRequest().authenticated(); } }

28.4 Actuator Security

If the Actuator is also in use, you will find:

  • The management endpoints are secure even if the application endpoints are insecure.
  • Security events are transformed into AuditEvent instances and published to the AuditEventRepository.
  • The default user will have the 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.

29. Working with SQL databases

The Spring Framework provides extensive support for working with SQL databases. From direct JDBC access using JdbcTemplate to complete ‘object relational mapping’ technologies such as Hibernate. Spring Data provides an additional level of functionality, creating Repository implementations directly from interfaces and using conventions to generate queries from your method names.

29.1 Configure a DataSource

Java’s javax.sql.DataSource interface provides a standard method of working with database connections. Traditionally a DataSource uses a URL along with some credentials to establish a database connection.

[小費]

Check also the ‘How-to’ section for more advanced examples, typically to take full control over the configuration of the DataSource.

29.1.1 Embedded Database Support

It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.

[小費]

The ‘How-to’ section includes a section on how to initialize a database

Spring Boot can auto-configure embedded H2HSQL 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 spring.datasource.generate-unique-name to true.

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 spring-jdbc for an embedded database to be auto-configured. In this example it’s pulled in transitively viaspring-boot-starter-data-jpa.

[小費]

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 DB_CLOSE_ON_EXIT=FALSE to do so. If you’re using HSQLDB, you should ensure that shutdown=true is not used. Disabling the database’s automatic shutdown allows Spring Boot to control when the database is closed, thereby ensuring that it happens once access to the database is no longer needed.

29.1.2 Connection to a production database

Production database connections can also be auto-configured using a pooling DataSource. Here’s the algorithm for choosing a specific implementation:

  • We prefer HikariCP for its performance and concurrency, so if that is available we always choose it.
  • Otherwise, if the Tomcat pooling DataSource is available we will use it.
  • If neither HikariCP nor the Tomcat pooling datasource are available and if Commons DBCP2 is available we will use it.

If you use the spring-boot-starter-jdbc or spring-boot-starter-data-jpa ‘starters’ you will automatically get a dependency to HikariCP.

[注意]

You can bypass that algorithm completely and specify the connection pool to use via the spring.datasource.type property. This is especially important if you are running your application in a Tomcat container as tomcat-jdbc is provided by default.

[小費]

Additional connection pools can always be configured manually. If you define your own DataSource bean, auto-configuration will not occur.

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 spring.datasource.url property or Spring Boot will attempt to auto-configure an embedded database.

[小費]

You often won’t need to specify the driver-class-name since Spring boot can deduce it for most databases from the url.

[注意]

For a pooling DataSource to be created we need to be able to verify that a valid Driver class is available, so we check for that before doing anything. I.e. if you set spring.datasource.driver-class-name=com.mysql.jdbc.Driver then that class has to be loadable.

See DataSourceProperties for more of the supported options. These are the standard options that work regardless of the actual implementation. It is also possible to fine-tune implementation-specific settings using their respective prefix (spring.datasource.hikari.*spring.datasource.tomcat.*, and spring.datasource.dbcp2.*). Refer to the documentation of the connection pool implementation you are using for more details.

For instance, if you are using the Tomcat connection pool you could customize many additional settings:

#若是沒有可用鏈接,則在拋出異常以前要等待的ms數。
spring.datasource.tomcat.max-wait = 10000 #能夠同時從該池分配的最大活動鏈接數。 spring.datasource.tomcat.max-active = 50 #在從池中借用鏈接以前驗證鏈接。 spring.datasource.tomcat.test-on-borrow = true

29.1.3鏈接到JNDI數據源

若是要將Spring Boot應用程序部署到Application Server,則可能須要使用Application Server內置功能配置和管理DataSource,並使用JNDI訪問它。

spring.datasource.jndi-name屬性能夠被用做一個替代 spring.datasource.urlspring.datasource.usernamespring.datasource.password 屬性來訪問DataSource從一個特定的JNDI位置。例如,如下部分application.properties顯示瞭如何訪問定義的JBoss AS DataSource

spring.datasource.jndi-name = java:jboss / datasources / customers

29.2使用JdbcTemplate

Spring JdbcTemplateNamedParameterJdbcTemplate類是自動配置的,你能夠將@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
[小費]

NamedParameterJdbcTemplate重複使用相同的JdbcTemplate幕後狀況。若是JdbcTemplate定義了多個且沒有主要候選項,NamedParameterJdbcTemplate則不會自動配置。

29.3 JPA和'Spring Data'

Java Persistence API是一種標準技術,容許您將對象「映射」到關係數據庫。spring-boot-starter-data-jpaPOM提供了上手的快捷方式。它提供如下關鍵依賴項:

  • Hibernate - 最受歡迎的JPA實現之一。
  • Spring Data JPA - 使實現基於JPA的存儲庫變得容易。
  • Spring ORMs - 來自Spring Framework的核心ORM支持。
[小費]

咱們不會在這裏討論太多關於JPA或Spring Data的細節。您能夠按照 「使用JPA訪問數據」從引導 spring.io並宣讀了春天的數據JPA 和Hibernate的參考文檔。

29.3.1實體類

傳統上,JPA「實體」類在persistence.xml文件中指定使用Spring Boot,此文件不是必需的,而是使用「實體掃描」。默認狀況下,將搜索主配置類下面的全部包(用@EnableAutoConfigurationor 註釋 @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; } //等等  }
[小費]

您能夠使用@EntityScan註釋自定義實體掃描位置請參見第78.4節「從Spring配置中分離@Entity定義」操做方法。

29.3.2 Spring Data JPA存儲庫

Spring Data JPA存儲庫是您能夠定義以訪問數據的接口。JPA查詢是從您的方法名稱自動建立的。例如,CityRepository 接口可能會聲明一種findAllByState(String state)方法來查找給定狀態中的全部城市。

對於更復雜的查詢,您能夠使用Spring Data的Query註釋來註釋您的方法 

Spring Data存儲庫一般從Repository或 CrudRepository接口擴展 若是您使用的是自動配置,則將從包含主配置類(帶有@EnableAutoConfiguration標註的類)的軟件包中搜索存儲庫 @SpringBootApplication

這是一個典型的Spring Data存儲庫:

package com.example.myapp.domain;

import org.springframework.data.domain。*; import org.springframework.data.repository。*; 公共 接口 CityRepository 擴展了 Repository <City,Long> {  Page <City> findAll(可分頁可分頁);  City findByNameAndCountryAllIgnoringCase(String name,String country);  }
[小費]

咱們幾乎沒有涉及Spring Data JPA的表面。有關詳細信息,請查看其參考文檔

29.3.3建立和刪除JPA數據庫

默認狀況下,當您使用嵌入式數據庫(H2,HSQL或Derby)時,纔會自動建立JPA數據庫您能夠使用spring.jpa.*屬性顯式配置JPA設置 例如,要建立和刪除表,您能夠將如下內容添加到您的表中application.properties

spring.jpa.hibernate.ddl-AUTO =創造降
[注意]

Hibernate本身的內部屬性名稱(若是你碰巧記得更好)是hibernate.hbm2ddl.auto您能夠使用spring.jpa.properties.*(在將它們添加到實體管理器以前剝離前綴)來設置它以及其餘Hibernate本機屬性例:

spring.jpa.properties.hibernate.globally_quoted_identifiers =真

傳遞hibernate.globally_quoted_identifiers給Hibernate實體管理器。

默認狀況下,DDL執行(或驗證)將延遲到ApplicationContext 啓動。還有一個spring.jpa.generate-ddl標誌,但若是Hibernate autoconfig處於活動狀態,則不會使用標誌,由於ddl-auto設置更精細。

29.3.4在視圖中打開EntityManager

若是您正在運行Web應用程序,Spring Boot將默認註冊 OpenEntityManagerInViewInterceptor 以應用「在視圖中打開EntityManager」模式,即容許在Web視圖中進行延遲加載。若是你不但願這種行爲,你應該設置spring.jpa.open-in-view到 falseapplication.properties

29.4使用H2的Web控制檯

H2數據庫提供了一個 基於瀏覽器的控制檯是春天開機便可自動爲您配置。知足如下條件時,將自動配置控制檯:

[小費]

若是您沒有使用Spring Boot的開發人員工具,但仍想使用H2的控制檯,那麼您能夠經過配置spring.h2.console.enabled 值爲屬性來實現trueH2控制檯僅用於開發期間,所以應注意確保spring.h2.console.enabledtrue在生產中設置

29.4.1更改H2控制檯的路徑

默認狀況下,控制檯將在/h2-console您能夠使用spring.h2.console.path屬性自定義控制檯的路徑

29.4.2固定H2控制檯

當Spring Security在類路徑上而且啓用了基自己份驗證時,H2控制檯將使用基自己份驗證自動保護。如下屬性可用於自定義安全性配置:

  • security.user.role
  • security.basic.authorize-mode
  • security.basic.enabled

29.5使用jOOQ

Java面向對象查詢(jOOQ)是Data Geekery的一個流行產品, 它從您的數據庫生成Java代碼,並容許您經過其流暢的API構建類型安全的SQL查詢。商業版和開源版均可以與Spring Boot一塊兒使用。

29.5.1代碼生成

In order to use jOOQ type-safe queries, you need to generate Java classes from your database schema. You can follow the instructions in the jOOQ user manual. If you are using the jooq-codegen-maven plugin (and you also use the spring-boot-starter-parent 「parent POM」) you can safely omit the plugin’s <version> tag. You can also use Spring Boot defined version variables (e.g. h2.version) to declare the plugin’s database dependency. Here’s an example:

<plugin>
    <groupId>org.jooq</groupId> <artifactId>jooq-codegen-maven</artifactId> <executions> ... </executions> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>${h2.version}</version> </dependency> </dependencies> <configuration> <jdbc> <driver>org.h2.Driver</driver> <url>jdbc:h2:~/yourdatabase</url> </jdbc> <generator> ... </generator> </configuration> </plugin>

29.5.2 Using DSLContext

The fluent API offered by jOOQ is initiated via the org.jooq.DSLContext interface. Spring Boot will auto-configure a DSLContext as a Spring Bean and connect it to your application DataSource. To use the DSLContext you can just @Autowire it:

@Component
public class JooqExample implements CommandLineRunner { private final DSLContext create; @Autowired public JooqExample(DSLContext dslContext) { this.create = dslContext; } }
[小費]

The jOOQ manual tends to use a variable named create to hold the DSLContext, we’ve done the same for this example.

You can then use the DSLContext to construct your queries:

public List<GregorianCalendar> authorsBornAfter1980() {
    return this.create.selectFrom(AUTHOR) .where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1))) .fetch(AUTHOR.DATE_OF_BIRTH); }

29.5.3 jOOQ SQL dialect

Spring Boot determines the SQL dialect to use for your datasource unless the spring.jooq.sql-dialect property has been configured. If the dialect couldn’t be detected, DEFAULT is used.

[注意]

Spring Boot can only auto-configure dialects supported by the open source version of jOOQ.

29.5.4 Customizing jOOQ

More advanced customizations can be achieved by defining your own @Bean definitions which will be used when the jOOQ Configuration is created. You can define beans for the following jOOQ Types:

  • ConnectionProvider
  • TransactionProvider
  • RecordMapperProvider
  • RecordListenerProvider
  • ExecuteListenerProvider
  • VisitListenerProvider

You can also create your own org.jooq.Configuration @Bean if you want to take complete control of the jOOQ configuration.

30. Working with NoSQL technologies

Spring Data provides additional projects that help you access a variety of NoSQL technologies including MongoDBNeo4JElasticsearchSolrRedisGemfire,CassandraCouchbase and LDAP. Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Elasticsearch, Solr Cassandra, Couchbase and LDAP; you can make use of the other projects, but you will need to configure them yourself. Refer to the appropriate reference documentation at projects.spring.io/spring-data.

30.1 Redis

Redis is a cache, message broker and richly-featured key-value store. Spring Boot offers basic auto-configuration for the Jedis and Lettuce client library and abstractions on top of it provided by Spring Data Redis.

There is a spring-boot-starter-data-redis ‘Starter’ for collecting the dependencies in a convenient way that uses Jedis by default. If you are building a reactive application, the spring-boot-starter-data-redis-reactive ‘Starter’ will get you going.

30.1.1 Connecting to Redis

You can inject an auto-configured RedisConnectionFactoryStringRedisTemplate 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,以實現 JedisClientConfigurationBuilderCustomizer更高級的自定義。若是您正在使用生菜,LettuceClientConfigurationBuilderCustomizer也能夠。

若是您添加@Bean本身的任何自動配置類型,它將替換默認值(除非RedisTemplate排除是基於bean名稱'redisTemplate'而不是其類型)。若是commons-pool2在類路徑上,默認狀況下您將得到池鏈接工廠。

30.2 MongoDB

MongoDB是一個開源的NoSQL文檔數據庫,它使用相似JSON的模式而不是傳統的基於表的關係數據。Spring Boot提供了一些使用MongoDB的便利,包括spring-boot-starter-data-mongodbspring-boot-starter-data-mongodb-reactive 'Starters'。

30.2.1鏈接MongoDB數據庫

您能夠注入自動配置org.springframework.data.mongodb.MongoDbFactory以訪問Mongo數據庫。默認狀況下,實例將嘗試使用URL鏈接到MongoDB服務器mongodb://localhost/test

import org.springframework.data.mongodb.MongoDbFactory; import com.mongodb.DB; @Component 公共  MyBean { 私人 決賽 MongoDbFactory mongo; @Autowired  public MyBean(MongoDbFactory mongo){  this .mongo = mongo; } // ... public void example(){ DB db = mongo.getDb(); // ... }  }

您能夠設置spring.data.mongodb.uri屬性以更改URL並配置其餘設置,例如副本集

spring.data.mongodb.uri = mongodb:// user:secret@mongo1.example.com :12345,mongo2.example.com:23456 / test

或者,只要您使用Mongo 2.x,請指定hostport例如,您能夠在如下內容中聲明如下內容application.properties

spring.data.mongodb.host = mongoserver spring.data.mongodb.port = 27017
[注意]

spring.data.mongodb.hostspring.data.mongodb.port若是您使用的是Mongo 3.0 Java驅動程序則不受支持。在這種狀況下,spring.data.mongodb.uri應該用於提供全部配置。

[小費]

若是spring.data.mongodb.port未指定,27017則使用默認值您能夠從上面的示例中刪除此行。

[小費]

若是您不使用Spring Data Mongo,則能夠注入com.mongodb.Mongobean而不是使用MongoDbFactory

若是要徹底控制創建MongoDB鏈接,也能夠聲明本身的bean MongoDbFactoryMongobean。

30.2.2 MongoTemplate

Spring Data Mongo提供了一個MongoTemplate與Spring的設計很是類似的 JdbcTemplateJdbcTemplateSpring Boot同樣,自動配置一個bean,只需注入:

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; @Component 公共  MyBean { 私人 決賽 MongoTemplate mongoTemplate; @Autowired  public MyBean(MongoTemplate mongoTemplate){  this .mongoTemplate = mongoTemplate; } // ...  }

有關MongoOperations完整的詳細信息,請參閱Javadoc。

30.2.3 Spring Data MongoDB存儲庫

Spring Data包括MongoDB的存儲庫支持。與前面討論的JPA存儲庫同樣,基本原則是根據方法名稱自動爲您構建查詢。

事實上,Spring Data JPA和Spring Data MongoDB共享相同的通用基礎架構; 因此你能夠從前面拿到JPA示例,假設它City 如今是一個Mongo數據類而不是JPA @Entity,它將以相同的方式工做。

package com.example.myapp.domain;

import org.springframework.data.domain。*; import org.springframework.data.repository。*; 公共 接口 CityRepository 擴展了 Repository <City,Long> {  Page <City> findAll(可分頁可分頁);  City findByNameAndCountryAllIgnoringCase(String name,String country);  }
[小費]

有關Spring Data MongoDB的完整詳細信息,包括其豐富的對象映射技術,請參閱其參考文檔

30.2.4嵌入式Mongo

Spring Boot爲Embedded Mongo提供自動配置 要在Spring Boot應用程序中使用它,請添加依賴項 de.flapdoodle.embed:de.flapdoodle.embed.mongo

能夠使用該spring.data.mongodb.port 屬性配置Mongo將偵聽的端口要使用隨機分配的空閒端口,請使用零值。MongoClient 由建立MongoAutoConfiguration將被自動配置爲使用隨機分配的端口。

[注意]

若是您不配置自定義端口,則默認狀況下嵌入式支持將使用隨機端口(而不是27017)。

若是類路徑上有SLF4J,Mongo生成的輸出將自動路由到名爲的記錄器org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo

您能夠聲明本身的bean IMongodConfigIRuntimeConfigbean來控制Mongo實例的配置和日誌記錄路由。

30.3 Neo4j

Neo4j是一個開源的NoSQL圖形數據庫,它使用與第一類關係相關的節點的豐富數據模型,與傳統的rdbms方法相比,它更適合於鏈接的大數據。Spring Boot爲使用Neo4j提供了一些便利,包括spring-boot-starter-data-neo4j「Starter」。

30.3.1鏈接到Neo4j數據庫

你能夠注入的自動配置Neo4jSessionSession或者Neo4jOperations,就像任何其餘的Spring Bean實例。默認狀況下,實例將嘗試使用如下命令鏈接到Neo4j服務器localhost:7474

@Component
公共  MyBean { private final Neo4jTemplate neo4jTemplate; @Autowired public MyBean(Neo4jTemplate neo4jTemplate) { this.neo4jTemplate = neo4jTemplate; } // ... }

You can take full control of the configuration by adding a org.neo4j.ogm.config.Configuration @Bean of your own. Also, adding a @Bean of typeNeo4jOperations disables the auto-configuration.

You can configure the user and credentials to use via the spring.data.neo4j.* properties:

spring.data.neo4j.uri=http://my-server:7474
spring.data.neo4j.username=neo4j spring.data.neo4j.password=secret

30.3.2 Using the embedded mode

若是添加org.neo4j:neo4j-ogm-embedded-driver到應用程序的依賴項,Spring Boot將自動配置Neo4j的進程內嵌入式實例,在應用程序關閉時不會保留任何數據。您能夠使用顯式禁用該模式spring.data.neo4j.embedded.enabled=false您還能夠爲嵌入模式啓用持久性:

	spring.data.neo4j.uri =文件://var/tmp/graph.db
[注意]

Neo4j OGM嵌入式驅動程序不提供Neo4j內核。用戶須要手動提供此依賴關係, 有關詳細信息,請參閱 文檔

30.3.3 Neo4jSession

默認狀況下,若是您正在運行Web應用程序,則會話將綁定到線程以進行整個請求處理(即「在視圖中打開會話」模式)。若是您不想要此行爲,請將如下內容添加到您的application.properties

	spring.data.neo4j.open式視=假

30.3.4 Spring Data Neo4j存儲庫

Spring Data包含對Neo4j的存儲庫支持。

事實上,Spring Data JPA和Spring Data Neo4j共享相同的通用基礎架構; 因此你能夠從前面拿到JPA例子,假設City 如今是Neo4j OGM @NodeEntity而不是JPA @Entity,它將以相同的方式工做。

[小費]

您能夠使用@EntityScan註釋自定義實體掃描位置

要啓用存儲庫支持(以及可選的支持@Transactional),請在Spring配置中添加如下兩個註釋:

@ EnableNeo4jRepositories(basePackages =「com.example.myapp.repository」) 
@EnableTransactionManagement

30.3.5存儲庫示例

package com.example.myapp.domain;

import org.springframework.data.domain。*; import org.springframework.data.repository。*; 公共 接口 CityRepository 擴展了 GraphRepository <City> {  Page <City> findAll(可分頁可分頁);  City findByNameAndCountry(String name,String country);  }
[小費]

有關Spring Data Neo4j的完整詳細信息,包括其豐富的對象映射技術,請參閱其參考文檔

30.4 Gemfire

Spring Data Gemfire提供了方便的Spring友好工具,用於訪問 Pivotal Gemfire數據管理平臺。有一個spring-boot-starter-data-gemfire'Starter'用於以方便的方式收集依賴項。目前沒有對Gemfire的自動配置支持,但您能夠使用單個註釋(@EnableGemfireRepositories啓用S​​pring Data Repositories 

30.5 Solr

Apache Solr是一個搜索引擎。Spring Boot爲Solr 5客戶端庫提供基本的自動配置,並在Spring Data Solr提供的基礎上提供抽象 有一個spring-boot-starter-data-solr'Starter'用於以方便的方式收集依賴項。

30.5.1鏈接到Solr

You can inject an auto-configured SolrClient instance as you would any other Spring bean. By default the instance will attempt to connect to a server usinglocalhost:8983/solr:

@Component
public class MyBean { private SolrClient solr; @Autowired public MyBean(SolrClient solr) { this.solr = solr; } // ... }

If you add a @Bean of your own of type SolrClient it will replace the default.

30.5.2 Spring Data Solr repositories

Spring Data includes repository support for Apache Solr. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.

In fact, both Spring Data JPA and Spring Data Solr share the same common infrastructure; so you could take the JPA example from earlier and, assuming that City is now a @SolrDocument class rather than a JPA @Entity, it will work in the same way.

[小費]

For complete details of Spring Data Solr, refer to their reference documentation.

30.6 Elasticsearch

Elasticsearch is an open source, distributed, real-time search and analytics engine. Spring Boot offers basic auto-configuration for the Elasticsearch and abstractions on top of it provided by Spring Data Elasticsearch. There is a spring-boot-starter-data-elasticsearch ‘Starter’ for collecting the dependencies in a convenient way. Spring Boot also supports Jest.

30.6.1 Connecting to Elasticsearch using Jest

If you have Jest on the classpath, you can inject an auto-configured JestClient targeting localhost:9200 by default. You can further tune how the client is configured:

spring.elasticsearch.jest.uris=http://search.example.com:9200
spring.elasticsearch.jest.read-timeout=10000 spring.elasticsearch.jest.username=user spring.elasticsearch.jest.password=secret

You can also register an arbitrary number of beans implementing HttpClientConfigBuilderCustomizer for more advanced customizations. The example below tunes additional HTTP settings:

static class HttpSettingsCustomizer implements HttpClientConfigBuilderCustomizer { @Override public void customize(HttpClientConfig.Builder builder) { builder.maxTotalConnection(100).defaultMaxTotalConnectionPerRoute(5); } }

To take full control over the registration, define a JestClient bean.

30.6.2 Connecting to Elasticsearch using Spring Data

To connect to Elasticsearch you must provide the address of one or more cluster nodes. The address can be specified by setting the spring.data.elasticsearch.cluster-nodes property to a comma-separated ‘host:port’ list. With this configuration in place, an ElasticsearchTemplate or TransportClient can be injected like any other Spring bean:

spring.data.elasticsearch.cluster-nodes=localhost:9300
@Component
public class MyBean { private final ElasticsearchTemplate template; public MyBean(ElasticsearchTemplate template) { this.template = template; } // ... }

If you add your own ElasticsearchTemplate or TransportClient @Bean it will replace the default.

30.6.3 Spring Data Elasticsearch repositories

Spring Data includes repository support for Elasticsearch. As with the JPA repositories discussed earlier, the basic principle is that queries are constructed for you automatically based on method names.

In fact, both Spring Data JPA and Spring Data Elasticsearch share the same common infrastructure; so you could take the JPA example from earlier and, assuming thatCity is now an Elasticsearch @Document class rather than a JPA @Entity, it will work in the same way.

[小費]

有關Spring Data Elasticsearch的完整詳細信息,請參閱其 參考文檔

30.7卡桑德拉

Cassandra是一個開源的分佈式數據庫管理系統,旨在處理許多商用服務器上的大量數據。Spring Boot提供了由Spring Data Cassandra提供的Cassandra和抽象的自動配置 有一個spring-boot-starter-data-cassandra'Starter'用於以方便的方式收集依賴項。

30.7.1鏈接到Cassandra

您能夠 像使用任何其餘Spring Bean同樣注入自動配置CassandraTemplate或Cassandra Session實例。這些spring.data.cassandra.* 屬性可用於自定義鏈接。通常來講,您將提供 keyspace-namecontact-points屬性:

spring.data.cassandra.keyspace-name = mykeyspace spring.data.cassandra.contact-points = cassandrahost1,cassandrahost2
@Component
公共  MyBean { 私人 CassandraTemplate模板; @Autowired  public MyBean(CassandraTemplate模板){  this .template = template; } // ...  }

若是您添加@Bean本身的類型CassandraTemplate,它將替換默認值。

30.7.2 Spring Data Cassandra存儲庫

Spring Data包含對Cassandra的基本存儲庫支持。目前,這比前面討論的JPA存儲庫更有限,而且須要使用註釋方法註釋@Query

[小費]

有關Spring Data Cassandra的完整詳細信息,請參閱其 參考文檔

30.8 Couchbase

Couchbase是一個開源的,分佈式的多模型NoSQL面向文檔的數據庫,針對交互式應用程序進行了優化。Spring Boot提供了由Spring Data Couchbase提供的Couchbase和抽象的自動配置 有一個spring-boot-starter-data-couchbase'Starter'用於以方便的方式收集依賴項。

30.8.1鏈接Couchbase

您能夠很是輕鬆地得到BucketCluster添加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 default and the password is the empty String. Alternatively, you can define your own org.springframework.data.couchbase.config.CouchbaseConfigurer @Bean to take control over the whole configuration.

It is also possible to customize some of the CouchbaseEnvironment settings. For instance the following configuration changes the timeout to use to open a new Bucket and enables SSL support:

spring.couchbase.env.timeouts.connect = 3000 spring.couchbase.env.ssl.key-store = / location / of / keystore.jks spring.couchbase.env.ssl.key-store-password = secret

檢查spring.couchbase.env.*屬性以獲取更多詳細信息。

30.8.2 Spring Data Couchbase存儲庫

Spring Data包括對Couchbase的存儲庫支持。有關Spring Data Couchbase的完整詳細信息,請參閱其 參考文檔

您能夠CouchbaseTemplate像使用任何其餘Spring Bean同樣注入自動配置的實例,只要默認 CouchbaseConfigurer值可用(當您啓用如上所述的couchbase支持時就會發生這種狀況)。

@Component
公共  MyBean { 私人 決賽 CouchbaseTemplate模板; @Autowired  public MyBean(CouchbaseTemplate template){  this .template = template; } // ...  }

您能夠在本身的配置中定義一些bean來覆蓋自動配置提供的bean:

  • 一個CouchbaseTemplate @Bean名字couchbaseTemplate
  • 一個IndexManager @Bean名字couchbaseIndexManager
  • 一個CustomConversions @Bean名字couchbaseCustomConversions

爲避免在您本身的配置中對這些名稱進行硬編碼,您能夠重複使用BeanNamesSpring Data Couchbase。例如,您能夠自定義要使用的轉換器,以下所示:

@Configuration
公共  SomeConfiguration { @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)  public CustomConversions myCustomConversions(){  return new CustomConversions(...); } // ...  }
[小費]

若是要徹底繞過Spring Data Couchbase的自動配置,請提供本身的org.springframework.data.couchbase.config.AbstractCouchbaseDataConfiguration 實現。

30.9 LDAP

LDAP(輕量級目錄訪問協議)是一種開放的,與供應商無關的行業標準應用程序協議,用於經過IP網絡訪問和維護分佈式目錄信息服務。Spring Boot爲任何兼容的LDAP服務器提供自動配置,併爲UnboundID支持嵌入式內存中LDAP服務器 

LDAP抽象由 Spring Data LDAP提供有一個spring-boot-starter-data-ldap'Starter'用於以方便的方式收集依賴項。

30.9.1鏈接LDAP服務器

要鏈接到LDAP服務器,請確保聲明對spring-boot-starter-data-ldap「Starter」 的依賴關係, 或者spring-ldap-core在application.properties中聲明服務器的URL:

spring.ldap.urls = ldap:// myserver:1235 spring.ldap.username = admin spring.ldap.password = secret

若是須要自定義鏈接設置,能夠使用spring.ldap.base和 spring.ldap.base-environment屬性。

30.9.2 Spring Data LDAP存儲庫

Spring Data includes repository support for LDAP. For complete details of Spring Data LDAP, refer to their reference documentation.

You can also inject an auto-configured LdapTemplate instance as you would with any other Spring Bean.

@Component
public class MyBean { private final LdapTemplate template; @Autowired public MyBean(LdapTemplate template) { this.template = template; } // ... }

30.9.3 Embedded in-memory LDAP server

For testing purposes Spring Boot supports auto-configuration of an in-memory LDAP server from UnboundID. To configure the server add a dependency to com.unboundid:unboundid-ldapsdk and declare a base-dn property:

spring.ldap.embedded.base-dn=dc=spring,dc=io

By default the server will start on a random port and they trigger the regular LDAP support (there is no need to specify a spring.ldap.urls property).

If there is a schema.ldif file on your classpath it will be used to initialize the server. You can also use the spring.ldap.embedded.ldif property if you want to load the initialization script from a different resource.

By default, a standard schema will be used to validate LDIF files, you can turn off validation altogether using the spring.ldap.embedded.validation.enabledproperty. If you have custom attributes, you can use spring.ldap.embedded.validation.schema to define your custom attribute types or object classes.

30.10 InfluxDB

InfluxDB is an open-source time series database optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet of Things sensor data, and real-time analytics.

30.10.1 Connecting to InfluxDB

Spring Boot auto-configures an InfluxDB instance as long as the influxdb-java client is on the classpath and the url of the database is set:

spring.influx.url=http://172.0.0.1:8086

If the connection to InfluxDB requires a user and password, you can set the spring.influx.user and spring.influx.password properties accordingly.

InfluxDB relies on OkHttp. If you need to tune the http client InfluxDB uses behind the scenes, you can register a OkHttpClient.Builder bean.

31. Caching

Spring Framework支持透明地嚮應用程序添加緩存。從本質上講,抽象將緩存應用於方法,從而減小了基於緩存中可用信息的執行次數。緩存邏輯是透明應用的,不會對調用者形成任何干擾。只要經過@EnableCaching 註釋啓用了緩存支持,Spring Boot就會自動配置緩存基礎結構

[注意]

有關更多詳細信息,請查看Spring Framework參考相關部分

簡而言之,將緩存添加到服務操做就像在其方法中添加相關注釋同樣簡單:

import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Component; @Component 公共  MathService { @Cacheable(「piDecimals」)  public int computePiDecimal( int i){  // ... }  }

此示例演示瞭如何在可能代價高昂的操做上使用緩存。在調用以前computePiDecimal,抽象將在piDecimals 與i參數匹配的緩存中查找條目若是找到條目,則緩存中的內容會當即返回給調用者,而且不會調用該方法。不然,在返回值以前調用該方法並更新緩存。

[注意]

您還能夠@CacheResult透明地使用標準JSR-107(JCache)註釋(例如)。但咱們強烈建議您不要混用和匹配它們。

若是您不添加任何特定的緩存庫,Spring Boot將自動配置在內存中使用併發映射的 Simple提供程序當須要緩存時(即piDecimals在上面的示例中),此提供程序將爲您即時建立它。簡單的提供程序並非真正推薦用於生產用途,但它很是適合入門並確保您瞭解這些功能。當您決定使用緩存提供程序時,請務必閱讀其文檔以瞭解如何配置應用程序使用的緩存。實際上,全部提供程序都要求您顯式配置在應用程序中使用的每一個緩存。有些提供了一種自定義spring.cache.cache-names屬性定義的默認緩存的方法

[小費]

還能夠透明更新或 逐出緩存中的數據。

[注意]

若是您使用的緩存基礎結構包含非基於接口的bean,請確保啓用該proxyTargetClass屬性@EnableCaching

31.1支持的緩存提供程序

緩存抽象不提供實際存儲,而是依賴於org.springframework.cache.Cache和 org.springframework.cache.CacheManager接口實現的抽象

若是還沒有定義類型的bean CacheManagerCacheResolver命名 的bean cacheResolver(請參閱參考資料CachingConfigurer),Spring Boot會嘗試檢測如下提供程序(按此順序):

[小費]

It is also possible to force the cache provider to use via the spring.cache.type property. Use this property if you need to disable caching altogether in certain environment (e.g. tests).

[小費]

Use the spring-boot-starter-cache ‘Starter’ to quickly add basic caching dependencies. The starter brings in spring-context-support: if you are adding dependencies manually, you must include spring-context-support in order to use the JCache, EhCache 2.x or Guava support.

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 ConcurrentMapCacheManager is expected. If that is not the case (either you provided your own config or a different cache provider was auto-configured), the customizer won’t be invoked at all. You can have as many customizers as you want and you can also order them as usual using @Order or Ordered.

31.1.1 Generic

Generic caching is used if the context defines at least one org.springframework.cache.Cache bean. A CacheManager wrapping all beans of that type is created.

31.1.2 JCache (JSR-107)

JCache is bootstrapped via the presence of a javax.cache.spi.CachingProvider on the classpath (i.e. a JSR-107 compliant caching library) and the JCacheCacheManager provided by the spring-boot-starter-cache ‘Starter’. There are various compliant libraries out there and Spring Boot provides dependency management for Ehcache 3, Hazelcast and Infinispan. Any other compliant library can be added as well.

It might happen that more than one provider is present, in which case the provider must be explicitly specified. Even if the JSR-107 standard does not enforce a standardized way to define the location of the configuration file, Spring Boot does its best to accommodate with implementation details.

# Only necessary if more than one provider is present
spring.cache.jcache.provider=com.acme.MyCachingProvider spring.cache.jcache.config=classpath:acme.xml
[注意]

Since a cache library may offer both a native implementation and JSR-107 support Spring Boot will prefer the JSR-107 support so that the same features are available if you switch to a different JSR-107 implementation.

[小費]

Spring Boot has a general support for Hazelcast. If a single HazelcastInstance is available, it is automatically reused for the CacheManager as well unless the spring.cache.jcache.config property is specified.

There are several ways to customize the underlying javax.cache.cacheManager:

  • Caches can be created on startup via the spring.cache.cache-names property. If a 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 javax.cache.CacheManager bean is defined, it is wrapped automatically in a org.springframework.cache.CacheManagerimplementation that the abstraction expects. No further customization is applied on it.

31.1.3 EhCache 2.x

EhCache 2.x is used if a file named ehcache.xml can be found at the root of the classpath. If EhCache 2.x, the EhCacheCacheManager provided by thespring-boot-starter-cache ‘Starter’ and such file is present it is used to bootstrap the cache manager. An alternate configuration file can be provided as well using:

spring.cache.ehcache.config=classpath:config/another-config.xml

31.1.4 Hazelcast

Spring Boot has a general support for Hazelcast. If a HazelcastInstance has been auto-configured, it is automatically wrapped in a CacheManager.

31.1.5 Infinispan

Infinispan has no default configuration file location so it must be specified explicitly (or the default bootstrap is used).

spring.cache.infinispan.config=infinispan.xml

Caches can be created on startup via the spring.cache.cache-names property. If a custom ConfigurationBuilder bean is defined, it is used to customize them.

[注意]

The support of Infinispan in Spring Boot is restricted to the embedded mode and is quite basic. If you want more options you should use the official Infinispan Spring Boot starter instead, check the documentation for more details.

31.1.6 Couchbase

If the Couchbase java client and the couchbase-spring-cache implementation are available and Couchbase is configured, a CouchbaseCacheManager will be auto-configured. It is also possible to create additional caches on startup using the spring.cache.cache-names property. These will operate on the Bucket that was auto-configured. You can also create additional caches on another Bucket using the customizer: assume you need two caches on the "main" Bucket (foo and bar) and one biz cache with a custom time to live of 2sec on the another Bucket. First, you can create the two first caches simply via configuration:

spring.cache.cache-names=foo,bar

Then define this extra @Configuration to configure the extra Bucket and the biz cache:

@Configuration
public class CouchbaseCacheConfiguration { private final Cluster cluster; public CouchbaseCacheConfiguration(Cluster cluster) { this.cluster = cluster; } @Bean public Bucket anotherBucket() { return this.cluster.openBucket("another", "secret"); } @Bean public CacheManagerCustomizer<CouchbaseCacheManager> cacheManagerCustomizer() { return c -> { c.prepareCache("biz", CacheBuilder.newInstance(anotherBucket()) .withExpiration(2)); }; } }

This sample configuration reuses the Cluster that was created via auto-configuration.

31.1.7 Redis

If Redis is available and configured, the RedisCacheManager is auto-configured. It is also possible to create additional caches on startup using the spring.cache.cache-names property.

[注意]

By default, a key prefix is added to prevent that if two separate caches use the same key, Redis would have overlapping keys and be likely to return invalid values. We strongly recommend to keep this setting enabled if you create your own RedisCacheManager.

31.1.8 Caffeine

Caffeine is a Java 8 rewrite of Guava’s cache that supersede the Guava support. If Caffeine is present, a CaffeineCacheManager (provided by thespring-boot-starter-cache ‘Starter’) is auto-configured. Caches can be created on startup using the spring.cache.cache-names property and customized by one of the following (in this order):

  1. A cache spec defined by spring.cache.caffeine.spec
  2. com.github.benmanes.caffeine.cache.CaffeineSpec bean is defined
  3. com.github.benmanes.caffeine.cache.Caffeine bean is defined

For instance, the following configuration creates a foo and bar caches with a maximum size of 500 and a time to live of 10 minutes

spring.cache.cache-names=foo,bar
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

此外,若是com.github.benmanes.caffeine.cache.CacheLoader定義bean,它會自動關聯到CaffeineCacheManager因爲CacheLoader它將與緩存管理器管理的全部緩存相關聯,所以必須將其定義爲CacheLoader<Object, Object>自動配置將忽略任何其餘泛型類型。

31.1.9簡單

若是找不到其餘提供程序,ConcurrentHashMap則配置使用as cache store 的簡單實現 若是應用程序中不存在緩存庫,則這是默認值。默認狀況下,即時建立緩存,但您能夠使用該cache-names屬性限制可用緩存的列表例如,若是您只想foobar緩存:

spring.cache.cache-names = foo,bar

若是執行此操做而且您的應用程序使用未列出的緩存,那麼在運行時須要緩存時它將失敗,但在啓動時則不會。這相似於「真實」緩存提供程序在使用未聲明的緩存時的行爲方式。

31.1.10無

若是@EnableCaching配置中存在,則還須要合適的緩存配置。若是您須要在某些環境中徹底禁用緩存,請強制緩存類型none使用no-op實現:

spring.cache.type = none

32.消息傳遞

Spring Framework爲與消息傳遞系統的集成提供了普遍的支持:從簡化使用JMS API JmsTemplate到完整的基礎架構,以異步接收消息。Spring AMQP爲「高級消息隊列協議」提供了相似的功能集,Spring Boot還爲RabbitTemplateRabbitMQ 提供了自動配置選項Spring WebSocket自己也支持STOMP消息傳遞,Spring Boot經過啓動器和少許自動配置支持。Spring Boot也支持Apache Kafka。

32.1 JMS

javax.jms.ConnectionFactory接口提供了一種建立javax.jms.Connection與JMS代理交互的標準方法 雖然Spring須要 ConnectionFactory使用JMS,但您一般不須要本身直接使用它,而是能夠依賴於更高級別的消息傳遞抽象(有關詳細信息,請參閱Spring Framework參考文檔的 相關部分)。Spring Boot還自動配置發送和接收消息所需的基礎結構。

32.1.1 ActiveMQ支持

Spring Boot還能夠ConnectionFactory在檢測到ActiveMQ在類路徑上可用時進行配置。若是代理存在,則會自動啓動並配置嵌入式代理(只要經過配置未指定代理URL)。

[注意]

若是您正在使用spring-boot-starter-activemq必要的依賴項來鏈接或嵌入ActiveMQ實例,以及與JMS集成的Spring基礎結構。

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
[小費]

有關ActiveMQProperties 更多支持的選項,請參閱 您還能夠註冊任意數量的bean,以實現ActiveMQConnectionFactoryCustomizer更高級的自定義。

默認狀況下,ActiveMQ會建立一個目標(若是它尚不存在),所以目標將根據其提供的名稱進行解析。

32.1.2阿爾忒彌斯支持

Spring Boot can auto-configure a ConnectionFactory when it detects that Artemis is available on the classpath. If the broker is present, an embedded broker is started and configured automatically (unless the mode property has been explicitly set). The supported modes are: embedded (to make explicit that an embedded broker is required and should lead to an error if the broker is not available in the classpath), and native to connect to a broker using the netty transport protocol. When the latter is configured, Spring Boot configures a ConnectionFactory connecting to a broker running on the local machine with the default settings.

[注意]

If you are using spring-boot-starter-artemis the necessary dependencies to connect to an existing Artemis instance are provided, as well as the Spring infrastructure to integrate with JMS. Adding org.apache.activemq:artemis-jms-server to your application allows you to use the embedded mode.

Artemis configuration is controlled by external configuration properties in spring.artemis.*. For example, you might declare the following section inapplication.properties:

spring.artemis.mode=native
spring.artemis.host=192.168.1.210 spring.artemis.port=9876 spring.artemis.user=admin spring.artemis.password=secret

When embedding the broker, you can choose if you want to enable persistence, and the list of destinations that should be made available. These can be specified as a comma-separated list to create them with the default options; or you can define bean(s) of typeorg.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration or org.apache.activemq.artemis.jms.server.config.TopicConfiguration, for advanced queue and topic configurations respectively.

See ArtemisProperties for more of the supported options.

No JNDI lookup is involved at all and destinations are resolved against their names, either using the ‘name’ attribute in the Artemis configuration or the names provided through configuration.

32.1.3 Using a JNDI ConnectionFactory

If you are running your application in an Application Server Spring Boot will attempt to locate a JMS ConnectionFactory using JNDI. By default the locations java:/JmsXA and java:/XAConnectionFactory will be checked. You can use the spring.jms.jndi-name property if you need to specify an alternative location:

spring.jms.jndi-name=java:/MyConnectionFactory

32.1.4 Sending a message

Spring’s JmsTemplate is auto-configured and you can autowire it directly into your own beans:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final JmsTemplate jmsTemplate; @Autowired public MyBean(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } // ... }
[注意]

JmsMessagingTemplate can be injected in a similar manner. If a DestinationResolver or MessageConverter beans are defined, they are associated automatically to the auto-configured JmsTemplate.

32.1.5 Receiving a message

When the JMS infrastructure is present, any bean can be annotated with @JmsListener to create a listener endpoint. If no JmsListenerContainerFactory has been defined, a default one is configured automatically. If a DestinationResolver or MessageConverter beans are defined, they are associated automatically to the default factory.

The default factory is transactional by default. If you are running in an infrastructure where a JtaTransactionManager is present, it will be associated to the listener container by default. If not, the sessionTransacted flag will be enabled. In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding @Transactional on your listener method (or a delegate thereof). This will make sure that the incoming message is acknowledged once the local transaction has completed. This also includes sending response messages that have been performed on the same JMS session.

The following component creates a listener endpoint on the someQueue destination:

@Component
public class MyBean { @JmsListener(destination =「someQueue」)  public void processMessage(String content){  // ... }  }
[小費]

查看Javadoc以@EnableJms 獲取更多詳細信息。

若是您須要建立更多JmsListenerContainerFactory實例,或者若是要覆蓋默認實例,則Spring Boot提供了一個DefaultJmsListenerContainerFactoryConfigurer 可用於初始化a DefaultJmsListenerContainerFactory的設置,其設置與自動配置的設置相同。

例如,如下公開了另外一個使用特定的工廠 MessageConverter

@Configuration
靜態  JmsConfiguration { @Bean  public DefaultJmsListenerContainerFactory myFactory( DefaultJmsListenerContainerFactoryConfigurer configurer){ DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory,connectionFactory()); factory.setMessageConverter(myMessageConverter()); 返回工廠; }  }

而後您能夠在任何@JmsListener註釋方法中使用以下:

@Component
公共  MyBean {  @JmsListener(destination = 「someQueue」containerFactory =「myFactory」public void processMessage(String content){ // ... }  }

32.2 AMQP

高級消息隊列協議(AMQP)是面向消息的中間件的平臺中立的線級協議。Spring AMQP項目將核心Spring概念應用於基於AMQP的消息傳遞解決方案的開發。Spring Boot提供了幾種經過RabbitMQ使用AMQP的便利,包括 spring-boot-starter-amqp'Starter'。

32.2.1 RabbitMQ支持

RabbitMQ是一個基於AMQP協議的輕量級,可靠,可擴展且可移植的消息代理。Spring使用RabbitMQAMQP協議進行通訊。

RabbitMQ配置由外部配置屬性控制 spring.rabbitmq.*例如,您能夠在如下部分聲明如下部分 application.properties

spring.rabbitmq.host = localhost spring.rabbitmq.port = 5672 spring.rabbitmq.username = admin spring.rabbitmq.password = secret

有關RabbitProperties 更多支持的選項,請參閱

[小費]

檢查瞭解AMQP,RabbitMQ使用的協議以 獲取更多詳細信息。

32.2.2發送消息

Spring的AmqpTemplateAmqpAdmin配置自動,您能夠直接自動裝配它們變成你本身的豆:

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; } // ... }
[注意]

RabbitMessagingTemplate can be injected in a similar manner. If a MessageConverter bean is defined, it is associated automatically to the auto-configured AmqpTemplate.

Any org.springframework.amqp.core.Queue that is defined as a bean will be automatically used to declare a corresponding queue on the RabbitMQ instance if necessary.

您能夠在AmqpTemplate重試操做上啓用重試,例如在代理鏈接丟失的狀況下。默認狀況下禁用重試。

32.2.3接收消息

當Rabbit基礎結構存在時,能夠使用任何bean來註釋 @RabbitListener以建立偵聽器端點。若是RabbitListenerContainerFactory 未定義,SimpleRabbitListenerContainerFactory則會自動配置默認值,您能夠使用該spring.rabbitmq.listener.type屬性切換到直接容器 若是 定義了一個MessageConverterMessageRecovererbean,它們將自動關聯到默認工廠。

如下組件在someQueue隊列上建立偵聽器端點

@Component
公共  MyBean { @RabbitListener(queues =「someQueue」)  public void processMessage(String content){  // ... }  }
[小費]

查看Javadoc以@EnableRabbit 獲取更多詳細信息。

若是您須要建立更多的RabbitListenerContainerFactory實例或若是要覆蓋默認,春天啓動提供了一個 SimpleRabbitListenerContainerFactoryConfigurerDirectRabbitListenerContainerFactoryConfigurer你能夠用它來初始化 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 defaultRequeueRejected property to false and zero re-deliveries will be attempted; or, throw an AmqpRejectAndDontRequeueException to signal the message should be rejected. This is the mechanism used when retries are enabled and the maximum delivery attempts are reached.

32.3 Apache Kafka Support

Apache Kafka is supported by providing auto-configuration of the spring-kafka project.

Kafka configuration is controlled by external configuration properties in spring.kafka.*. For example, you might declare the following section inapplication.properties:

spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup

See KafkaProperties for more of the supported options.

32.3.1 Sending a Message

Spring’s KafkaTemplate is auto-configured and you can autowire them directly in your own beans:

@Component
public class MyBean { private final KafkaTemplate kafkaTemplate; @Autowired public MyBean(KafkaTemplate kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } // ... }

32.3.2 Receiving a Message

When the Apache Kafka infrastructure is present, any bean can be annotated with @KafkaListener to create a listener endpoint. If no KafkaListenerContainerFactory has been defined, a default one is configured automatically with keys defined in spring.kafka.listener.*.

The following component creates a listener endpoint on the someTopic topic:

@Component
public class MyBean { @KafkaListener(topics = "someTopic") public void processMessage(String content) { // ... } }

32.3.3 Additional Kafka Properties

The properties supported by auto configuration are shown in Appendix A, Common application properties. Note that these properties (hyphenated or camelCase) map directly to the Apache Kafka dotted properties for the most part, refer to the Apache Kafka documentation for details.

The first few of these properties apply to both producers and consumers, but can be specified at the producer or consumer level if you wish to use different values for each. Apache Kafka designates properties with an importance: HIGH, MEDIUM and LOW. Spring Boot auto configuration supports all HIGH importance properties, some selected MEDIUM and LOW, and any that do not have a default value.

只有Kafka支持的屬性的子集可經過KafkaProperties 該類得到。若是您但願使用不直接支持的其餘屬性配置生產者或使用者,請使用如下命令:

spring.kafka.properties.foo.bar = baz spring.kafka.consumer.properties.fiz.buz = qux spring,kafka.producer.properties.baz.qux = fiz

這將常見的foo.barKafka屬性設置爲baz(適用於生產者和使用者),將消費者fiz.buz屬性設置quxbaz.qux生產者屬性fiz

[重要] 重要

以這種方式設置的屬性將覆蓋Spring Boot明確支持的任何配置項。

33.使用'RestTemplate'調用REST服務

若是須要從應用程序調用遠程REST服務,能夠使用Spring Framework的RestTemplate類。因爲RestTemplate實例在使用以前一般須要自定義,所以Spring Boot不提供任何單個自動配置的 RestTemplatebean。可是,它會自動配置a RestTemplateBuilder,可RestTemplate在須要時用於建立實例。自動配置RestTemplateBuilder將確保將敏感HttpMessageConverters應用於RestTemplate實例。

這是一個典型的例子:

@Service
 public  class MyService { 私人 決賽 RestTemplate restTemplate; public MyBean(RestTemplateBuilder restTemplateBuilder){ this .restTemplate = restTemplateBuilder.build(); } 公衆詳細someRestCall(字符串名稱){ 返回  .restTemplate.getForObject(「/ {名} /詳細信息」,詳細信息。,名); }  }
[小費]

RestTemplateBuilder包括許多可用於快速配置a的有用方法RestTemplate例如,要添加BASIC auth支持,您能夠使用builder.basicAuthorization("user", "password").build()

33.1 RestTemplate定製

RestTemplate自定義有三種主要方法,具體取決於您但願自定義應用的普遍程度。

要使任何自定義的範圍儘量窄,請注入自動配置 RestTemplateBuilder,而後根據須要調用其方法。每一個方法調用都返回一個新RestTemplateBuilder實例,所以自定義只會影響構建器的使用。

爲了實現應用程序範圍的附加定製,RestTemplateCustomizer能夠使用bean。全部這些bean都自動註冊自動配置 RestTemplateBuilder,並將應用於使用它構建的任何模板。

這是一個定製器的示例,它爲全部主機配置代理的使用,除了 192.168.0.5

靜態  ProxyCustomizer 實現 RestTemplateCustomizer { @Override  public void customize(RestTemplate restTemplate){ HttpHost proxy = new HttpHost(「proxy.example.com」); HttpClient httpClient = HttpClientBuilder.create() .setRoutePlanner(new DefaultProxyRoutePlanner(proxy){ @覆蓋 公共 HttpHost determineProxy(HttpHost目標, HttpRequest請求,HttpContext上下文) 拋出 HttpException { if(target.getHostName()。equals(「192.168.0.5」)){ return null; } return super .determineProxy(target,request,context); }  })。創建(); restTemplate.setRequestFactory( 新的 HttpComponentsClientHttpRequestFactory(httpClient)); }  }

最後,最極端(也不多使用)的選項是建立本身的 RestTemplateBuilderbean。這將關閉a的自動配置, RestTemplateBuilder並將阻止使用任何RestTemplateCustomizerbean。

34.使用'WebClient'調用REST服務

若是你的類路徑上有Spring WebFlux,你也能夠選擇WebClient 用來調用遠程REST服務; 相比之下RestTemplate,這個客戶端具備更多的功能感,而且徹底被動。您能夠使用構建器建立本身的客戶端實例,該構建器WebClient.create()已經提供了良好的開箱即用體驗。請參閱WebClient上的 相關部分

Spring Boot將爲您建立和預配置這樣的構建器; 例如,客戶端HTTP編解碼器將像服務器同樣配置(請參閱WebFlux HTTP編解碼器自動配置)。

這是一個典型的例子:

@Service
 public  class MyService { 私有 最終 WebClient webClient; public MyBean(WebClient.Builder webClientBuilder){ this .webClient = webClientBuilder.baseUrl(「http://example.org」)。build(); } public Mono <Details> someRestCall(String name){ return this .webClient.get()。url(「/ {name} / details」,name) 。.retrieve()bodyToMono(詳情。); }  }

34.1 WebClient自定義

WebClient自定義有三種主要方法,具體取決於您但願自定義應用的普遍程度。

要使任何自定義的範圍儘量窄,請注入自動配置 WebClient.Builder,而後根據須要調用其方法。WebClient.Builder實例是有狀態的; 對構建器的任何更改都將反映在隨後使用它建立的全部客戶端中。若是您想使用相同的構建器建立多個客戶端,還能夠考慮使用克隆構建器WebClient.Builder other = builder.clone();

To make an application-wide, additive customization to all WebClient.Builder instances, you can declare WebClientCustomizer beans and change the WebClient.Builder as you would do locally at the point of injection.

Lastly, you can fall back to the original API and just use WebClient.create(). In that case, no auto-configuration nor WebClientCustomizer will be applied.

35. Validation

The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (e.g. Hibernate validator) is on the classpath. This allows bean methods to be annotated with javax.validation constraints on their parameters and/or on their return value. Target classes with such annotated methods need to be annotated with the @Validated annotation at the type level for their methods to be searched for inline constraint annotations.

For instance, the following service triggers the validation of the first argument, making sure its size is between 8 and 10

@Service
@Validated
public class MyBean { public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code, Author author) { ... } }

36. Sending email

The Spring Framework provides an easy abstraction for sending email using the JavaMailSender interface and Spring Boot provides auto-configuration for it as well as a starter module.

[小費]

Check the reference documentation for a detailed explanation of how you can use JavaMailSender.

若是spring.mail.host和相關庫(由定義的 spring-boot-starter-mail)可用,JavaMailSender則建立默認值(若是不存在)。發件人能夠經過spring.mail命名空間中的配置項進一步自定義,MailProperties有關詳細信息,請參閱 

特別是,某些默認超時值是無限的,您可能但願更改它以免線程被無響應的郵件服務器阻止:

spring.mail.properties.mail.smtp.connectiontimeout = 5000 spring.mail.properties.mail.smtp.timeout = 3000 spring.mail.properties.mail.smtp.writetimeout = 5000

37.使用JTA的分佈式事務

Spring Boot使用AtomikosBitronix 嵌入式事務管理器支持跨多個XA資源的分佈式JTA事務部署到合適的Java EE Application Server時,也支持JTA事務。

當檢測到JTA環境時,Spring JtaTransactionManager將用於管理事務。自動配置的JMS,DataSource和JPA bean將升級爲支持XA事務。您能夠使用標準的Spring慣用語@Transactional來參與分佈式事務。若是您在JTA環境中並仍想使用本地事務,則能夠將該spring.jta.enabled屬性設置false爲禁用JTA自動配置。

37.1使用Atomikos事務管理器

Atomikos是一個流行的開源事務管理器,能夠嵌入到Spring Boot應用程序中。您能夠使用spring-boot-starter-jta-atomikosStarter引入相應的Atomikos庫。Spring Boot將自動配置Atomikos,並確保depends-on對Spring bean應用適當的設置,以便正確啓動和關閉命令。

默認狀況下,Atomikos事務日誌將寫入transaction-logs應用程序主目錄(應用程序jar文件所在的目錄)中的目錄。您能夠經過spring.jta.log-dirapplication.properties文件中設置屬性來自定義此目錄屬性啓動spring.jta.atomikos.properties 也可用於自定義Atomikos UserTransactionServiceImp有關 完整的詳細信息,請參閱 AtomikosPropertiesJavadoc

[注意]

爲確保多個事務管理器能夠安全地協調相同的資源管理器,必須使用惟一ID配置每一個Atomikos實例。默認狀況下,此ID是運行Atomikos的計算機的IP地址。要確保生產中的惟一性,應spring.jta.transaction-manager-id 爲應用程序的每一個實例配置具備不一樣值屬性。

37.2使用Bitronix事務管理器

Bitronix是流行的開源JTA事務管理器實現。您能夠使用spring-boot-starter-jta-bitronixstarter將適當的Bitronix依賴項添加到項目中。與Atomikos同樣,Spring Boot將自動配置Bitronix並對bean進行後處理,以確保啓動和關閉順序正確。

默認狀況下,Bitronix事務日誌文件(part1.btmpart2.btm)將寫入transaction-logs應用程序主目錄中的目錄。您能夠使用該spring.jta.log-dir屬性自定義此目錄屬性啓動 spring.jta.bitronix.properties也綁定到bitronix.tm.Configurationbean,容許徹底自定義。有關 詳細信息,請參閱 Bitronix文檔

[注意]

爲確保多個事務管理器能夠安全地協調相同的資源管理器,必須爲每一個Bitronix實例配置惟一ID。默認狀況下,此ID是運行Bitronix的計算機的IP地址。要確保生產中的惟一性,應spring.jta.transaction-manager-id 爲應用程序的每一個實例配置具備不一樣值屬性。

37.3使用Narayana事務管理器

Narayana是JBoss支持的流行的開源JTA事務管理器實現。您能夠使用spring-boot-starter-jta-narayanastarter將相應的Narayana依賴項添加到項目中。與Atomikos和Bitronix同樣,Spring Boot將自動配置Narayana並對bean進行後處理,以確保啓動和關閉順序正確。

默認狀況下,Narayana事務日誌將寫入transaction-logs應用程序主目錄(應用程序jar文件所在的目錄)中的目錄。您能夠經過spring.jta.log-dirapplication.properties文件中設置屬性來自定義此目錄屬性啓動spring.jta.narayana.properties 也可用於自定義Narayana配置。有關 完整的詳細信息,請參閱 NarayanaPropertiesJavadoc

[注意]

爲確保多個事務管理器能夠安全地協調相同的資源管理器,必須使用惟一ID配置每一個Narayana實例。默認狀況下,此ID設置爲1要確保生產中的惟一性,應spring.jta.transaction-manager-id爲應用程序的每一個實例配置具備不一樣值的 屬性。

37.4使用Java EE託管事務管理器

若是您正在打包春季啓動應用程序做爲warear文件,並將其部署到Java EE應用服務器,您能夠使用內置的事務管理器應用程序服務器。春天開機時會試圖經過尋找共同的JNDI位置(自動配置一個事務管理器java:comp/UserTransaction, java:comp/TransactionManager等等)。若是您使用的是應用程序服務器提供的事務服務,一般還須要確保全部資源都由服務器管理並經過JNDI公開。Spring Boot將嘗試經過ConnectionFactory在JNDI路徑上查找來自動配置JMS,java:/JmsXA或者java:/XAConnectionFactory您能夠使用該 spring.datasource.jndi-name屬性 來配置您的DataSource

37.5混合XA和非XA JMS鏈接

使用JTA時,主JMS ConnectionFactorybean將支持XA並參與分佈式事務。在某些狀況下,您可能但願使用非XA處理某些JMS消息ConnectionFactory例如,您的JMS處理邏輯可能須要比XA超時更長的時間。

若是你想使用非XA,ConnectionFactory你能夠注入 nonXaJmsConnectionFactorybean而不是@Primary jmsConnectionFactorybean。爲了保持一致性,jmsConnectionFactory還使用bean別名提供bean xaJmsConnectionFactory

例如:

//注入主(XA感知)ConnectionFactory 
@Autowired
私有 ConnectionFactory defaultConnectionFactory; //注入XA感知ConnectionFactory(使用別名並注入與上面相同的內容) @Autowired  @Qualifier(「xaJmsConnectionFactory」)  private ConnectionFactory xaConnectionFactory; //注入非XA感知的ConnectionFactory @Autowired  @Qualifier(「nonXaJmsConnectionFactory」) 私有 ConnectionFactory nonXaConnectionFactory;

37.6支持替代嵌入式事務管理器

XAConnectionFactoryWrapper 和XADataSourceWrapper接口可用於支持替代嵌入式事務經理。接口負責包裝XAConnectionFactoryXADataSourcebean,並將它們做爲常規ConnectionFactoryDataSourcebean 公開,它們將透明地註冊到分佈式事務中。只要您有一個JtaTransactionManagerbean和在您的域中註冊的相應XA包裝bean,DataSource和JMS自動配置將使用JTA變體ApplicationContext

BitronixXAConnectionFactoryWrapper 和BitronixXADataSourceWrapper 提供瞭如何編寫XA包裝很好的例子。

38. Hazelcast

若是Hazelcast位於類路徑上並找到合適的配置,Spring Boot將自動配置HazelcastInstance您能夠在應用程序中注入的配置

You can define a com.hazelcast.config.Config bean and we’ll use that. If your configuration defines an instance name, we’ll try to locate an existing instance rather than creating a new one.

You could also specify the hazelcast.xml configuration file to use via configuration:

spring.hazelcast.config=classpath:config/my-hazelcast.xml

Otherwise, Spring Boot tries to find the Hazelcast configuration from the default locations, that is hazelcast.xml in the working directory or at the root of the classpath. We also check if the hazelcast.config system property is set. Check the Hazelcast documentation for more details.

If hazelcast-client is present on the classpath, Spring Boot will first attempt to create a client with similar rules as above, that is:

  • The presence of a com.hazelcast.client.config.ClientConfig bean
  • A configuration file defined by the spring.hazelcast.config property
  • The presence of the hazelcast.client.config system property
  • hazelcast-client.xml in the working directory or at the root of the classpath
[注意]

Spring Boot also has an explicit caching support for Hazelcast. The HazelcastInstance is automatically wrapped in a CacheManager implementation if caching is enabled.

39. Quartz Scheduler

Spring Boot offers several conveniences for working with the Quartz scheduler, including the spring-boot-starter-quartz ‘Starter’. If Quartz is available, a Scheduler will be auto-configured (via the SchedulerFactoryBean abstraction).

Beans of the following types will be automatically picked up and associated with the the Scheduler:

  • JobDetail: defines a particular Job. JobDetail instance can easily be built with the JobBuilder API
  • Calendar
  • Trigger:定義什麼時候觸發特定做業

默認狀況下,JobStore將使用內存可是,若是DataSource應用程序中bean,而且相應地spring.quartz.job-store-type配置了 屬性,則能夠配置基於JDBC的存儲

spring.quartz.job-store-type = jdbc

使用jdbc存儲時,能夠在啓動時初始化架構:

spring.quartz.jdbc.initialize-schema = true
[注意]

默認狀況下會檢測數據庫,並使用Quartz庫提供的標準腳本進行初始化。也能夠使用該spring.quartz.jdbc.schema屬性提供自定義腳本 

能夠使用Quartz配置屬性(請參閱參考資料spring.quartz.properties.*)和SchedulerFactoryBeanCustomizer容許編程SchedulerFactoryBean自定義的bean來自定義Quartz Scheduler配置 

Job能夠定義setter以注入數據映射屬性。也能夠以相似的方式注入常規豆類:

公共  SampleJob 擴展了 QuartzJobBean { private MyService myService; 私有字符串名稱; //注入「MyService」bean public void setMyService(MyService myService){...} //注入「name」做業數據屬性 public void setName(String name){...} @Override  protected void executeInternal(JobExecutionContext context) 拋出 JobExecutionException { ... }  }

40.春季整合

Spring Boot提供了一些使用Spring Integration的便利,包括spring-boot-starter-integration'Starter'。Spring Integration提供了消息傳遞以及其餘傳輸(如HTTP,TCP等)的抽象。若是類路徑上有Spring Integration,它將經過@EnableIntegration註釋進行初始化 

Spring Boot還將配置因爲存在其餘Spring Integration模塊而觸發的一些功能。若是'spring-integration-jmx'也在類路徑上,則將經過JMX發佈消息處理統計信息若是 'spring-integration-jdbc'可用,則能夠在啓動時建立默認數據庫模式:

spring.integration.jdbc.initializer.enabled = true

有關 詳細信息,請參閱 IntegrationAutoConfiguration 和IntegrationProperties類。

41.春季會議

Spring Boot provides Spring Session auto-configuration for a wide range of stores:

  • JDBC
  • Redis
  • Hazelcast
  • HashMap

If Spring Session is available, you must choose the StoreType that you wish to use to store the sessions. For instance to use JDBC as backend store, you’d configure your application as follows:

spring.session.store-type=jdbc
[小費]

You can disable Spring Session by setting the store-type to none.

Each store has specific additional settings. For instance it is possible to customize the name of the table for the jdbc store:

spring.session.jdbc.table-name=SESSIONS

42. Monitoring and management over JMX

Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default Spring Boot will create an MBeanServer with bean id ‘mbeanServer’ and expose any of your beans that are annotated with Spring JMX annotations (@ManagedResource@ManagedAttribute@ManagedOperation).

See the JmxAutoConfiguration class for more details.

43. Testing

Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules; spring-boot-test contains core items, and spring-boot-test-autoconfigure supports auto-configuration for tests.

Most developers will just use the spring-boot-starter-test ‘Starter’ which imports both Spring Boot test modules as well has JUnit, AssertJ, Hamcrest and a number of other useful libraries.

43.1 Test scope dependencies

If you use the spring-boot-starter-test ‘Starter’ (in the test scope), you will find the following provided libraries:

  • JUnit — The de-facto standard for unit testing Java applications.
  • Spring Test & Spring Boot Test — Utilities and integration test support for Spring Boot applications.
  • AssertJ — A fluent assertion library.
  • Hamcrest — A library of matcher objects (also known as constraints or predicates).
  • Mockito — A Java mocking framework.
  • JSONassert — An assertion library for JSON.
  • JsonPath — XPath for JSON.

These are common libraries that we generally find useful when writing tests. You are free to add additional test dependencies of your own if these don’t suit your needs.

43.2 Testing Spring applications

One of the major advantages of dependency injection is that it should make your code easier to unit test. You can simply instantiate objects using the new operator without even involving Spring. You can also use mock objects instead of real dependencies.

Often you need to move beyond ‘unit testing’ and start ‘integration testing’ (with a Spring ApplicationContext actually involved in the process). It’s useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure.

The Spring Framework includes a dedicated test module for just such integration testing. You can declare a dependency directly to org.springframework:spring-test or use the spring-boot-starter-test ‘Starter’ to pull it in transitively.

If you have not used the spring-test module before you should start by reading the relevant section of the Spring Framework reference documentation.

43.3 Testing Spring Boot applications

A Spring Boot application is just a Spring ApplicationContext, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. One thing to watch out for though is that the external properties, logging and other features of Spring Boot are only installed in the context by default if you use SpringApplication to create it.

Spring Boot provides a @SpringBootTest annotation which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests via SpringApplication.

You can use the webEnvironment attribute of @SpringBootTest to further refine how your tests will run:

  • MOCK — Loads 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環境(模擬或其餘)。
[注意]

若是您的測試是@Transactional,它將默認在每一個測試方法結束時回滾事務。若是您使用的是組合這種安排既用 RANDOM_PORTDEFINED_PORT在服務器上發起的任何交易不會由於測試是在不一樣的線程比服務器處理運行回滾。

[注意]

除了@SpringBootTest提供許多其餘註釋以外,還提供了用於測試應用程序的更具體的切片。請參閱下文了解詳情。

[小費]

不要忘記也添加@RunWith(SpringRunner.class)到您的測試中,不然註釋將被忽略。

43.3.1檢測測試配置

若是您熟悉Spring Test Framework,那麼您可能習慣使用 @ContextConfiguration(classes=…​)它來指定@Configuration 要加載的Spring 或者,您可能常常@Configuration在測試中使用嵌套類。

在測試Spring Boot應用程序時,一般不須要這樣作。@*Test只要您沒有明肯定義,Spring Boot的註釋就會自動搜索您的主要配置。

搜索算法從包含測試的包開始工做,直到找到一個 @SpringBootApplication或帶@SpringBootConfiguration註釋的類。只要您 以合理的方式構建代碼,一般就會找到主要配置。

若是要自定義主要配置,能夠使用嵌套 @TestConfiguration類。@Configuration將用於代替應用程序主要配置的嵌套@TestConfiguration類不一樣,除了應用程序的主要配置以外,還將使用嵌套類。

[注意]

Spring的測試框架將在測試之間緩存應用程序上下文。所以,只要您的測試共享相同的配置(不管它如何被發現),加載上下文的潛在耗時過程將只發生一次。

43.3.2排除測試配置

若是您的應用程序使用組件掃描,例如,若是您使用 @SpringBootApplication@ComponentScan,您可能會發現僅爲特定測試建立的頂級配置類偶然會在任何地方被拾取。

正如咱們在前面看到的, @TestConfiguration能夠在一個內部類的測試的用於定製的主配置。放置在頂級類時,@TestConfiguration表示src/test/java不該經過掃描拾取而後,您能夠在須要的位置顯式導入該類:

@RunWith(SpringRunner.class)
@SpringBootTest @Import 
(MyTestsConfiguration.class)
 public  class MyTests { @Test  public void exampleTest(){ ... }  }
[注意]

若是您直接使用@ComponentScan(即不經過@SpringBootApplication),則須要註冊TypeExcludeFilter有關詳細信息,請參閱 Javadoc

43.3.3使用隨機端口

If you need to start a full running server for tests, we recommend that you use random ports. If you use @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) an available port will be picked at random each time your test runs.

The @LocalServerPort annotation can be used to inject the actual port used into your test. For convenience, tests that need to make REST calls to the started server can additionally @Autowire a TestRestTemplate which will resolve relative links to the running server.

import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class RandomPortExampleTests { @Autowired private TestRestTemplate restTemplate; @Test public void exampleTest() { String body = this.restTemplate.getForObject("/", String.class); assertThat(body).isEqualTo("Hello World"); } }

43.3.4 Mocking and spying beans

It’s sometimes necessary to mock certain components within your application context when running tests. For example, you may have a facade over some remote service that’s unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment.

Spring Boot includes a @MockBean annotation that can be used to define a Mockito mock for a bean inside your ApplicationContext. You can use the annotation to add new beans, or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on @Configurationclasses 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. @SpringBootTest). To use this feature with a different arrangement, a listener will need to be added explicitly:

@TestExecutionListeners(MockitoTestExecutionListener.class)

Here’s a typical example where we replace an existing RemoteService bean with a mock implementation:

import org.junit.*;
import org.junit.runner.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.context.*; import org.springframework.boot.test.mock.mockito.*; import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; @RunWith(SpringRunner.class) @SpringBootTest public class MyTests { @MockBean private RemoteService remoteService; @Autowired private Reverser reverser; @Test public void exampleTest() { // RemoteService has been injected into the reverser bean given(this.remoteService.someCall()).willReturn("mock"); String reverse = reverser.reverseSomeCall(); assertThat(reverse).isEqualTo("kcom"); } }

Additionally you can also use @SpyBean to wrap any existing bean with a Mockito spy. See the Javadoc for full details.

43.3.5 Auto-configured tests

Spring Boot’s auto-configuration system works well for applications, but can sometimes be a little too much for tests. It’s often helpful to load only the parts of the configuration that are required to test a ‘slice’ of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you don’t want to involve database calls in those tests; or you might be wanting to test JPA entities, and you’re not interested in web layer when those tests run.

The spring-boot-test-autoconfigure module includes a number of annotations that can be used to automatically configure such ‘slices’. Each of them works in a similar way, providing a @…​Test annotation that loads the ApplicationContext and one or more @AutoConfigure…​ annotations that can be used to customize auto-configuration settings.

[注意]

Each slice loads a very restricted set of auto-configuration classes. If you need to exclude one of them, most @…​Test annotations provide an excludeAutoConfiguration attribute. Alternatively, you can use @ImportAutoConfiguration#exclude.

[小費]

It’s also possible to use the @AutoConfigure…​ annotations with the standard @SpringBootTest annotation. You can use this combination if you’re not interested in ‘slicing’ your application but you want some of the auto-configured test beans.

43.3.6 Auto-configured JSON tests

To test that Object JSON serialization and deserialization is working as expected you can use the @JsonTest annotation. @JsonTest will auto-configure Jackson ObjectMapper, any @JsonComponent beans and any Jackson Modules. It also configures Gson if you happen to be using that instead of, or as well as, Jackson. If you need to configure elements of the auto-configuration you can use the @AutoConfigureJsonTesters annotation.

Spring Boot includes AssertJ based helpers that work with the JSONassert and JsonPath libraries to check that JSON is as expected. The JacksonTesterGsonTester 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幫助程序類也能夠直接在標準單元測試中使用。若是您不使用,只需在initFields方法中調用助手的@Before方法便可 @JsonTest

@JsonTest能夠 在附錄中找到啓用的自動配置列表

43.3.7自動配置的Spring MVC測試

要測試Spring MVC控制器是否正常工做,您能夠使用@WebMvcTest 註釋。@WebMvcTest將自動配置Spring MVC的基礎設施和限制掃描豆@Controller@ControllerAdvice@JsonComponentFilter, WebMvcConfigurerHandlerMethodArgumentResolver@Component使用此批註時,不會掃描常規bean。

一般@WebMvcTest將限於單個控制器並與其結合使用 @MockBean,以便爲所需的協做者提供模擬實現。

@WebMvcTest還自動配置MockMvcMock MVC提供了一種快速測試MVC控制器的強大方法,無需啓動完整的HTTP服務器。

[小費]

您也能夠經過使用註釋來MockMvc自動配置@WebMvcTest(例如SpringBootTest@AutoConfigureMockMvc

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過濾器時),則能夠使用@AutoConfigureMockMvc 註釋中的屬性

若是您使用HtmlUnit或Selenium,自動配置還將提供HTMLUnit WebClientbean和/或WebDriverbean。這是一個使用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會將WebDriverbean放在一個特殊的「範圍」中,以確保在每次測試後退出驅動程序,並注入新實例。若是您不想要此行爲,則能夠添加@Scope("singleton")到您的WebDriver @Bean 定義中。

@WebMvcTest能夠 在附錄中找到啓用的自動配置列表

43.3.8自動配置Spring WebFlux測試

要測試Spring WebFlux控制器是否正常工做,您能夠使用@WebFluxTest 註釋。@WebFluxTest將自動配置Spring WebFlux基礎設施和限制掃描豆@Controller@ControllerAdvice@JsonComponent,和 WebFluxConfigurer@Component使用此批註時,不會掃描常規bean。

一般@WebFluxTest將限於單個控制器並與其結合使用 @MockBean,以便爲所需的協做者提供模擬實現。

@WebFluxTest還有自動配置WebTestClient,這提供了一種快速測試WebFlux控制器的強大方法,無需啓動完整的HTTP服務器。

[小費]

您也能夠經過使用註釋來WebTestClient自動配置@WebFluxTest (例如SpringBootTest@AutoConfigureWebTestClient

import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @WebFluxTest(UserVehicleController.class)  public class MyControllerTests { @Autowired 私有 WebTestClient webClient; @MockBean  private UserVehicleService userVehicleService; @Test  public void testExample()拋出異常{ 給定( .userVehicleService.getVehicleDetails(「sboot」)) .willReturn(new VehicleDetails(「Honda」「Civic」)); 這個 .webClient.get()。uri(「/ sboot / vehicle」)。accept(MediaType.TEXT_PLAIN) 。交換() .expectStatus()。ISOK() .expectBody(String .class).isEqualTo(「Honda Civic」); }  }

A list of the auto-configuration that is enabled by @WebFluxTest can be found in the appendix.

43.3.9 Auto-configured Data JPA tests

@DataJpaTest can be used if you want to test JPA applications. By default it will configure an in-memory embedded database, scan for @Entity classes and configure Spring Data JPA repositories. Regular @Component beans will not be loaded into the ApplicationContext.

Data JPA tests are transactional and rollback at the end of each test by default, see the relevant section in the Spring Reference Documentation for more details. If that’s not what you want, you can disable transaction management for a test or for the whole class as follows:

import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @DataJpaTest @Transactional(propagation = Propagation.NOT_SUPPORTED) public class ExampleNonTransactionalTests { }

數據JPA測試也能夠注入一個 TestEntityManager bean,它提供了EntityManager專門爲測試設計的標準JPA的替代方法若是你想在TestEntityManager外面使用@DataJpaTests你也能夠使用@AutoConfigureTestEntityManager註釋。JdbcTemplate若是您須要,也能夠使用A.

import org.junit。*; import org.junit.runner。*; import org.springframework.boot.test.autoconfigure.orm.jpa。*; import static org.assertj.core.api.Assertions。*; @RunWith(SpringRunner.class) @DataJpaTest  public class ExampleRepositoryTests { @Autowired 私有 TestEntityManager entityManager; @Autowired 私有 UserRepository存儲庫; @Test  public void testExample()拋出 Exception {  this .entityManager.persist( new User( 「sboot」 「1234」)); User user = this .repository.findByUsername(「sboot」); assertThat(user.getUsername())。isEqualTo(「sboot」); assertThat(user.getVin())。isEqualTo(「1234」); }  }

內存中的嵌入式數據庫一般能夠很好地用於測試,由於它們很快而且不須要任何開發人員安裝。可是,若是您更喜歡對真實數據庫運行測試,則能夠使用@AutoConfigureTestDatabase註釋:

@RunWith(SpringRunner.class)
@DataJpaTest 
@AutoConfigureTestDatabase(replace = Replace.NONE)
 public  class ExampleRepositoryTests { // ...  }

@DataJpaTest能夠 在附錄中找到啓用的自動配置列表

43.3.10自動配置的JDBC測試

@JdbcTest相似於@DataJpaTest純jdbc相關測試。默認狀況下,它還將配置內存中的嵌入式數據庫和JdbcTemplate常規 @Componentbean不會被加載到ApplicationContext

默認狀況下,JDBC測試在每一個測試結束時都是事務性和回滾,有關詳細信息,請參閱Spring Reference Documentation中相關部分若是這不是您想要的,您能夠爲測試或整個類禁用事務管理,以下所示:

import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @JdbcTest  @Transactional(propagation = Propagation.NOT_SUPPORTED)  public class ExampleNonTransactionalTests {  }

若是您但願測試針對真實數據庫運行,則能夠使用與@AutoConfigureTestDatabase註釋相同的方式使用 註釋DataJpaTest

@JdbcTest能夠 在附錄中找到啓用的自動配置列表

43.3.11自動配置的jOOQ測試

@JooqTest能夠以與@JdbcTestjOOQ相關的測試相似的方式使用因爲jOOQ嚴重依賴於與數據庫模式相對應的基於Java的模式,所以DataSource將使用現有模式若是要經過內存數據庫替換它,能夠使用@AutoconfigureTestDatabase覆蓋這些設置。

@JooqTest將配置一個DSLContext常規@Componentbean不會加載到ApplicationContext

import org.jooq.DSLContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.jooq.JooqTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @JooqTest  public class ExampleJooqTests { @Autowired  private DSLContext dslContext; }

默認狀況下,JOOQ測試在每一個測試結束時都是事務性和回滾。若是這不是您想要的,您能夠禁用測試或整個測試類的事務管理,如上例所示

@JooqTest能夠 在附錄中找到啓用的自動配置列表

43.3.12自動配置的數據MongoDB測試

@DataMongoTest若是要測試MongoDB應用程序,能夠使用它。默認狀況下,它將配置內存中嵌入式MongoDB(若是可用),配置MongoTemplate,掃描@Document類並配置Spring Data MongoDB存儲庫。常規 @Componentbean不會加載到ApplicationContext

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataMongoTest public class ExampleDataMongoTests { @Autowired private MongoTemplate mongoTemplate; // }

In-memory embedded MongoDB generally works well for tests since it is fast and doesn’t require any developer installation. If, however, you prefer to run tests against a real MongoDB server you should exclude the embedded MongoDB auto-configuration:

import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class) public class ExampleDataMongoNonEmbeddedTests { }

A list of the auto-configuration that is enabled by @DataMongoTest can be found in the appendix.

43.3.13 Auto-configured Data Neo4j tests

@DataNeo4jTest can be used if you want to test Neo4j applications. By default, it will use an in-memory embedded Neo4j (if the embedded driver is available), scan for@NodeEntity classes and configure Spring Data Neo4j repositories. Regular @Component beans will not be loaded into the ApplicationContext:

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataNeo4jTest public class ExampleDataNeo4jTests { @Autowired private YourRepository repository; // }

Data Neo4j tests are transactional and rollback at the end of each test by default, see the relevant section in the Spring Reference Documentation for more details. If that’s not what you want, you can disable transaction management for a test or for the whole class as follows:

import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringRunner.class) @DataNeo4jTest @Transactional(propagation = Propagation.NOT_SUPPORTED) public class ExampleNonTransactionalTests { }

A list of the auto-configuration that is enabled by @DataNeo4jTest can be found in the appendix.

43.3.14 Auto-configured Data Redis tests

@DataRedisTest can be used if you want to test Redis applications. By default, it will scan for @RedisHash classes and configure Spring Data Redis repositories. Regular @Component beans will not be loaded into the ApplicationContext:

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataRedisTest public class ExampleDataRedisTests { @Autowired private YourRepository repository; // }

@DataRedisTest能夠 在附錄中找到啓用的自動配置列表

43.3.15自動配置的數據LDAP測試

@DataLdapTest若是要測試LDAP應用程序,能夠使用它。默認狀況下,它將配置內存中嵌入式LDAP(若是可用),a LdapTemplate,掃描@Entry 類並配置Spring Data LDAP存儲庫。常規@Componentbean不會加載到ApplicationContext

import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; import org.springframework.ldap.core.LdapTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataLdapTest  public class ExampleDataLdapTests { @Autowired  private LdapTemplate ldapTemplate; // }

內存中嵌入式LDAP一般適用於測試,由於它速度快,不須要任何開發人員安裝。可是,若是您但願針對真實LDAP服務器運行測試,則應排除嵌入式LDAP自動配置:

import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration; import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataLdapTest(excludeAutoConfiguration = EmbeddedLdapAutoConfiguration.class)  public class ExampleDataLdapNonEmbeddedTests {  }

@DataLdapTest能夠 在附錄中找到啓用的自動配置列表

43.3.16自動配置的REST客戶端

@RestClientTest,若是你想測試REST客戶註釋能夠使用。默認狀況下,它將自動配置Jackson和GSON支持,配置RestTemplateBuilder並添加支持MockRestServiceServer應使用valuecomponents屬性指定要測試的特定bean @RestClientTest

@RunWith(SpringRunner.class)
@RestClientTest(RemoteVehicleDetailsS​​ervice.class)
 public  class ExampleRestClientTest { @Autowired 私有 RemoteVehicleDetailsS​​ervice服務; @Autowired 私有 MockRestServiceServer服務器; @Test  public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() 拋出異常{  this .server.expect(requestTo( 「/ greet / details」)) .andRespond(withSuccess(「hello」,MediaType.TEXT_PLAIN)); String greeting = this .service.callRestService(); 斷言(問候).isEqualTo(「你好」); }  }

A list of the auto-configuration that is enabled by @RestClientTest can be found in the appendix.

43.3.17 Auto-configured Spring REST Docs tests

The @AutoConfigureRestDocs annotation can be used if you want to use Spring REST Docs in your tests. It will automatically configure MockMvc to use Spring REST Docs and remove the need for Spring REST Docs' JUnit rule.

import org.junit.Test;
import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(UserController.class) @AutoConfigureRestDocs public class UserDocumentationTests { @Autowired private MockMvc mvc; @Test public void listUsers() throws Exception { this.mvc.perform(get("/users").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()) .andDo(document("list-users")); } }

@AutoConfigureRestDocs can be used to override the default output directory (target/generated-snippets if you are using Maven or build/generated-snippets if you are using Gradle). It can also be used to configure the host, scheme, and port that will appear in any documented URIs. If you require more control over Spring REST Docs' configuration a RestDocsMockMvcConfigurationCustomizer bean can be used:

@TestConfiguration
static class CustomizationConfiguration implements RestDocsMockMvcConfigurationCustomizer { @Override public void customize(MockMvcRestDocumentationConfigurer configurer) { configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); } }

If you want to make use of Spring REST Docs' support for a parameterized output directory, you can create a RestDocumentationResultHandler bean. The auto-configuration will call alwaysDo with this result handler, thereby causing each MockMvc call to automatically generate the default snippets:

@TestConfiguration
static class ResultHandlerConfiguration { @Bean public RestDocumentationResultHandler restDocumentation() { return MockMvcRestDocumentation.document("{method-name}"); } }

43.3.18 Using Spock to test Spring Boot applications

If you wish to use Spock to test a Spring Boot application you should add a dependency on Spock’s spock-spring module to your application’s build. spock-springintegrates Spring’s test framework into Spock. It is recommended that you use Spock 1.1 or later to benefit from a number of recent improvements to Spock’s Spring Framework and Spring Boot integration. Please refer to the documentation for Spock’s Spring module for further details.

43.4 Test utilities

A few test utility classes are packaged as part of spring-boot that are generally useful when testing your application.

43.4.1 ConfigFileApplicationContextInitializer

ConfigFileApplicationContextInitializer is an ApplicationContextInitializer that can apply to your tests to load Spring Boot application.propertiesfiles. You can use this when you don’t need the full features provided by @SpringBootTest.

@ContextConfiguration(classes = Config.class,
    initializers = ConfigFileApplicationContextInitializer.class)
[注意]

Using ConfigFileApplicationContextInitializer alone won’t provide support for @Value("${…​}") injection. Its only job is to ensure that application.properties files are loaded into Spring’s Environment. For @Value support you need to either additionally configure a PropertySourcesPlaceholderConfigurer or use @SpringBootTest where one will be auto-configured for you.

43.4.2 EnvironmentTestUtils

EnvironmentTestUtils allows you to quickly add properties to a ConfigurableEnvironment or ConfigurableApplicationContext. Simply call it withkey=value strings:

EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot");

43.4.3 OutputCapture

OutputCapture is a JUnit Rule that you can use to capture System.out and System.err output. Simply declare the capture as a @Rule then use toString() for assertions:

import org.junit.Rule;
import org.junit.Test; import org.springframework.boot.test.rule.OutputCapture; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class MyTest { @Rule public OutputCapture capture = new OutputCapture(); @Test public void testName() throws Exception { System.out.println("Hello World!"); assertThat(capture.toString(), containsString("World")); } }

43.4.4 TestRestTemplate

TestRestTemplate is a convenience alternative to Spring’s RestTemplate that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case the template will behave in a test-friendly way by not throwing exceptions on server-side errors. It is recommended, but not mandatory, to use Apache HTTP Client (version 4.3.2 or better), and if you have that on your classpath the TestRestTemplate will respond by configuring the client appropriately. If you do use Apache’s HTTP client some additional test-friendly features will be enabled:

  • Redirects will not be followed (so you can assert the response location)
  • Cookies will be ignored (so the template is stateless)

TestRestTemplate can be instantiated directly in your integration tests:

public class MyTest { private TestRestTemplate template = new TestRestTemplate(); @Test public void testRequest() throws Exception { HttpHeaders headers = template.getForEntity("http://myhost.com/example", String.class).getHeaders(); assertThat(headers.getLocation().toString(), containsString("myotherhost")); } }

Alternatively, if you are using the @SpringBootTest annotation with WebEnvironment.RANDOM_PORT or WebEnvironment.DEFINED_PORT, you can just inject a fully configured TestRestTemplate and start using it. If necessary, additional customizations can be applied via the RestTemplateBuilder bean. Any URLs that do not specify a host and port will automatically connect to the embedded server:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest { @Autowired private TestRestTemplate template; @Test public void testRequest() throws Exception { HttpHeaders headers = template.getForEntity("/example", String.class).getHeaders(); assertThat(headers.getLocation().toString(), containsString("myotherhost")); } @TestConfiguration static class Config { @Bean public RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder() .additionalMessageConverters(...) .customizers(...); } } }

44. WebSockets

Spring Boot provides WebSockets auto-configuration for embedded Tomcat (8 and 7), Jetty 9 and Undertow. If you’re deploying a war file to a standalone container, Spring Boot assumes that the container will be responsible for the configuration of its WebSocket support.

Spring Framework provides rich WebSocket support that can be easily accessed via the spring-boot-starter-websocket module.

45. Web Services

Spring Boot provides Web Services auto-configuration so that all is required is defining your Endpoints.

The Spring Web Services features can be easily accessed via the spring-boot-starter-webservices module.

46. Creating your own auto-configuration

If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot.

自動配置能夠與「啓動器」相關聯,該「啓動器」提供自動配置代碼以及您將使用它的典型庫。咱們將首先介紹構建本身的自動配置所需的知識,而後咱們將繼續介紹建立自定義啓動器所需的 典型步驟

[小費]

能夠使用演示項目 來展現如何逐步建立啓動器。

46.1瞭解自動配置的bean

在引擎蓋下,自動配置使用標準@Configuration實現其餘@Conditional註釋用於約束什麼時候應用自動配置。一般自動配置類使用@ConditionalOnClass@ConditionalOnMissingBean註釋。這可確保自動配置僅在找到相關類時以及未聲明本身的類時應用@Configuration

您能夠瀏覽源代碼spring-boot-autoconfigure 以查看@Configuration咱們提供類(請參閱 META-INF/spring.factories 文件)。

46.2查找自動配置候選項

Spring Boot會檢查META-INF/spring.factories已發佈jar中是否存在文件。該文件應列出EnableAutoConfiguration密鑰下的配置類 

org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\
com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration

若是須要按特定順序應用配置,則能夠使用 @AutoConfigureAfter或 @AutoConfigureBefore註釋。例如,若是您提供特定於Web的配置,則可能須要在以後應用您的類 WebMvcAutoConfiguration

若是您想訂購某些不該該彼此直接瞭解的自動配置,您也能夠使用@AutoconfigureOrder該註釋與常規註釋具備相同的語義,@Order但爲自動配置類提供了專用順序。

[注意]

自動配置,必須加載的方式確保它們在特定的包空間中定義,而且它們永遠不是組件掃描的目標。

46.3條件註釋

您幾乎老是但願@Conditional在自動配置類中包含一個或多個註釋。@ConditionalOnMissingBean是一個常見的示例,用於容許開發人員「覆蓋」自動配置,若是他們對您的默認值不滿意。

Spring Boot包含許多@Conditional註釋,您能夠經過註釋@Configuration類或單個@Bean方法在本身的代碼中重用這些註釋

46.3.1類別條件

The @ConditionalOnClass and @ConditionalOnMissingClass annotations allows configuration to be included based on the presence or absence of specific classes. Due to the fact that annotation metadata is parsed using ASM you can actually use the value attribute to refer to the real class, even though that class might not actually appear on the running application classpath. You can also use the name attribute if you prefer to specify the class name using a String value.

[小費]

If you are using @ConditionalOnClass or @ConditionalOnMissingClass as a part of a meta-annotation to compose your own composed annotations you must use name as referring to the class in such a case is not handled.

46.3.2 Bean conditions

The @ConditionalOnBean and @ConditionalOnMissingBean annotations allow a bean to be included based on the presence or absence of specific beans. You can use the value attribute to specify beans by type, or name to specify beans by name. The search attribute allows you to limit the ApplicationContext hierarchy that should be considered when searching for beans.

When placed on a @Bean method, the target type defaults to the return type of the method, for instance:

@Configuration
public class MyAutoConfiguration { @Bean @ConditionalOnMissingBean public MyService myService() { ... } }

In the example above, the myService bean is going to be created if no bean of type MyService is already contained in the ApplicationContext.

[小費]

You need to be very careful about the order that bean definitions are added as these conditions are evaluated based on what has been processed so far. For this reason, we recommend only using @ConditionalOnBean and @ConditionalOnMissingBean annotations on auto-configuration classes (since these are guaranteed to load after any user-defined beans definitions have been added).

[注意]

@ConditionalOnBean and @ConditionalOnMissingBean do not prevent @Configuration classes from being created. Using these conditions at the class level is equivalent to marking each contained @Bean method with the annotation.

46.3.3 Property conditions

The @ConditionalOnProperty annotation allows configuration to be included based on a Spring Environment property. Use the prefix and name attributes to specify the property that should be checked. By default any property that exists and is not equal to false will be matched. You can also create more advanced checks using the havingValue and matchIfMissing attributes.

46.3.4 Resource conditions

The @ConditionalOnResource annotation allows configuration to be included only when a specific resource is present. Resources can be specified using the usual Spring conventions, for example, file:/home/user/test.dat.

46.3.5 Web application conditions

The @ConditionalOnWebApplication and @ConditionalOnNotWebApplication annotations allow configuration to be included depending on whether the application is a 'web application'. A web application is any application that is using a Spring WebApplicationContext, defines a session scope or has a StandardServletEnvironment.

46.3.6 SpEL expression conditions

The @ConditionalOnExpression annotation allows configuration to be included based on the result of a SpEL expression.

46.4 Creating your own starter

A full Spring Boot starter for a library may contain the following components:

  • The autoconfigure module that contains the auto-configuration code.
  • starter模塊提供對autoconfigure模塊以及庫的依賴關係以及一般有用的任何其餘依賴項。簡而言之,添加啓動器應該足以開始使用該庫。
[小費]

若是您不須要將這兩個問題分開,則能夠將自動配置代碼和依賴關係管理組合在一個模塊中。

46.4.1命名

請確保爲您的啓動器提供適當的命名空間。spring-boot即便您使用的是其餘Maven groupId,也不要使用它來啓動模塊名稱咱們可能會爲您未來自動配置的內容提供官方支持。

這是一條經驗法則。假設您正在爲「acme」建立啓動器,將自動配置模塊acme-spring-boot-autoconfigure和啓動器 命名爲acme-spring-boot-starter若是您只有一個模塊將二者合併,請使用 acme-spring-boot-starter

此外,若是您的啓動器提供配置密鑰,請爲它們使用適當的命名空間。特別是,不包括你在春天開機使用的命名空間(如按鍵 servermanagementspring,等)。這些是「咱們的」,咱們可能會在將來改進/修改它們,這樣可能會破壞你的東西。

確保 觸發元數據生成,以便爲您的密鑰提供IDE幫助。您可能但願查看生成的元數據(META-INF/spring-configuration-metadata.json)以確保正確記錄您的密鑰。

46.4.2自動配置模塊

autoconfigure模塊包含開始使用庫所需的全部內容。它還能夠包含配置鍵定義(@ConfigurationProperties)和任何可用於進一步自定義組件初始化方式的回調接口。

[小費]

您應該將庫的依賴項標記爲可選,以便您能夠更輕鬆地在項目中包含autoconfigure模塊。若是你這樣作,將不提供庫,默認狀況下Spring Boot將退回。

46.4.3啓動器模塊

真的,起動器是一個空罐子。它的惟一目的是爲庫提供必要的依賴關係; 將其視爲開始所須要的觀點。

不要對添加啓動器的項目作出假設。若是您自動配置的庫一般須要其餘啓動器,請同時說起它們。若是可選依賴項的數量很高,則提供一組適當的默認依賴項可能很難,由於您應該避免爲庫的典型用法帶來沒必要要的依賴項。

47.接下來要讀什麼

若是您想了解本節中討論的任何類的更多信息,能夠查看Spring Boot API文檔,也能夠直接瀏覽 源代碼若是您有具體問題,請查看 操做方法部分。

If you are comfortable with Spring Boot’s core features, you can carry on and read about production-ready features.

Part V. Spring Boot Actuator: Production-ready features

 

Spring Boot includes a number of additional features to help you monitor and manage your application when it’s pushed to production. You can choose to manage and monitor your application using HTTP endpoints or with JMX. Auditing, health and metrics gathering can be automatically applied to your application.

Actuator HTTP endpoints are only available with a Spring MVC-based application. In particular, it will not work with Jersey unless you enable Spring MVC as well.

48. Enabling production-ready features

The spring-boot-actuator module provides all of Spring Boot’s production-ready features. The simplest way to enable the features is to add a dependency to the spring-boot-starter-actuator ‘Starter’.

To add the actuator to a Maven based project, add the following ‘Starter’ dependency:

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

For Gradle, use the declaration:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-actuator")
}

49. Endpoints

Actuator endpoints allow you to monitor and interact with your application. Spring Boot includes a number of built-in endpoints and you can also add your own. For example the health endpoint provides basic application health information.

The way that endpoints are exposed will depend on the type of technology that you choose. Most applications choose HTTP monitoring, where the ID of the endpoint along with a prefix of /application is mapped to a URL. For example, by default, the health endpoint will be mapped to /application/health.

The following technology agnostic endpoints are available:

ID Description Sensitive Default

actuator

Provides a hypermedia-based 「discovery page」 for the other endpoints. Requires Spring HATEOAS to be on the classpath.

true

auditevents

Exposes audit events information for the current application.

true

autoconfig

Displays an auto-configuration report showing all auto-configuration candidates and the reason why they ‘were’ or ‘were not’ applied.

true

beans

Displays a complete list of all the Spring beans in your application.

true

configprops

Displays a collated list of all @ConfigurationProperties.

true

dump

Performs a thread dump.

true

env

Exposes properties from Spring’s ConfigurableEnvironment.

true

flyway

Shows any Flyway database migrations that have been applied.

true

health

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

info

Displays arbitrary application info.

false

loggers

Shows and modifies the configuration of loggers in the application.

true

liquibase

Shows any Liquibase database migrations that have been applied.

true

metrics

Shows ‘metrics’ information for the current application.

true

mappings

Displays a collated list of all @RequestMapping paths.

true

shutdown

Allows the application to be gracefully shutdown (not enabled by default).

true

trace

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

docs

Displays documentation, including example requests and responses, for the Actuator’s endpoints. Requires spring-boot-actuator-docs to be on the classpath.

false

heapdump

Returns a GZip compressed hprof heap dump file.

true

jolokia

Exposes JMX beans over HTTP (when Jolokia is on the classpath).

true

logfile

Returns the contents of the logfile (if logging.file or logging.path properties have been set). Supports the use of the HTTP Range header to retrieve part of the log file’s content.

true

[注意]

Depending on how an endpoint is exposed, the sensitive property may be used as a security hint. For example, sensitive endpoints will require a username/password when they are accessed over HTTP (or simply disabled if web security is not enabled).

49.1 Customizing endpoints

Endpoints can be customized using Spring properties. You can change if an endpoint is enabled, if it is considered sensitive and even its id.

For example, here is an application.properties that changes the sensitivity and id of the beans endpoint and also enables shutdown.

endpoints.beans.id=springbeans
endpoints.beans.sensitive=false endpoints.shutdown.enabled=true
[注意]

The prefix ‟endpoints + . + name」 is used to uniquely identify the endpoint that is being configured.

By default, all endpoints except for shutdown are enabled. If you prefer to specifically 「opt-in」 endpoint enablement you can use the endpoints.enabled property. For example, the following will disable all endpoints except for info:

endpoints.enabled=false
endpoints.info.enabled=true

Likewise, you can also choose to globally set the 「sensitive」 flag of all endpoints. By default, the sensitive flag depends on the type of endpoint (see the table above). For example, to mark all endpoints as sensitive except info:

endpoints.sensitive=true
endpoints.info.sensitive=false

49.2 Hypermedia for actuator MVC endpoints

If endpoints.hypermedia.enabled is set to true and Spring HATEOAS is on the classpath (e.g. through the spring-boot-starter-hateoas or if you are usingSpring Data REST) then the HTTP endpoints from the Actuator are enhanced with hypermedia links, and a 「discovery page」 is added with links to all the endpoints. The 「discovery page」 is available on /application by default. It is implemented as an endpoint, allowing properties to be used to configure its path (endpoints.actuator.path) and whether or not it is enabled (endpoints.actuator.enabled).

When a custom management context path is configured, the 「discovery page」 will automatically move from /application to the root of the management context. For example, if the management context path is /management then the discovery page will be available from /management.

若是HAL瀏覽器經過其webjar(org.webjars:hal-browser位於類路徑上,或者經過spring-data-rest-hal-browserHAL瀏覽器的形式經過HTML「發現頁面」提供。

49.3 CORS支持

跨源資源共享 (CORS)是一種W3C規範,容許您以靈活的方式指定受權的跨域請求類型。Actuator的MVC端點能夠配置爲支持此類方案。

默認狀況下禁用CORS支持,而且僅endpoints.cors.allowed-origins在設置屬性後才啓用CORS支持 下面許可的配置 GETPOST從電話example.com域:

endpoints.cors.allowed-origins = http://example.com endpoints.cors.allowed-methods = GET,POST
[小費]

檢查EndpointCorsProperties 以獲取完整的選項列表。

49.4添加自定義端點

若是添加一個@Bean類型Endpoint,它將自動經過JMX和HTTP公開(若是有可用的服務器)。能夠經過建立類型的bean來進一步自定義HTTP端點MvcEndpointMvcEndpoint不是,@Controller但它能夠使用@RequestMapping(和@Managed*)來公開資源。

[小費]

若是你這樣作是爲庫特徵考慮增長帶註釋的配置類@ManagementContextConfiguration/META-INF/spring.factories下鍵org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration若是您這樣作,那麼若是您的用戶要求單獨的管理端口或地址,則端點將移動到具備全部其餘MVC端點的子上下文。WebConfigurerAdapter若是它想要將靜態資源(例如)添加到管理端點,則以這種方式聲明的配置能夠是

49.5健康信息

運行情況信息可用於檢查正在運行的應用程序的狀態。監視軟件常用它來提醒某人生產系統是否出現故障。health端點公開的默認信息取決於訪問方式。對於安全應用程序中未經身份驗證的鏈接,將返回簡單的「狀態」消息,對於通過身份驗證的鏈接,還會顯示其餘詳細信息(有關HTTP詳細信息請參見 第50.7節「HTTP健康端點格式和訪問限制」)。

健康信息是從HealthIndicator您定義的全部bean中收集 ApplicationContextSpring Boot包括一些自動配置 HealthIndicators,你也能夠編寫本身的。默認狀況下,最終系統狀態是經過 基於有序狀態列表對HealthAggregator每一個狀態進行排序來派生的HealthIndicator排序列表中的第一個狀態用做總體運行情況。若是否,則HealthIndicator返回已知 HealthAggregatorUNKNOWN狀態,則使用狀態。

49.6 HealthIndicators的安全性

Information returned by HealthIndicators is often somewhat sensitive in nature. For example, you probably don’t want to publish details of your database server to the world. For this reason, by default, only the health status is exposed over an unauthenticated HTTP connection. If you are happy for complete health information to always be exposed you can set endpoints.health.sensitive to false.

Health responses are also cached to prevent 「denial of service」 attacks. Use the endpoints.health.time-to-live property if you want to change the default cache period of 1000 milliseconds.

49.6.1 Auto-configured HealthIndicators

The following HealthIndicators are auto-configured by Spring Boot when appropriate:

Name Description

CassandraHealthIndicator

Checks that a Cassandra database is up.

DiskSpaceHealthIndicator

Checks for low disk space.

DataSourceHealthIndicator

Checks that a connection to DataSource can be obtained.

ElasticsearchHealthIndicator

Checks that an Elasticsearch cluster is up.

JmsHealthIndicator

Checks that a JMS broker is up.

MailHealthIndicator

Checks that a mail server is up.

MongoHealthIndicator

Checks that a Mongo database is up.

RabbitHealthIndicator

Checks that a Rabbit server is up.

RedisHealthIndicator

Checks that a Redis server is up.

SolrHealthIndicator

Checks that a Solr server is up.

[小費]

It is possible to disable them all using the management.health.defaults.enabled property.

49.6.2 Writing custom HealthIndicators

To provide custom health information you can register Spring beans that implement the HealthIndicator interface. You need to provide an implementation of the health() method and return a Health response. The Health response should include a status and can optionally include additional details to be displayed.

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down().withDetail("Error Code", errorCode).build(); } return Health.up().build(); } }
[注意]

給定的標識符HealthIndicator是沒有HealthIndicator後綴的bean的名稱( 若是存在)。在上面的示例中,健康信息將在名爲的條目中可用my

除了Spring Boot的預約義Status 類型以外,還能夠Health返回Status表示新系統狀態的自定義在這種狀況下,HealthAggregator 還須要提供接口的自定義實現,或者必須使用management.health.status.order配置屬性配置默認實現

例如,假設在您的某個實現中使用了 Status帶代碼的新代碼要配置嚴重性順序,請將如下內容添加到應用程序屬性中:FATALHealthIndicator

management.health.status.order = FATAL,DOWN,OUT_OF_SERVICE,UNKNOWN,UP

響應中的HTTP狀態代碼反映了總體運行情況(例如,UP 映射到200 OUT_OF_SERVICEDOWN503)。HealthMvcEndpoint若是經過HTTP訪問運行情況端點,您可能還但願註冊自定義狀態映射例如,如下映射FATALHttpStatus.SERVICE_UNAVAILABLE

endpoints.health.mapping.FATAL = 503

內置狀態的默認狀態映射是:

狀態 製圖

SERVICE_UNAVAILABLE(503)

中止服務

SERVICE_UNAVAILABLE(503)

UP

默認狀況下沒有映射,所以http狀態爲200

未知

默認狀況下沒有映射,所以http狀態爲200

49.7申請信息

應用程序信息公開從InfoContributor您的中定義的全部bean 收集的各類信息 ApplicationContextSpring Boot包括一些自動配置 InfoContributors,你也能夠編寫本身的。

49.7.1自動配置的InfoContributors

InfoContributors適當時,Spring Boot會自動配置如下內容

名稱 描述

EnvironmentInfoContributor

鑰匙Environment下方露出任何info鑰匙。

GitInfoContributor

若是git.properties文件可用,則公開git信息

BuildInfoContributor

若是META-INF/build-info.properties文件可用,則公開構建信息

[小費]

能夠使用management.info.defaults.enabled 屬性禁用它們

49.7.2自定義應用程序信息信息

您能夠info經過設置info.*Spring屬性來自定義端點公開的數據Environment信息鍵下的全部屬性都將自動公開。例如,您能夠將如下內容添加到您的application.properties

info.app.encoding = UTF-8 info.app.java.source = 1.8 info.app.java.target = 1.8
[小費]

您能夠在構建時擴展信息屬性,而不是對這些值進行硬編碼 

假設您正在使用Maven,您能夠按以下方式重寫上面的示例:

info.app.encoding =@project.build.sourceEncoding @ info.app.java.source =@java.version @ info.app.java.target =@java.version @

49.7.3 Git提交信息

info端點的另外一個有用功能是它可以git在構建項目時發佈有關源代碼存儲庫狀態的信息。若是 GitProperties豆可用,git.branchgit.commit.idgit.commit.time屬性將被暴露出來。

[小費]

一個GitPropertiesbean是自動配置,若是一個git.properties文件可在classpath的根目錄。有關更多詳細信息請參閱 生成git信息

若是要顯示完整的git信息(即完整內容 git.properties),請使用如下management.info.git.mode屬性:

management.info.git.mode =已滿

49.7.4構建信息

info若是BuildProperties bean可用端點還能夠發佈有關構建的信息。若是META-INF/build-info.properties類路徑中文件可用,則會發生這種狀況

[小費]

Maven和Gradle插件均可以生成該文件,有關詳細信息,請參閱 生成構建信息

49.7.5編寫自定義InfoContributors

要提供自定義應用程序信息,您能夠註冊實現該InfoContributor接口的Spring bean 

下面的示例提供了example具備單個值條目:

import java.util.Collections;

import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component 公共  ExampleInfoContributor實現 InfoContributor { @Override  public void contribution(Info.Builder builder){ builder.withDetail(「example」 Collections.singletonMap(「key」「value」)); }  }

若是您點擊info端點,您應該看到包含如下附加條目的響應:

{ 
    「example」{ 「key」「value」 } }

50.經過HTTP監控和管理

If you are developing a Spring MVC application, Spring Boot Actuator will auto-configure all enabled endpoints to be exposed over HTTP. The default convention is to use the id of the endpoint with a prefix of /application as the URL path. For example, health is exposed as /application/health.

50.1 Accessing sensitive endpoints

By default all sensitive HTTP endpoints are secured such that only users that have an ACTUATOR role may access them. Security is enforced using the standardHttpServletRequest.isUserInRole method.

[小費]

Use the management.security.roles property if you want something different to ACTUATOR.

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 management.security.enabled property.

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

若是您的自定義安全配置能夠保護您的執行器端點,則還須要確保通過身份驗證的用戶具備指定的角色

相關文章
相關標籤/搜索