diff --git a/I. Spring Boot Documentation/1. About the Documentation.md b/I. Spring Boot Documentation/1. About the Documentation.md new file mode 100644 index 00000000..9fe5a9e8 --- /dev/null +++ b/I. Spring Boot Documentation/1. About the Documentation.md @@ -0,0 +1,10 @@ +### 1. 关于本文档 + +Spring Boot参考指南有如下形式的文档: +- [HTML](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/html) +- [PDF](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/pdf/spring-boot-reference.pdf) +- [EPUB](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/epub/spring-boot-reference.epub) + +你可以从[docs.spring.io/spring-boot/docs/current/reference](https://docs.spring.io/spring-boot/docs/current/reference)获取到最新版本。 + +对本文档的拷贝,不管是电子版还是打印,在保证包含版权声明,并且不收取任何费用的情况下,你可以自由使用,或分发给其他人。 diff --git a/I. Spring Boot Documentation/1. About the documentation.md b/I. Spring Boot Documentation/1. About the documentation.md deleted file mode 100644 index 16fa22e1..00000000 --- a/I. Spring Boot Documentation/1. About the documentation.md +++ /dev/null @@ -1,5 +0,0 @@ -### 1. 关于本文档 - -Spring Boot参考指南有[html](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/html),[pdf](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/pdf/spring-boot-reference.pdf)和[epub](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/epub/spring-boot-reference.epub)等形式的文档,你可以从[docs.spring.io/spring-boot/docs/current/reference](http://docs.spring.io/spring-boot/docs/current/reference)获取到最新版本。 - -对本文档的拷贝,不管是电子版还是打印,在保证包含版权声明,并且不收取任何费用的情况下,你可以自由使用,或分发给其他人。 diff --git a/I. Spring Boot Documentation/2. Getting Help.md b/I. Spring Boot Documentation/2. Getting Help.md new file mode 100644 index 00000000..391bcfe7 --- /dev/null +++ b/I. Spring Boot Documentation/2. Getting Help.md @@ -0,0 +1,10 @@ +### 2. 获取帮助 + +如果你在使用Spring Boot时遇到了麻烦,我们很乐意帮忙。 + +- 尝试[How-to文档](../IX. ‘How-to’ guides/README.md)。它们为多数常见问题提供解决方案。 +- 学习Spring基础知识。Spring Boot是在很多其他Spring项目上构建的,查看[spring.io](http://spring.io/)站点可以获取丰富的参考文档。如果你刚开始使用Spring,可以尝试这些[指导](http://spring.io/guides)中的一个。 +- 提问题。我们时刻监控着[stackoverflow.com](http://stackoverflow.com/)上标记为[spring-boot](http://stackoverflow.com/tags/spring-boot)的问题。 +- 在[github.com/spring-projects/spring-boot/issues](https://github.com/spring-projects/spring-boot/issues)上报告Spring Boot的bug。 + +**注**:Spring Boot的一切都是开源的,包括文档。如果你发现文档有问题,或是想提高它们的质量,请[参与进来](http://github.com/spring-projects/spring-boot/tree/master)! diff --git a/I. Spring Boot Documentation/2. Getting help.md b/I. Spring Boot Documentation/2. Getting help.md deleted file mode 100644 index 84e69fdb..00000000 --- a/I. Spring Boot Documentation/2. Getting help.md +++ /dev/null @@ -1,10 +0,0 @@ -### 2. 获取帮助 - -使用Spring Boot遇到麻烦,我们很乐意帮忙! - -- 尝试[How-to’s](../IX. ‘How-to’ guides/README.md)-它们为多数常见问题提供解决方案。 -- 学习Spring基础知识-Spring Boot是在很多其他Spring项目上构建的,查看[spring.io](http://spring.io/)站点可以获取丰富的参考文档。如果你刚开始使用Spring,可以尝试这些[指导](http://spring.io/guides)中的一个。 -- 提问题-我们时刻监控着[stackoverflow.com](http://stackoverflow.com/)上标记为[spring-boot](http://stackoverflow.com/tags/spring-boot)的问题。 -- 在[github.com/spring-projects/spring-boot/issues](https://github.com/spring-projects/spring-boot/issues)上报告Spring Boot的bug。 - -**注**:Spring Boot的一切都是开源的,包括文档!如果你发现文档有问题,或只是想提高它们的质量,请[参与进来](http://github.com/spring-projects/spring-boot/tree/master)! diff --git a/I. Spring Boot Documentation/3. First Steps.md b/I. Spring Boot Documentation/3. First Steps.md new file mode 100644 index 00000000..a6e64eb8 --- /dev/null +++ b/I. Spring Boot Documentation/3. First Steps.md @@ -0,0 +1,7 @@ +### 3. 第一步 + +如果你想对Spring Boot或Spring有个整体认识,可以从[下列主题](../II. Getting started/README.md)开始: + +- 从零开始:[概述](../II. Getting started/8. Introducing Spring Boot.md)|[要求](../II. Getting started/9. System Requirements.md)|[安装](../II. Getting started/10. Installing Spring Boot.md) +- 教程:[第一部分](../II. Getting started/11. Developing your first Spring Boot application.md)|[第二部分](../II. Getting started/11.3. Writing the code.md) +- 运行示例:[第一部分](../II. Getting started/11.4. Running the example.md)|[第二部分](../II. Getting started/11.5. Creating an executable jar.md) diff --git a/I. Spring Boot Documentation/3. First steps.md b/I. Spring Boot Documentation/3. First steps.md deleted file mode 100644 index 97447527..00000000 --- a/I. Spring Boot Documentation/3. First steps.md +++ /dev/null @@ -1,7 +0,0 @@ -### 3. 第一步 - -如果你想对Spring Boot或Spring有个整体认识,可以从[这里开始](../II. Getting started/README.md)! - -- 从零开始:[概述](../II. Getting started/8. Introducing Spring Boot.md)|[要求](../II. Getting started/9. System Requirements.md)|[安装](../II. Getting started/10. Installing Spring Boot.md) -- 教程:[第一部分](../II. Getting started/11. Developing your first Spring Boot application.md)|[第二部分](../II. Getting started/11.3. Writing the code.md) -- 运行示例:[第一部分](../II. Getting started/11.4. Running the example.md)|[第二部分](../II. Getting started/11.5. Creating an executable jar.md) diff --git a/I. Spring Boot Documentation/4. Working with Spring Boot.md b/I. Spring Boot Documentation/4. Working with Spring Boot.md index fb4cbc7f..eb00bdf1 100644 --- a/I. Spring Boot Documentation/4. Working with Spring Boot.md +++ b/I. Spring Boot Documentation/4. Working with Spring Boot.md @@ -1,6 +1,6 @@ ### 4. 使用Spring Boot -准备好使用Spring Boot了?[我们已经为你铺好道路](../III. Using Spring Boot/README.md). +准备好使用Spring Boot了?[我们已经为你铺好了道路](../III. Using Spring Boot/README.md): - 构建系统:[Maven](../III. Using Spring Boot/13.2. Maven.md)|[Gradle](../III. Using Spring Boot/13.3. Gradle.md)|[Ant](../III. Using Spring Boot/13.4. Ant.md)|[Starters](../III. Using Spring Boot/13.5. Starters.md) - 最佳实践:[代码结构](../III. Using Spring Boot/14. Structuring your code.md)|[@Configuration](../III. Using Spring Boot/15. Configuration classes.md)|[@EnableAutoConfiguration](../III. Using Spring Boot/16. Auto-configuration.md)|[Beans和依赖注入](../III. Using Spring Boot/17. Spring Beans and dependency injection.md) diff --git a/I. Spring Boot Documentation/5. Learning about Spring Boot Features.md b/I. Spring Boot Documentation/5. Learning about Spring Boot Features.md new file mode 100644 index 00000000..de397edb --- /dev/null +++ b/I. Spring Boot Documentation/5. Learning about Spring Boot Features.md @@ -0,0 +1,10 @@ +### 5. 了解Spring Boot特性 + +想要了解更多Spring Boot核心特性的详情?[下列内容就是为你准备的](../IV. Spring Boot features/README.md): + +- 核心特性:[SpringApplication](../IV. Spring Boot features/23. SpringApplication.md)|[外部化配置](../IV. Spring Boot features/24. Externalized Configuration.md)|[Profiles](../IV. Spring Boot features/25. Profiles.md)|[日志](../IV. Spring Boot features/26. Logging.md) +- Web应用:[MVC](../IV. Spring Boot features/27.1. The ‘Spring Web MVC framework’.md)|[内嵌容器](../IV. Spring Boot features/27.3 Embedded servlet container support.md) +- 使用数据:[SQL](../IV. Spring Boot features/29. Working with SQL databases.md)|[NO-SQL](../IV. Spring Boot features/30. Working with NoSQL technologies.md) +- 消息:[概述](../IV. Spring Boot features/32. Messaging.md)|[JMS](../IV. Spring Boot features/32.1. JMS.md) +- 测试:[概述](../IV. Spring Boot features/40. Testing.md)|[Boot应用](../IV. Spring Boot features/40.3 Testing Spring Boot applications.md)|[工具](../IV. Spring Boot features/40.4 Test utilities.md) +- 扩展:[Auto-configuration](../IV. Spring Boot features/43. Creating your own auto-configuration.md)|[@Conditions](../IV. Spring Boot features/43.3 Condition annotations.md) diff --git a/I. Spring Boot Documentation/5. Learning about Spring Boot features.md b/I. Spring Boot Documentation/5. Learning about Spring Boot features.md deleted file mode 100644 index ed6c3005..00000000 --- a/I. Spring Boot Documentation/5. Learning about Spring Boot features.md +++ /dev/null @@ -1,10 +0,0 @@ -### 5. 了解Spring Boot特性 - -想要了解更多Spring Boot核心特性的详情?[这就是为你准备的](../IV. Spring Boot features/README.md)! - -- 核心特性:[SpringApplication](../IV. Spring Boot features/23. SpringApplication.md)|[外部化配置](../IV. Spring Boot features/24. Externalized Configuration.md)|[Profiles](../IV. Spring Boot features/25. Profiles.md)|[日志](../IV. Spring Boot features/26. Logging.md) -- Web应用:[MVC](../IV. Spring Boot features/27.1. The ‘Spring Web MVC framework’.md)|[内嵌容器](../IV. Spring Boot features/27.3 Embedded servlet container support.md) -- 使用数据:[SQL](../IV. Spring Boot features/29. Working with SQL databases.md)|[NO-SQL](../IV. Spring Boot features/30. Working with NoSQL technologies.md) -- 消息:[概述](../IV. Spring Boot features/32. Messaging.md)|[JMS](../IV. Spring Boot features/32.1. JMS.md) -- 测试:[概述](../IV. Spring Boot features/40. Testing.md)|[Boot应用](../IV. Spring Boot features/40.3 Testing Spring Boot applications.md)|[工具](../IV. Spring Boot features/40.4 Test utilities.md) -- 扩展:[Auto-configuration](../IV. Spring Boot features/43. Creating your own auto-configuration.md)|[@Conditions](../IV. Spring Boot features/43.3 Condition annotations.md) diff --git a/I. Spring Boot Documentation/6. Moving to Production.md b/I. Spring Boot Documentation/6. Moving to Production.md new file mode 100644 index 00000000..4ea50fa4 --- /dev/null +++ b/I. Spring Boot Documentation/6. Moving to Production.md @@ -0,0 +1,7 @@ +### 6. 迁移到生产环境 + +当你准备将Spring Boot应用发布到生产环境时,我们提供了一些你[可能喜欢的技巧](../V. Spring Boot Actuator/README.md)! + +- 管理端点:[概述](../V. Spring Boot Actuator/46. Endpoints.md)|[自定义](../V. Spring Boot Actuator/46.1 Customizing endpoints.md) +- 连接选项:[HTTP](../V. Spring Boot Actuator/47. Monitoring and management over HTTP.md)|[JMX](../V. Spring Boot Actuator/48. Monitoring and management over JMX.md) +- 监控:[指标](../V. Spring Boot Actuator/50. Metrics.md)|[审计](../V. Spring Boot Actuator/51. Auditing.md)|[追踪](../V. Spring Boot Actuator/52. Tracing.md)|[进程](../V. Spring Boot Actuator/53. Process monitoring.md) diff --git a/I. Spring Boot Documentation/6. Moving to production.md b/I. Spring Boot Documentation/6. Moving to production.md deleted file mode 100644 index 418a25c6..00000000 --- a/I. Spring Boot Documentation/6. Moving to production.md +++ /dev/null @@ -1,7 +0,0 @@ -### 6. 迁移到生产环境 - -当你准备将Spring Boot应用发布到生产环境时,我们提供了一些你[可能喜欢的技巧](../V. Spring Boot Actuator/README.md)! - -- 管理端点:[概述](../V. Spring Boot Actuator/46. Endpoints.md)|[自定义](../V. Spring Boot Actuator/46.1 Customizing endpoints.md) -- 连接选项:[HTTP](../V. Spring Boot Actuator/47. Monitoring and management over HTTP.md)|[JMX](../V. Spring Boot Actuator/48. Monitoring and management over JMX.md)|[SSH](../V. Spring Boot Actuator/49. Monitoring and management using a remote shell.md) -- 监控:[指标](../V. Spring Boot Actuator/50. Metrics.md)|[审计](../V. Spring Boot Actuator/51. Auditing.md)|[追踪](../V. Spring Boot Actuator/52. Tracing.md)|[进程](../V. Spring Boot Actuator/53. Process monitoring.md) diff --git a/I. Spring Boot Documentation/7. Advanced Topics.md b/I. Spring Boot Documentation/7. Advanced Topics.md new file mode 100644 index 00000000..5012fdb5 --- /dev/null +++ b/I. Spring Boot Documentation/7. Advanced Topics.md @@ -0,0 +1,7 @@ +### 7. 高级主题 + +最后,我们为高级用户准备了一些主题。 + +- Spring Boot应用部署:[云部署](../VI. Deploying Spring Boot applications/55. Deploying to the cloud.md) | [操作系统服务](../VI. Deploying Spring Boot applications/56.1 Unix&Linux services.md) +- 构建工具插件:[Maven](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-maven-plugin)|[Gradle](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-gradle-plugin) +- 附录:[应用属性](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties)|[Auto-configuration类](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#auto-configuration-classes)|[可执行Jars](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#executable-jar) diff --git a/I. Spring Boot Documentation/7. Advanced topics.md b/I. Spring Boot Documentation/7. Advanced topics.md deleted file mode 100644 index 1c0e08b0..00000000 --- a/I. Spring Boot Documentation/7. Advanced topics.md +++ /dev/null @@ -1,7 +0,0 @@ -### 7. 高级主题 - -最后,我们为高级用户准备了一些主题。 - -- 部署Spring Boot应用:[云部署](../VI. Deploying Spring Boot applications/55. Deploying to the cloud.md) | [操作系统服务](../VI. Deploying Spring Boot applications/56.1 Unix&Linux services.md) -- 构建工具插件:[Maven](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-maven-plugin)|[Gradle](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-gradle-plugin) -- 附录:[应用属性](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties)|[Auto-configuration类](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#auto-configuration-classes)|[可执行Jars](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#executable-jar) diff --git a/II. Getting Started/10. Installing Spring Boot.md b/II. Getting Started/10. Installing Spring Boot.md new file mode 100644 index 00000000..27e8dbf3 --- /dev/null +++ b/II. Getting Started/10. Installing Spring Boot.md @@ -0,0 +1,7 @@ +### 10. Spring Boot安装 + +Spring Boot可以跟经典的Java开发工具一起使用或安装成一个命令行工具。无论哪种方式,你都需要安装[Java SDK v1.8 ](http://www.java.com/)或更高版本。在开始之前,你需要使用下面的命令,检查下当前安装的Java版本: +```shell +$ java -version +``` +如果你是一个Java新手,或想体验一下Spring Boot,你可能想先尝试[Spring Boot CLI](10.2. Installing the Spring Boot CLI.md)(命令行界面)。否则,请继续阅读“经典”的安装指南。 \ No newline at end of file diff --git a/II. Getting started/10.1. Installation instructions for the Java developer.md b/II. Getting Started/10.1. Installation Instructions for the Java Developer.md similarity index 100% rename from II. Getting started/10.1. Installation instructions for the Java developer.md rename to II. Getting Started/10.1. Installation Instructions for the Java Developer.md diff --git a/II. Getting Started/10.1.1. Maven Installation.md b/II. Getting Started/10.1.1. Maven Installation.md new file mode 100644 index 00000000..c2b0e09b --- /dev/null +++ b/II. Getting Started/10.1.1. Maven Installation.md @@ -0,0 +1,48 @@ + +### 10.1.1. Maven安装 + +Spring Boot兼容Apache Maven 3.2或更高版本。如果本地没有安装Maven,你可以参考[maven.apache.org](http://maven.apache.org/)上的指南。 + +**注**:在很多操作系统上,可以通过包管理器来安装Maven。如果你使用OSX Homebrew,尝试`brew install maven`。Ubuntu用户可以运行`sudo apt-get install maven`。使用Chocolatey的Windows用户可以以管理员身份在命令提示符上运行`choco install maven`。 + +Spring Boot依赖使用的groupId为`org.springframework.boot`。通常,你的Maven POM文件会继承`spring-boot-starter-parent`工程,并声明一个或多个[“Starter POMs”](../III. Using Spring Boot/13.4. Starter POMs.md)依赖。此外,Spring Boot提供了一个可选的[Maven插件](../VIII. Build tool plugins/58. Spring Boot Maven plugin.md),用于创建可执行jars。 + +下面是一个典型的pom.xml文件: +```xml + + + 4.0.0 + + com.example + myproject + 0.0.1-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + +``` +**注**:`spring-boot-starter-parent`是使用Spring Boot的一种不错的方式,但它并不总是最合适的。有时你可能需要继承一个不同的父POM,或是不喜欢我们的默认配置。这些情况,请查看[章节 13.2.2,在不使用parent POM的情况下玩转Spring Boot](../III. Using Spring Boot/13.1.2. Using Spring Boot without the Parent POM.md)。 diff --git a/II. Getting Started/10.1.2. Gradle Installation.md b/II. Getting Started/10.1.2. Gradle Installation.md new file mode 100644 index 00000000..7003c6ea --- /dev/null +++ b/II. Getting Started/10.1.2. Gradle Installation.md @@ -0,0 +1,32 @@ +### 10.1.2. Gradle安装 + +Spring Boot兼容Gradle 4。如果本地没有安装Gradle,你可以参考[gradle.org](https://gradle.org/)上的指南。 + +Spring Boot的依赖可通过groupId `org.springframework.boot`来声明。通常,你的项目声明一个或多个[“Starter POMs”](../III. Using Spring Boot/13.4. Starter POMs.md)依赖。Spring Boot提供了一个很有用的[Gradle插件](../VIII. Build tool plugins/59. Spring Boot Gradle plugin.md),可以用来简化依赖声明,创建可执行jars。 + +**Gradle Wrapper** + +**注** 当你需要构建项目时,Gradle Wrapper提供一种给力的获取Gradle的方式。它是一小段脚本和库,跟你的代码一块提交,用于启动构建进程,具体参考[Gradle Wrapper](https://docs.gradle.org/4.2.1/userguide/gradle_wrapper.html)。 + +下面是一个典型的`build.gradle`文件: +```gradle +plugins { + id 'org.springframework.boot' version '2.0.0.RELEASE' + id 'java' +} + + +jar { + baseName = 'myproject' + version = '0.0.1-SNAPSHOT' +} + +repositories { + jcenter() +} + +dependencies { + compile("org.springframework.boot:spring-boot-starter-web") + testCompile("org.springframework.boot:spring-boot-starter-test") +} +``` diff --git a/II. Getting Started/10.2. Installing the Spring Boot CLI.md b/II. Getting Started/10.2. Installing the Spring Boot CLI.md new file mode 100644 index 00000000..276a64ff --- /dev/null +++ b/II. Getting Started/10.2. Installing the Spring Boot CLI.md @@ -0,0 +1,5 @@ +### 10.2. Spring Boot CLI安装 + +Spring Boot CLI(命令行界面)是一个命令行工具,可用于快速搭建基于Spring的原型。它支持运行[Groovy](http://groovy.codehaus.org/)脚本,这也就意味着你可以使用类似Java的语法,但不用写很多的模板代码。 + +Spring Boot不一定非要配合CLI使用,但它绝对是Spring应用取得进展的最快方式(你咋不飞上天呢?)。 \ No newline at end of file diff --git a/II. Getting Started/10.2.1. Manual Installation.md b/II. Getting Started/10.2.1. Manual Installation.md new file mode 100644 index 00000000..6f2b26c4 --- /dev/null +++ b/II. Getting Started/10.2.1. Manual Installation.md @@ -0,0 +1,10 @@ +### 10.2.1. 手动安装 + +Spring CLI分发包可以从Spring软件仓库下载: + +1. [spring-boot-cli-2.0.0.RELEASE-bin.zip](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/2.0.0.RELEASE/spring-boot-cli-2.0.0.RELEASE-bin.zip) +2. [spring-boot-cli-2.0.0.RELEASE-bin.tar.gz](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/2.0.0.RELEASE/spring-boot-cli-2.0.0.RELEASE-bin.tar.gz) + +不稳定的[snapshot分发包](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/)也可以获取到。 + +下载完成后,解压分发包,根据存档里的[INSTALL.txt](http://raw.github.com/spring-projects/spring-boot/master/spring-boot-cli/src/main/content/INSTALL.txt)操作指南进行安装。总的来说,在`.zip`文件的`bin/`目录下会有一个spring脚本(Windows下是`spring.bat`),或使用`java -jar`运行`lib/`目录下的`.jar`文件(该脚本会帮你确保classpath被正确设置)。 diff --git a/II. Getting started/10.2.2. Installation with SDKMAN.md b/II. Getting Started/10.2.2. Installation with SDKMAN.md similarity index 85% rename from II. Getting started/10.2.2. Installation with SDKMAN.md rename to II. Getting Started/10.2.2. Installation with SDKMAN.md index 70f8e463..6fedf85b 100644 --- a/II. Getting started/10.2.2. Installation with SDKMAN.md +++ b/II. Getting Started/10.2.2. Installation with SDKMAN.md @@ -4,16 +4,16 @@ SDKMAN(软件开发包管理器)可以对各种各样的二进制SDK包进 ```shell $ sdk install springboot $ spring --version -Spring Boot v2.0.0.M5 +Spring Boot v2.0.0.RELEASE ``` 如果你正在为CLI开发新的特性,并想轻松获取刚构建的版本,可以使用以下命令: ```shell -$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.0.0.M5-bin/spring-2.0.0.M5/ +$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.0.0.RELEASE-bin/spring-2.0.0.RELEASE/ $ sdk default springboot dev $ spring --version -Spring CLI v2.0.0.M5 +Spring CLI v2.0.0.RELEASE ``` -这将会安装一个名叫dev的本地spring实例,它指向你的目标构建位置,所以每次你重新构建Spring Boot,spring都会更新为最新的。 +这将会安装一个名叫dev的本地spring实例,它指向你的目标构建位置,所以每次你重新构建Spring Boot,spring都会是最新的。 你可以通过以下命令来验证: ```shell @@ -23,7 +23,7 @@ $ sdk ls springboot Available Springboot Versions ================================================================================ > + dev -* 2.0.0.M5 +* 2.0.0.RELEASE ================================================================================ + - local version diff --git a/II. Getting Started/10.2.3. OSX Homebrew Installation.md b/II. Getting Started/10.2.3. OSX Homebrew Installation.md new file mode 100644 index 00000000..11361d20 --- /dev/null +++ b/II. Getting Started/10.2.3. OSX Homebrew Installation.md @@ -0,0 +1,10 @@ +### 10.2.3. 使用OSX Homebrew进行安装 + +如果你的环境是Mac,并使用[Homebrew](http://brew.sh/),你可以使用下面的命令安装Spring Boot CLI: +```shell +$ brew tap pivotal/tap +$ brew install springboot +``` +Homebrew会把spring安装到`/usr/local/bin`下。 + +**注**:如果该方案不可用,可能是因为你的brew版本太老了。你需要执行`brew update`,然后重试。 diff --git a/II. Getting Started/10.2.4. MacPorts Installation.md b/II. Getting Started/10.2.4. MacPorts Installation.md new file mode 100644 index 00000000..dee32f39 --- /dev/null +++ b/II. Getting Started/10.2.4. MacPorts Installation.md @@ -0,0 +1,6 @@ +### 10.2.4. 使用MacPorts进行安装 + +如果你的环境是Mac,并使用[MacPorts](http://www.macports.org/),你可以使用下面的命令安装Spring Boot CLI: +```shell +$ sudo port install spring-boot-cli +``` diff --git a/II. Getting started/10.2.5. Command-line completion.md b/II. Getting Started/10.2.5. Command-line Completion.md similarity index 100% rename from II. Getting started/10.2.5. Command-line completion.md rename to II. Getting Started/10.2.5. Command-line Completion.md diff --git a/II. Getting Started/10.2.6. Quick-start Spring CLI Example.md b/II. Getting Started/10.2.6. Quick-start Spring CLI Example.md new file mode 100644 index 00000000..5a2855cc --- /dev/null +++ b/II. Getting Started/10.2.6. Quick-start Spring CLI Example.md @@ -0,0 +1,24 @@ +### 10.2.6. Spring CLI示例快速入门 + +你可以使用下面的web应用,测试Spring CLI安装是否成功。创建一个名叫`app.groovy`的文件: +```groovy +@RestController +class ThisWillActuallyRun { + + @RequestMapping("/") + String home() { + "Hello World!" + } + +} +``` +然后,在shell中运行以下命令: +```shell +$ spring run app.groovy +``` +**注**:首次运行该应用比较慢,因为需要下载依赖,后续运行将会快很多。 + +使用你最喜欢的浏览器打开[localhost:8080](localhost:8080),然后就可以看到如下输出: +```java +Hello World! +``` diff --git a/II. Getting Started/10.3. Upgrading from an Earlier Version of Spring Boot.md b/II. Getting Started/10.3. Upgrading from an Earlier Version of Spring Boot.md new file mode 100644 index 00000000..7f5211ee --- /dev/null +++ b/II. Getting Started/10.3. Upgrading from an Earlier Version of Spring Boot.md @@ -0,0 +1,5 @@ +### 10.3. 版本升级 + +如果你正在升级Spring Boot的早期发布版本,那最好查看下[project wiki](http://github.com/spring-projects/spring-boot/wiki)上的"迁移指南",你会找到升级说明和一个对应每次版本发布的"new and noteworthy"特性列表。 + +想要升级一个已安装的CLI,你需要使用合适的包管理命令,例如`brew upgrade`;如果是手动安装CLI,按照[standard instructions](10.2.1. Manual installation.md)操作并记得更新你的PATH环境变量以移除任何老的引用。 diff --git a/II. Getting Started/11. Developing Your First Spring Boot Application.md b/II. Getting Started/11. Developing Your First Spring Boot Application.md new file mode 100644 index 00000000..c5858388 --- /dev/null +++ b/II. Getting Started/11. Developing Your First Spring Boot Application.md @@ -0,0 +1,19 @@ +### 11. 开发你的第一个Spring Boot应用 + +这一节描述怎样开发一个简单的"Hello World" web应用,以此强调下Spring Boot的一些关键特性。项目采用Maven进行构建,因为大多数IDE都支持它。 + +**注**:[spring.io](http://spring.io/)网站包含很多Spring Boot"入门"指南,如果你需要特定问题的解决方案,可以先去那瞅瞅。你也可以简化下面的步骤,直接从[start.spring.io](https://start.spring.io/)的依赖搜索器选中`Web` starter,这会生成一个新的项目结构,然后你就可以happy的敲代码了。具体详情参考[文档](https://github.com/spring-io/initializr)。 + +在开始前,你需要打开终端运行以下命令,确保已经安装好了可用的Java和Maven版本: +```shell +$ java -version +java version "1.8.0_102" +Java(TM) SE Runtime Environment (build 1.8.0_102-b14) +Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) +``` +```shell +$ 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 version: 1.8.0_102, vendor: Oracle Corporation +``` +**注**:该示例需要创建单独的文件夹,后续的操作建立在你已创建一个合适的文件夹,并且它是你的当前目录。 diff --git a/II. Getting Started/11.1. Creating the POM.md b/II. Getting Started/11.1. Creating the POM.md new file mode 100644 index 00000000..bc26dc95 --- /dev/null +++ b/II. Getting Started/11.1. Creating the POM.md @@ -0,0 +1,26 @@ +### 11.1. 创建POM + +让我们以创建一个Maven `pom.xml`文件作为开始吧,因为`pom.xml`是构建项目的处方!打开你最喜欢的文本编辑器,并添加以下内容: +```xml + + + 4.0.0 + + com.example + myproject + 0.0.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + + + +``` +这样一个可工作的构建就完成了,你可以通过运行`mvn package`测试它(暂时忽略"jar将是空的-没有包含任何内容!"的警告)。 + +**注**:此刻,你可以将该项目导入到IDE中(大多数现代的Java IDE都包含对Maven的内建支持)。简单起见,我们继续使用普通的文本编辑器完成该示例。 \ No newline at end of file diff --git a/II. Getting Started/11.2. Adding Classpath Dependencies.md b/II. Getting Started/11.2. Adding Classpath Dependencies.md new file mode 100644 index 00000000..06743854 --- /dev/null +++ b/II. Getting Started/11.2. Adding Classpath Dependencies.md @@ -0,0 +1,19 @@ +### 11.2. 添加classpath依赖 + +Spring Boot提供很多"Starters",用来简化添加jars到classpath的操作。示例程序中已经在POM的`parent`节点使用了`spring-boot-starter-parent`,它是一个特殊的starter,提供了有用的Maven默认设置。同时,它也提供一个`dependency-management`节点,这样对于期望(”blessed“)的依赖就可以省略version标记了。 + +其他”Starters“提供开发特定类型应用所需的依赖。由于正在开发web应用,我们添加`spring-boot-starter-web`依赖。在此之前,我们可以运行下面的命令,先看一下目前的依赖: +```shell +$ mvn dependency:tree +[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT +``` +`mvn dependency:tree`命令可以将项目依赖以树形方式展现出来,你可以看到`spring-boot-starter-parent`本身并没有提供依赖。为了添加需要的依赖,编辑你的`pom.xml`,并在`parent`节点下添加`spring-boot-starter-web`依赖: +```xml + + + org.springframework.boot + spring-boot-starter-web + + +``` +如果再次运行`mvn dependency:tree`,你将看到现在多了一些其他依赖,包括Tomcat web服务器和Spring Boot自身。 diff --git a/II. Getting Started/11.3. Writing the Code.md b/II. Getting Started/11.3. Writing the Code.md new file mode 100644 index 00000000..061b09f2 --- /dev/null +++ b/II. Getting Started/11.3. Writing the Code.md @@ -0,0 +1,24 @@ +### 11.3. 编写代码 + +为了完成应用程序,我们需要创建一个单独的Java文件。默认地,Maven会编译`src/main/java`下的源码,所以你需要创建那样的文件结构,然后添加一个名为`src/main/java/Example.java`的文件: +```java +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; +import org.springframework.web.bind.annotation.*; + +@RestController +@EnableAutoConfiguration +public class Example { + + @RequestMapping("/") + String home() { + return "Hello World!"; + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(Example.class, args); + } + +} +``` +尽管代码不多,但已经发生了很多事情。我们在接下来的几节里分步探讨重要的部分。 diff --git a/II. Getting Started/11.3.1. The @RestController and @RequestMapping Annotations.md b/II. Getting Started/11.3.1. The @RestController and @RequestMapping Annotations.md new file mode 100644 index 00000000..687a9726 --- /dev/null +++ b/II. Getting Started/11.3.1. The @RestController and @RequestMapping Annotations.md @@ -0,0 +1,8 @@ + +### 11.3.1. @RestController和@RequestMapping注解 + +Example类上使用的第一个注解是`@RestController`,这被称为构造型(stereotype)注解。它为阅读代码的人提供暗示(这是一个支持REST的控制器),对于Spring,该类扮演了一个特殊角色。在本示例中,我们的类是一个web `@Controller`,所以当web请求进来时,Spring会考虑是否使用它来处理。 + +`@RequestMapping`注解提供路由信息,它告诉Spring任何来自/路径的HTTP请求都应该被映射到`home`方法。`@RestController`注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。 + +**注**:`@RestController`和`@RequestMapping`是Spring MVC中的注解(它们不是Spring Boot的特定部分)。具体参考Spring文档的[MVC章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#mvc)。 diff --git a/II. Getting Started/11.3.2. The @EnableAutoConfiguration Annotation.md b/II. Getting Started/11.3.2. The @EnableAutoConfiguration Annotation.md new file mode 100644 index 00000000..6451ae85 --- /dev/null +++ b/II. Getting Started/11.3.2. The @EnableAutoConfiguration Annotation.md @@ -0,0 +1,5 @@ +### 11.3.2. @EnableAutoConfiguration注解 + +第二个类级别的注解是`@EnableAutoConfiguration`,这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于`spring-boot-starter-web`添加了Tomcat和Spring MVC,所以auto-configuration假定你正在开发一个web应用,并对Spring进行相应地设置。 + +**Starters和Auto-Configuration**:Auto-configuration设计成可以跟"Starters"一起很好的使用,但这两个概念没有直接的联系。你可以自由地挑选starters以外的jar依赖,Spring Boot仍会尽最大努力去自动配置你的应用。 diff --git "a/II. Getting started/11.3.3. The \342\200\234main\342\200\235 method.md" "b/II. Getting Started/11.3.3. The \342\200\234main\342\200\235 Method.md" similarity index 100% rename from "II. Getting started/11.3.3. The \342\200\234main\342\200\235 method.md" rename to "II. Getting Started/11.3.3. The \342\200\234main\342\200\235 Method.md" diff --git a/II. Getting Started/11.4. Running the Example.md b/II. Getting Started/11.4. Running the Example.md new file mode 100644 index 00000000..e8e20a76 --- /dev/null +++ b/II. Getting Started/11.4. Running the Example.md @@ -0,0 +1,23 @@ +### 11.4. 运行示例 + +到此,示例应用可以工作了。由于使用了`spring-boot-starter-parent` POM,这样你就有了一个非常有用的run目标来启动程序。在项目根目录下输入`mvn spring-boot:run`启动应用。你会看到如下的输出: +```shell +$ mvn spring-boot:run + + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v2.0.0.RELEASE) +....... . . . +....... . . . (log output here) +....... . . . +........ Started Example in 2.222 seconds (JVM running for 6.514) +``` +如果使用浏览器打开[localhost:8080](http://localhost:8080),你应该可以看到如下输出: +```shell +Hello World! +``` +点击`ctrl-c`温柔地关闭应用程序。 diff --git a/II. Getting Started/11.5. Creating an Executable Jar.md b/II. Getting Started/11.5. Creating an Executable Jar.md new file mode 100644 index 00000000..4406f4ec --- /dev/null +++ b/II. Getting Started/11.5. Creating an Executable Jar.md @@ -0,0 +1,60 @@ +### 11.5. 创建可执行jar + +我们通过创建一个完全自包含,并可以在生产环境运行的可执行jar来结束示例。可执行jars(有时被称为胖jars "fat jars")是包含编译后的类及代码运行所需依赖jar的存档。 + +**可执行jars和Java**:Java没有提供一个标准方式,用于加载内嵌jar文件(即jar文件中还包含jar文件),这对分发自包含应用来说是个问题。为了解决该问题,很多开发者采用"共享的"jars。共享的jar只是将所有应用依赖的类打包进一个单独的存档,这种方式存在的问题是,很难区分应用程序中使用了哪些库。在多个jars中如果存在相同的文件名(但内容不一样)也会是一个问题。Spring Boot采取一个[不同的方式](../X. Appendices/D. The executable jar format.md),让你真正的直接内嵌jars。 + +为了创建可执行的jar,我们需要将`spring-boot-maven-plugin`添加到`pom.xml`中,在dependencies节点后面插入以下内容: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + + + +``` +**注**:`spring-boot-starter-parent` POM包含绑定到repackage目标的``配置。如果不使用parent POM,你需要自己声明该配置,具体参考[插件文档](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin/usage.html)。 + +保存`pom.xml`,并从命令行运行`mvn package`: +```shell +$ mvn package + +[INFO] Scanning for projects... +[INFO] +[INFO] ------------------------------------------------------------------------ +[INFO] Building myproject 0.0.1-SNAPSHOT +[INFO] ------------------------------------------------------------------------ +[INFO] .... .. +[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject --- +[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar +[INFO] +[INFO] --- spring-boot-maven-plugin:2.0.0.RELEASE:repackage (default) @ myproject --- +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +``` +如果查看target目录,你应该可以看到`myproject-0.0.1-SNAPSHOT.jar`,该文件大概有10MB。想查看内部结构,可以运行`jar tvf`: +```shell +$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar +``` +在该目录下,你应该还能看到一个很小的名为`myproject-0.0.1-SNAPSHOT.jar.original`的文件,这是在Spring Boot重新打包前,Maven创建的原始jar文件。 + +可以使用`java -jar`命令运行该应用程序: +```shell +$ java -jar target/myproject-0.0.1-SNAPSHOT.jar + + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v2.0.0.RELEASE) +....... . . . +....... . . . (log output here) +....... . . . +........ Started Example in 2.536 seconds (JVM running for 2.864) +``` +如前所述,点击`ctrl-c`退出应用。 diff --git a/II. Getting Started/12. What to Read Next.md b/II. Getting Started/12. What to Read Next.md new file mode 100644 index 00000000..5855d166 --- /dev/null +++ b/II. Getting Started/12. What to Read Next.md @@ -0,0 +1,7 @@ +### 12. 接下来阅读什么 + +希望本章节已提供一些Spring Boot的基础部分,并帮你找到开发自己应用的方式。如果你是任务驱动型的开发者,那可以直接跳到[spring.io](http://spring.io/),check out一些[入门指南](http://spring.io/guides/),以解决特定的"使用Spring如何做"的问题;我们也有Spring Boot相关的[How-to](../IX. ‘How-to’ guides/README.md)参考文档。 + +[Spring Boot仓库](http://github.com/spring-projects/spring-boot)有大量可以运行的[示例](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples),这些示例代码是彼此独立的(运行或使用示例的时候不需要构建其他示例)。 + +否则,下一步就是阅读 [III、使用Spring Boot](../III. Using Spring Boot/README.md),如果没耐心,可以跳过该章节,直接阅读 [IV、Spring Boot特性](../IV. Spring Boot features/README.md)。 diff --git a/II. Getting started/8. Introducing Spring Boot.md b/II. Getting Started/8. Introducing Spring Boot.md similarity index 84% rename from II. Getting started/8. Introducing Spring Boot.md rename to II. Getting Started/8. Introducing Spring Boot.md index c4887606..1e336116 100644 --- a/II. Getting started/8. Introducing Spring Boot.md +++ b/II. Getting Started/8. Introducing Spring Boot.md @@ -1,6 +1,6 @@ ### 8. Spring Boot介绍 -Spring Boot简化了基于Spring的应用开发,你只需要"run"就能创建一个独立的,产品级别的Spring应用。 +Spring Boot简化了基于Spring的应用开发。你可以很容易地创建一个独立的,产品级别的Spring应用。 我们为Spring平台及第三方库提供开箱即用的设置,这样你就可以有条不紊地开始。多数Spring Boot应用只需要很少的Spring配置。 你可以使用Spring Boot创建Java应用,并使用`java -jar`启动它或采用传统的war部署方式。我们也提供了一个运行"spring脚本"的命令行工具。 diff --git a/II. Getting Started/9. System Requirements.md b/II. Getting Started/9. System Requirements.md new file mode 100644 index 00000000..d04821b4 --- /dev/null +++ b/II. Getting Started/9. System Requirements.md @@ -0,0 +1,3 @@ +### 9. 系统要求 + +Spring Boot 2.0.0.RELEASE 需要[Java8或者9](http://www.java.com/)环境,Spring框架[5.0.4.RELEASE](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/)或以上版本。明确提供构建支持的有Maven 3.2+和Gradle 4。 \ No newline at end of file diff --git a/II. Getting Started/9.1. Servlet Containers.md b/II. Getting Started/9.1. Servlet Containers.md new file mode 100644 index 00000000..0bfcfad7 --- /dev/null +++ b/II. Getting Started/9.1. Servlet Containers.md @@ -0,0 +1,11 @@ +### 9.1. Servlet容器 + +Spring Boot支持下列内嵌容器: + +|名称|Servlet版本| +|--------|:-------| +|Tomcat 8.5|3.1| +|Jetty 9.4|3.1| +|Undertow 1.4|3.1| + +你也可以将Spring Boot应用部署到任何兼容Servlet 3.0+的容器。 \ No newline at end of file diff --git a/II. Getting Started/README.md b/II. Getting Started/README.md new file mode 100644 index 00000000..870e6582 --- /dev/null +++ b/II. Getting Started/README.md @@ -0,0 +1,3 @@ +### 入门指南 + +如果你想从大体上了解Spring Boot或Spring,本章节正是你所需要的!本节中,我们会回答基本的"what?","how?"和"why?"等问题,简单介绍下Spring Boot,并说明怎么安装。然后我们会构建第一个Spring Boot应用,并讨论一些需要遵循的核心原则。 diff --git a/II. Getting started/10. Installing Spring Boot.md b/II. Getting started/10. Installing Spring Boot.md deleted file mode 100644 index 7cd2f981..00000000 --- a/II. Getting started/10. Installing Spring Boot.md +++ /dev/null @@ -1,7 +0,0 @@ -### 10. Spring Boot安装 - -Spring Boot可以跟经典的Java开发工具(Eclipse,IntelliJ等)一起使用或安装成一个命令行工具。不管怎样,你都需要安装[Java SDK v1.8 ](http://www.java.com/)或更高版本。在开始之前,你需要检查下当前安装的Java版本: -```shell -$ java -version -``` -如果你是一个Java新手,或只是想体验一下Spring Boot,你可能想先尝试[Spring Boot CLI](10.2. Installing the Spring Boot CLI.md),否则继续阅读“经典”地安装指南。 diff --git a/II. Getting started/10.1.1. Maven installation.md b/II. Getting started/10.1.1. Maven installation.md deleted file mode 100644 index 89e6520b..00000000 --- a/II. Getting started/10.1.1. Maven installation.md +++ /dev/null @@ -1,71 +0,0 @@ - -### 10.1.1. Maven安装 - -Spring Boot兼容Apache Maven 3.2或更高版本。如果本地没有安装Maven,你可以参考[maven.apache.org](http://maven.apache.org/)上的指南。 - -**注**:在很多操作系统上,可以通过包管理器来安装Maven。OSX Homebrew用户可以尝试`brew install maven`。Ubuntu用户可以运行`sudo apt-get install maven`。使用Chocolatey的Windows用户可以以管理员身份在命令提示符上运行`choco install maven`。 - -Spring Boot依赖使用的groupId为`org.springframework.boot`。通常,你的Maven POM文件会继承`spring-boot-starter-parent`工程,并声明一个或多个[“Starter POMs”](../III. Using Spring Boot/13.4. Starter POMs.md)依赖。此外,Spring Boot提供了一个可选的[Maven插件](../VIII. Build tool plugins/58. Spring Boot Maven plugin.md),用于创建可执行jars。 - -下面是一个典型的pom.xml文件: -```xml - - - 4.0.0 - - com.example - myproject - 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M5 - - - - - - org.springframework.boot - spring-boot-starter-web - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - - spring-snapshots - http://repo.spring.io/snapshot - true - - - spring-milestones - http://repo.spring.io/milestone - - - - - spring-snapshots - http://repo.spring.io/snapshot - - - spring-milestones - http://repo.spring.io/milestone - - - -``` -**注**:`spring-boot-starter-parent`是使用Spring Boot的一种不错的方式,但它并不总是最合适的。有时你可能需要继承一个不同的父 POM,或只是不喜欢我们的默认配置,那你可以使用import作用域这种替代方案,具体查看[Section 13.2.2, “Using Spring Boot without the parent POM”](../III. Using Spring Boot/13.1.2. Using Spring Boot without the parent POM.md)。 diff --git a/II. Getting started/10.1.2. Gradle installation.md b/II. Getting started/10.1.2. Gradle installation.md deleted file mode 100644 index f43ff5df..00000000 --- a/II. Getting started/10.1.2. Gradle installation.md +++ /dev/null @@ -1,42 +0,0 @@ -### 10.1.2. Gradle安装 - -Spring Boot兼容Gradle 4。如果本地没有安装Gradle,你可以参考[www.gradle.org](http://www.gradle.org/)上的指南。 - -Spring Boot的依赖可通过groupId `org.springframework.boot`来声明。通常,你的项目将声明一个或多个[“Starter POMs”](../III. Using Spring Boot/13.4. Starter POMs.md)依赖。Spring Boot提供了一个很有用的[Gradle插件](../VIII. Build tool plugins/59. Spring Boot Gradle plugin.md),可以用来简化依赖声明,创建可执行jars。 - -**注** 当你需要构建项目时,Gradle Wrapper提供一种给力的获取Gradle的方式。它是一小段脚本和库,跟你的代码一块提交,用于启动构建进程,具体参考[Gradle Wrapper](https://docs.gradle.org/4.0.2/userguide/gradle_wrapper.html)。 - -下面是一个典型的`build.gradle`文件: -```gradle -buildscript { - repositories { - jcenter() - maven { url 'http://repo.spring.io/snapshot' } - maven { url 'http://repo.spring.io/milestone' } - } - dependencies { - classpath('org.springframework.boot:spring-boot-gradle-plugin:2.0.0.M5') - } -} - -apply plugin: 'java' -apply plugin: 'org.springframework.boot' -apply plugin: 'io.spring.dependency-management' - -jar { - baseName = 'myproject' - version = '0.0.1-SNAPSHOT' -} - -repositories { - jcenter() - maven { url "http://repo.spring.io/snapshot" } - maven { url "http://repo.spring.io/milestone" } -} - -dependencies { - compile("org.springframework.boot:spring-boot-starter-web") - testCompile("org.springframework.boot:spring-boot-starter-test") -} - -``` diff --git a/II. Getting started/10.2. Installing the Spring Boot CLI.md b/II. Getting started/10.2. Installing the Spring Boot CLI.md deleted file mode 100644 index 8dafc680..00000000 --- a/II. Getting started/10.2. Installing the Spring Boot CLI.md +++ /dev/null @@ -1,5 +0,0 @@ -### 10.2. Spring Boot CLI安装 - -Spring Boot CLI是一个命令行工具,可用于快速搭建基于Spring的原型。它支持运行[Groovy](http://groovy.codehaus.org/)脚本,这也就意味着你可以使用类似Java的语法,但不用写很多的模板代码。 - -Spring Boot不一定非要配合CLI使用,但它绝对是Spring应用取得进展的最快方式(你咋不飞上天呢?)。 diff --git a/II. Getting started/10.2.1. Manual installation.md b/II. Getting started/10.2.1. Manual installation.md deleted file mode 100644 index b99c487a..00000000 --- a/II. Getting started/10.2.1. Manual installation.md +++ /dev/null @@ -1,10 +0,0 @@ -### 10.2.1. 手动安装 - -Spring CLI分发包可以从Spring软件仓库下载: - -1. [spring-boot-cli-2.0.0.M5-bin.zip](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/2.0.0.M5/spring-boot-cli-2.0.0.M5-bin.zip) -2. [spring-boot-cli-2.0.0.M5-bin.tar.gz](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/2.0.0.M5/spring-boot-cli-2.0.0.M5-bin.tar.gz) - -不稳定的[snapshot分发包](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/)也可以获取到。 - -下载完成后,解压分发包,根据存档里的[INSTALL.txt](http://raw.github.com/spring-projects/spring-boot/master/spring-boot-cli/src/main/content/INSTALL.txt)操作指南进行安装。总的来说,在`.zip`文件的`bin/`目录下会有一个spring脚本(Windows下是`spring.bat`),或使用`java -jar`运行`lib/`目录下的`.jar`文件(该脚本会帮你确保classpath被正确设置)。 diff --git a/II. Getting started/10.2.3. OSX Homebrew installation.md b/II. Getting started/10.2.3. OSX Homebrew installation.md deleted file mode 100644 index bdac8e3a..00000000 --- a/II. Getting started/10.2.3. OSX Homebrew installation.md +++ /dev/null @@ -1,10 +0,0 @@ -### 10.2.3. 使用OSX Homebrew进行安装 - -如果你的环境是Mac,并使用[Homebrew](http://brew.sh/),想要安装Spring Boot CLI只需以下操作: -```shell -$ brew tap pivotal/tap -$ brew install springboot -``` -Homebrew将把spring安装到`/usr/local/bin`下。 - -**注**:如果该方案不可用,可能是因为你的brew版本太老了。你只需执行`brew update`并重试即可。 diff --git a/II. Getting started/10.2.4. MacPorts installation.md b/II. Getting started/10.2.4. MacPorts installation.md deleted file mode 100644 index df019ae7..00000000 --- a/II. Getting started/10.2.4. MacPorts installation.md +++ /dev/null @@ -1,6 +0,0 @@ -### 10.2.4. 使用MacPorts进行安装 - -如果你的环境是Mac,并使用[MacPorts](http://www.macports.org/),想要安装Spring Boot CLI只需以下操作: -```shell -$ sudo port install spring-boot-cli -``` diff --git a/II. Getting started/10.2.6. Quick start Spring CLI example.md b/II. Getting started/10.2.6. Quick start Spring CLI example.md deleted file mode 100644 index e10a158c..00000000 --- a/II. Getting started/10.2.6. Quick start Spring CLI example.md +++ /dev/null @@ -1,24 +0,0 @@ -### 10.2.6. Spring CLI示例快速入门 - -下面是一个相当简单的web应用,你可以用它测试Spring CLI安装是否成功。创建一个名叫`app.groovy`的文件: -```groovy -@RestController -class ThisWillActuallyRun { - - @RequestMapping("/") - String home() { - "Hello World!" - } - -} -``` -然后只需在shell中运行以下命令: -```shell -$ spring run app.groovy -``` -**注**:首次运行该应用将会花费一些时间,因为需要下载依赖,后续运行将会快很多。 - -使用你最喜欢的浏览器打开[localhost:8080](localhost:8080),然后就可以看到如下输出: -```java -Hello World! -``` diff --git a/II. Getting started/10.3. Upgrading from an earlier version of Spring Boot.md b/II. Getting started/10.3. Upgrading from an earlier version of Spring Boot.md deleted file mode 100644 index 558844be..00000000 --- a/II. Getting started/10.3. Upgrading from an earlier version of Spring Boot.md +++ /dev/null @@ -1,5 +0,0 @@ -### 10.3. 版本升级 - -如果你正在升级Spring Boot的早期发布版本,那最好查看下[project wiki](http://github.com/spring-projects/spring-boot/wiki)上的"release notes",你会发现每次发布对应的升级指南和一个"new and noteworthy"特性列表。 - -想要升级一个已安装的CLI,你需要使用合适的包管理命令,例如`brew upgrade`;如果是手动安装CLI,按照[standard instructions](10.2.1. Manual installation.md)操作并记得更新你的PATH环境变量以移除任何老的引用。 diff --git a/II. Getting started/11. Developing your first Spring Boot application.md b/II. Getting started/11. Developing your first Spring Boot application.md deleted file mode 100644 index a60132ea..00000000 --- a/II. Getting started/11. Developing your first Spring Boot application.md +++ /dev/null @@ -1,19 +0,0 @@ -### 11. 开发你的第一个Spring Boot应用 - -我们将使用Java开发一个简单的"Hello World" web应用,以此强调下Spring Boot的一些关键特性。项目采用Maven进行构建,因为大多数IDEs都支持它。 - -**注**:[spring.io](http://spring.io/)网站包含很多Spring Boot"入门"指南,如果你正在找特定问题的解决方案,可以先去那瞅瞅。你也可以简化下面的步骤,直接从[start.spring.io](https://start.spring.io/)的依赖搜索器选中`web` starter,这会自动生成一个新的项目结构,然后你就可以happy的敲代码了。具体详情参考[文档](https://github.com/spring-io/initializr)。 - -在开始前,你需要打开终端检查下安装的Java和Maven版本是否可用: -```shell -$ java -version -java version "1.8.0_102" -Java(TM) SE Runtime Environment (build 1.8.0_102-b14) -Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) -``` -```shell -$ 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 version: 1.8.0_102, vendor: Oracle Corporation -``` -**注**:该示例需要创建单独的文件夹,后续的操作建立在你已创建一个合适的文件夹,并且它是你的“当前目录”。 diff --git a/II. Getting started/11.1. Creating the POM.md b/II. Getting started/11.1. Creating the POM.md deleted file mode 100644 index bc69b414..00000000 --- a/II. Getting started/11.1. Creating the POM.md +++ /dev/null @@ -1,48 +0,0 @@ -### 11.1. 创建POM - -让我们以创建一个Maven `pom.xml`文件作为开始吧,因为`pom.xml`是构建项目的处方!打开你最喜欢的文本编辑器,并添加以下内容: -```xml - - - 4.0.0 - - com.example - myproject - 0.0.1-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M5 - - - - - - - - spring-snapshots - http://repo.spring.io/snapshot - true - - - spring-milestones - http://repo.spring.io/milestone - - - - - spring-snapshots - http://repo.spring.io/snapshot - - - spring-milestones - http://repo.spring.io/milestone - - - -``` -这样一个可工作的构建就完成了,你可以通过运行`mvn package`测试它(暂时忽略"jar将是空的-没有包含任何内容!"的警告)。 - -**注**:此刻,你可以将该项目导入到IDE中(大多数现代的Java IDE都包含对Maven的内建支持)。简单起见,我们将继续使用普通的文本编辑器完成该示例。 diff --git a/II. Getting started/11.2. Adding classpath dependencies.md b/II. Getting started/11.2. Adding classpath dependencies.md deleted file mode 100644 index 6919f826..00000000 --- a/II. Getting started/11.2. Adding classpath dependencies.md +++ /dev/null @@ -1,19 +0,0 @@ -### 11.2. 添加classpath依赖 - -Spring Boot提供很多"Starters",用来简化添加jars到classpath的操作。示例程序中已经在POM的`parent`节点使用了`spring-boot-starter-parent`,它是一个特殊的starter,提供了有用的Maven默认设置。同时,它也提供一个`dependency-management`节点,这样对于期望(”blessed“)的依赖就可以省略version标记了。 - -其他”Starters“只简单提供开发特定类型应用所需的依赖。由于正在开发web应用,我们将添加`spring-boot-starter-web`依赖-但在此之前,让我们先看下目前的依赖: -```shell -$ mvn dependency:tree -[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT -``` -`mvn dependency:tree`命令可以将项目依赖以树形方式展现出来,你可以看到`spring-boot-starter-parent`本身并没有提供依赖。编辑`pom.xml`,并在`parent`节点下添加`spring-boot-starter-web`依赖: -```xml - - - org.springframework.boot - spring-boot-starter-web - - -``` -如果再次运行`mvn dependency:tree`,你将看到现在多了一些其他依赖,包括Tomcat web服务器和Spring Boot自身。 diff --git a/II. Getting started/11.3. Writing the code.md b/II. Getting started/11.3. Writing the code.md deleted file mode 100644 index 3bfa38a6..00000000 --- a/II. Getting started/11.3. Writing the code.md +++ /dev/null @@ -1,25 +0,0 @@ -### 11.3. 编写代码 - -为了完成应用程序,我们需要创建一个单独的Java文件。Maven默认会编译`src/main/java`下的源码,所以你需要创建那样的文件结构,并添加一个名为`src/main/java/Example.java`的文件: -```java -import org.springframework.boot.*; -import org.springframework.boot.autoconfigure.*; -import org.springframework.stereotype.*; -import org.springframework.web.bind.annotation.*; - -@RestController -@EnableAutoConfiguration -public class Example { - - @RequestMapping("/") - String home() { - return "Hello World!"; - } - - public static void main(String[] args) throws Exception { - SpringApplication.run(Example.class, args); - } - -} -``` -尽管代码不多,但已经发生了很多事情,让我们分步探讨重要的部分吧! diff --git a/II. Getting started/11.3.1. The @RestController and @RequestMapping annotations.md b/II. Getting started/11.3.1. The @RestController and @RequestMapping annotations.md deleted file mode 100644 index 86e4cc07..00000000 --- a/II. Getting started/11.3.1. The @RestController and @RequestMapping annotations.md +++ /dev/null @@ -1,8 +0,0 @@ - -### 11.3.1. @RestController和@RequestMapping注解 - -Example类上使用的第一个注解是`@RestController`,这被称为构造型(stereotype)注解。它为阅读代码的人提供暗示(这是一个支持REST的控制器),对于Spring,该类扮演了一个特殊角色。在本示例中,我们的类是一个web `@Controller`,所以当web请求进来时,Spring会考虑是否使用它来处理。 - -`@RequestMapping`注解提供路由信息,它告诉Spring任何来自"/"路径的HTTP请求都应该被映射到`home`方法。`@RestController`注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。 - -**注**:`@RestController`和`@RequestMapping`是Spring MVC中的注解(它们不是Spring Boot的特定部分),具体参考Spring文档的[MVC章节](http://mvc.linesh.tw)。 diff --git a/II. Getting started/11.3.2. The @EnableAutoConfiguration annotation.md b/II. Getting started/11.3.2. The @EnableAutoConfiguration annotation.md deleted file mode 100644 index 4e2f0ec5..00000000 --- a/II. Getting started/11.3.2. The @EnableAutoConfiguration annotation.md +++ /dev/null @@ -1,5 +0,0 @@ -### 11.3.2. @EnableAutoConfiguration注解 - -第二个类级别的注解是`@EnableAutoConfiguration`,这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于`spring-boot-starter-web`添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用,并对Spring进行相应地设置。 - -**Starters和Auto-Configuration**:Auto-configuration设计成可以跟"Starters"一起很好的使用,但这两个概念没有直接的联系。你可以自由地挑选starters以外的jar依赖,Spring Boot仍会尽最大努力去自动配置你的应用。 diff --git a/II. Getting started/11.4. Running the example.md b/II. Getting started/11.4. Running the example.md deleted file mode 100644 index 274abedd..00000000 --- a/II. Getting started/11.4. Running the example.md +++ /dev/null @@ -1,23 +0,0 @@ -### 11.4. 运行示例 - -到此,示例应用可以工作了。由于使用了`spring-boot-starter-parent` POM,这样我们就有了一个非常有用的run目标来启动程序。在项目根目录下输入`mvn spring-boot:run`启动应用: -```shell -$ mvn spring-boot:run - - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ -( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v2.0.0.M5) -....... . . . -....... . . . (log output here) -....... . . . -........ Started Example in 2.222 seconds (JVM running for 6.514) -``` -如果使用浏览器打开[localhost:8080](http://localhost:8080),你应该可以看到如下输出: -```shell -Hello World! -``` -点击`ctrl-c`温雅地关闭应用程序。 diff --git a/II. Getting started/11.5. Creating an executable jar.md b/II. Getting started/11.5. Creating an executable jar.md deleted file mode 100644 index 54facb2e..00000000 --- a/II. Getting started/11.5. Creating an executable jar.md +++ /dev/null @@ -1,60 +0,0 @@ -### 11.5. 创建可执行jar - -让我们通过创建一个完全自包含,并可以在生产环境运行的可执行jar来结束示例吧!可执行jars(有时被称为胖jars "fat jars")是包含编译后的类及代码运行所需依赖jar的存档。 - -**可执行jars和Java**:Java没有提供任何标准方式,用于加载内嵌jar文件(即jar文件中还包含jar文件),这对分发自包含应用来说是个问题。为了解决该问题,很多开发者采用"共享的"jars。共享的jar只是简单地将所有jars的类打包进一个单独的存档,这种方式存在的问题是,很难区分应用程序中使用了哪些库。在多个jars中如果存在相同的文件名(但内容不一样)也会是一个问题。Spring Boot采取一个[不同的方式](../X. Appendices/D. The executable jar format.md),允许你真正的直接内嵌jars。 - -为了创建可执行的jar,我们需要将`spring-boot-maven-plugin`添加到`pom.xml`中,在dependencies节点后面插入以下内容: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - - -``` -**注**:`spring-boot-starter-parent` POM包含绑定到repackage目标的``配置。如果不使用parent POM,你需要自己声明该配置,具体参考[插件文档](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin/usage.html)。 - -保存`pom.xml`,并从命令行运行`mvn package`: -```shell -$ mvn package - -[INFO] Scanning for projects... -[INFO] -[INFO] ------------------------------------------------------------------------ -[INFO] Building myproject 0.0.1-SNAPSHOT -[INFO] ------------------------------------------------------------------------ -[INFO] .... .. -[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject --- -[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar -[INFO] -[INFO] --- spring-boot-maven-plugin:2.0.0.M5:repackage (default) @ myproject --- -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -``` -如果查看target目录,你应该可以看到`myproject-0.0.1-SNAPSHOT.jar`,该文件大概有10MB。想查看内部结构,可以运行`jar tvf`: -```shell -$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar -``` -在该目录下,你应该还能看到一个很小的名为`myproject-0.0.1-SNAPSHOT.jar.original`的文件,这是在Spring Boot重新打包前,Maven创建的原始jar文件。 - -可以使用`java -jar`命令运行该应用程序: -```shell -$ java -jar target/myproject-0.0.1-SNAPSHOT.jar - - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ -( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v2.0.0.M5) -....... . . . -....... . . . (log output here) -....... . . . -........ Started Example in 2.536 seconds (JVM running for 2.864) -``` -如上所述,点击`ctrl-c`可以温雅地退出应用。 diff --git a/II. Getting started/12. What to read next.md b/II. Getting started/12. What to read next.md deleted file mode 100644 index bdd34414..00000000 --- a/II. Getting started/12. What to read next.md +++ /dev/null @@ -1,7 +0,0 @@ -### 12. 接下来阅读什么 - -希望本章节已为你提供一些Spring Boot的基础部分,并帮你找到开发自己应用的方式。如果你是任务驱动型的开发者,那可以直接跳到[spring.io](http://spring.io/),check out一些[入门指南](http://spring.io/guides/),以解决特定的"使用Spring如何做"的问题;我们也有Spring Boot相关的[How-to](../IX. ‘How-to’ guides/README.md)参考文档。 - -[Spring Boot仓库](http://github.com/spring-projects/spring-boot)有大量可以运行的[示例](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples),这些示例代码是彼此独立的(运行或使用示例的时候不需要构建其他示例)。 - -否则,下一步就是阅读 [III、使用Spring Boot](../III. Using Spring Boot/README.md),如果没耐心,可以跳过该章节,直接阅读 [IV、Spring Boot特性](../IV. Spring Boot features/README.md)。 diff --git a/II. Getting started/9. System Requirements.md b/II. Getting started/9. System Requirements.md deleted file mode 100644 index f6b6bef9..00000000 --- a/II. Getting started/9. System Requirements.md +++ /dev/null @@ -1,3 +0,0 @@ -### 9. 系统要求 - -Spring Boot 2.0.0.M5 需要[Java8](http://www.java.com/)环境,Spring框架5.0.0.RELEASE或以上版本。明确提供构建支持的有Maven(3.2+)和Gradle 4。 \ No newline at end of file diff --git a/II. Getting started/9.1. Servlet containers.md b/II. Getting started/9.1. Servlet containers.md deleted file mode 100644 index 3688e13c..00000000 --- a/II. Getting started/9.1. Servlet containers.md +++ /dev/null @@ -1,11 +0,0 @@ -### 9.1. Servlet容器 - -下列内嵌容器支持开箱即用(out of the box): - -|名称|Servlet版本| -|--------|:-------| -|Tomcat 8.5|3.1| -|Jetty 9.4|3.1| -|Undertow 1.3|3.1| - -你也可以将Spring Boot应用部署到任何兼容Servlet 3.0+的容器。 diff --git a/II. Getting started/README.md b/II. Getting started/README.md deleted file mode 100644 index 5ea4ed27..00000000 --- a/II. Getting started/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### 入门指南 - -如果你想从大体上了解Spring Boot或Spring,本章节正是你所需要的!本节中,我们会回答基本的"what?","how?"和"why?"等问题,并通过一些安装指南简单介绍下Spring Boot。然后我们会构建第一个Spring Boot应用,并讨论一些需要遵循的核心原则。 diff --git a/III. Using Spring Boot/13. Build Systems.md b/III. Using Spring Boot/13. Build Systems.md new file mode 100644 index 00000000..5c2c2184 --- /dev/null +++ b/III. Using Spring Boot/13. Build Systems.md @@ -0,0 +1,3 @@ +### 13. 构建系统 + +强烈建议你选择一个支持依赖管理,能消费发布到"Maven中央仓库"的artifacts的构建系统,比如Maven或Gradle。使用其他构建系统也是可以的,比如Ant,但它们得不到特别好的支持。 diff --git a/III. Using Spring Boot/13. Build systems.md b/III. Using Spring Boot/13. Build systems.md deleted file mode 100644 index b6a7cfa0..00000000 --- a/III. Using Spring Boot/13. Build systems.md +++ /dev/null @@ -1,3 +0,0 @@ -### 13. 构建系统 - -强烈建议你选择一个支持依赖管理,能消费发布到"Maven中央仓库"的artifacts的构建系统,比如Maven或Gradle。使用其他构建系统也是可以的,比如Ant,但它们可能得不到很好的支持。 diff --git a/III. Using Spring Boot/13.1. Dependency Management.md b/III. Using Spring Boot/13.1. Dependency Management.md new file mode 100644 index 00000000..e720b69f --- /dev/null +++ b/III. Using Spring Boot/13.1. Dependency Management.md @@ -0,0 +1,9 @@ +### 13.1. 依赖管理 + +Spring Boot每次发布时都会提供一个它所支持的精选依赖列表。实际上,在构建配置里你不需要提供任何依赖的版本,因为Spring Boot已经替你管理好了。当更新Spring Boot时,那些依赖也会一起更新。 + +**注** 如果有必要,你可以指定依赖的版本来覆盖Spring Boot默认版本。 + +精选列表包括所有能够跟Spring Boot一起使用的Spring模块及第三方库,该列表支持[Maven](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-maven-parent-pom)和[Gradle](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-gradle-dependency-management),可以作为一份标准的[材料清单(spring-boot-dependencies)](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-maven-without-a-parent)。 + +**注** Spring Boot每次发布都关联一个Spring框架的基础版本。强烈建议你不要自己指定Spring版本。 diff --git a/III. Using Spring Boot/13.1. Dependency management.md b/III. Using Spring Boot/13.1. Dependency management.md deleted file mode 100644 index ce75a35d..00000000 --- a/III. Using Spring Boot/13.1. Dependency management.md +++ /dev/null @@ -1,9 +0,0 @@ -### 13.1. 依赖管理 - -Spring Boot每次发布时都会提供一个它所支持的精选依赖列表。实际上,在构建配置里你不需要提供任何依赖的版本,因为Spring Boot已经替你管理好了。当更新Spring Boot时,那些依赖也会一起更新。 - -**注** 如果有必要,你可以指定依赖的版本来覆盖Spring Boot默认版本。 - -精选列表包括所有能够跟Spring Boot一起使用的Spring模块及第三方库,该列表支持[Maven](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-maven-parent-pom)和[Gradle](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-gradle-dependency-management),可以作为一份标准的[材料清单(spring-boot-dependencies)](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-maven-without-a-parent)。 - -**注** Spring Boot每次发布都关联一个Spring框架的基础版本,所以强烈建议你不要自己指定Spring版本。 diff --git a/III. Using Spring Boot/13.2. Maven.md b/III. Using Spring Boot/13.2. Maven.md index 5c98c2b4..f2ebaead 100644 --- a/III. Using Spring Boot/13.2. Maven.md +++ b/III. Using Spring Boot/13.2. Maven.md @@ -3,9 +3,9 @@ Maven用户可以继承`spring-boot-starter-parent`项目来获取合适的默认设置。该parent项目提供以下特性: - 默认编译级别为Java 1.8 - 源码编码为UTF-8 -- 一个[Dependency management](./13.1. Dependency management.md)节点,允许你省略常见依赖的``标签,继承自`spring-boot-dependencies` POM。 +- 一个[Dependency management](./13.1. Dependency management.md)节选,管理着常见依赖的版本。允许你省略常见依赖的``标签,继承自`spring-boot-dependencies` POM。 - 恰到好处的[资源过滤](https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html) - 恰到好处的插件配置([exec插件](http://mojo.codehaus.org/exec-maven-plugin/),[Git commit ID](https://github.com/ktoso/maven-git-commit-id-plugin),[shade](http://maven.apache.org/plugins/maven-shade-plugin/)) -- 恰到好处的对`application.properties`和`application.yml`进行筛选,包括特定profile(profile-specific)的文件,比如`application-foo.properties`和`application-foo.yml` +- 恰到好处的对`application.properties`和`application.yml`进行筛选,包括特定profile(profile-specific)的文件,比如`application-dev.properties`和`application-dev.yml` -最后一点:由于配置文件默认接收Spring风格的占位符(`${...}`),所以Maven filtering需改用`@..@`占位符(你可以使用Maven属性`resource.delimiter`来覆盖它)。 +最后一点:由于`application.properties`和`application.yml`接收Spring风格的占位符(`${...}`),所以Maven filtering需改用`@..@`占位符(你可以通过设置Maven属性`resource.delimiter`来覆盖它)。 diff --git a/III. Using Spring Boot/13.2.1. Inheriting the Starter Parent.md b/III. Using Spring Boot/13.2.1. Inheriting the Starter Parent.md new file mode 100644 index 00000000..f70262ad --- /dev/null +++ b/III. Using Spring Boot/13.2.1. Inheriting the Starter Parent.md @@ -0,0 +1,21 @@ +### 13.2.1. 继承starter parent + +如果你想配置项目,让其继承自`spring-boot-starter-parent`,只需将`parent`按如下设置: +```xml + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + +``` +**注**:你应该只需在该依赖上指定Spring Boot版本,如果导入其他的starters,放心的省略版本号好了。 + +按照以上设置,你可以在自己的项目中通过覆盖属性来覆盖个别的依赖。例如,你可以将以下设置添加到`pom.xml`中来升级Spring Data到另一个发布版本。 +```xml + + Fowler-SR2 + +``` + +**注** 查看[spring-boot-dependencies pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-dependencies/pom.xml)获取支持的属性列表。 diff --git a/III. Using Spring Boot/13.2.1. Inheriting the starter parent.md b/III. Using Spring Boot/13.2.1. Inheriting the starter parent.md deleted file mode 100644 index 36aec075..00000000 --- a/III. Using Spring Boot/13.2.1. Inheriting the starter parent.md +++ /dev/null @@ -1,21 +0,0 @@ -### 13.2.1. 继承starter parent - -如果你想配置项目,让其继承自`spring-boot-starter-parent`,只需将`parent`按如下设置: -```xml - - - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M5 - -``` -**注**:你应该只需在该依赖上指定Spring Boot版本,如果导入其他的starters,放心的省略版本号好了。 - -按照以上设置,你可以在自己的项目中通过覆盖属性来覆盖个别的依赖。例如,你可以将以下设置添加到`pom.xml`中来升级Spring Data到另一个发布版本。 -```xml - - Fowler-SR2 - -``` - -**注** 查看[spring-boot-dependencies pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-dependencies/pom.xml)获取支持的属性列表。 diff --git a/III. Using Spring Boot/13.2.2. Using Spring Boot without the Parent POM.md b/III. Using Spring Boot/13.2.2. Using Spring Boot without the Parent POM.md new file mode 100644 index 00000000..db20b7b5 --- /dev/null +++ b/III. Using Spring Boot/13.2.2. Using Spring Boot without the Parent POM.md @@ -0,0 +1,43 @@ +### 13.2.2. 在不使用parent POM的情况下玩转Spring Boot + +不是每个人都喜欢继承`spring-boot-starter-parent` POM,比如你可能需要使用公司的标准parent,或倾向于显式声明所有的Maven配置。 + +如果你不想使用`spring-boot-starter-parent`,通过设置`scope=import`的依赖,你仍能获取到依赖管理的好处: +```xml + + + + + org.springframework.boot + spring-boot-dependencies + 2.0.0.RELEASE + pom + import + + + +``` + +以上设置不允许你使用属性覆盖个别依赖,为了达到这个目的,你需要在项目的`dependencyManagement`节点中,在`spring-boot-dependencies`实体前插入一个节点。例如,为了将Spring Data升级到另一个发布版本,你需要将以下配置添加到`pom.xml`中: +```xml + + + + + org.springframework.data + spring-data-releasetrain + Fowler-SR2 + import + pom + + + org.springframework.boot + spring-boot-dependencies + 2.0.0.RELEASE + pom + import + + + +``` +**注** 示例中,我们指定了一个材料清单,但任何的依赖类型都可以通过这种方式覆盖。 diff --git a/III. Using Spring Boot/13.2.2. Using Spring Boot without the parent POM.md b/III. Using Spring Boot/13.2.2. Using Spring Boot without the parent POM.md deleted file mode 100644 index 89fe9873..00000000 --- a/III. Using Spring Boot/13.2.2. Using Spring Boot without the parent POM.md +++ /dev/null @@ -1,43 +0,0 @@ -### 13.2.2. 在不使用parent POM的情况下玩转Spring Boot - -不是每个人都喜欢继承`spring-boot-starter-parent` POM,比如你可能需要使用公司的标准parent,或只是倾向于显式声明所有的Maven配置。 - -如果你不想使用`spring-boot-starter-parent`,通过设置`scope=import`的依赖,你仍能获取到依赖管理的好处: -```xml - - - - - org.springframework.boot - spring-boot-dependencies - 2.0.0.M5 - pom - import - - - -``` - -以上设置不允许你使用属性覆盖个别依赖,为了达到这个目的,你需要在项目的`dependencyManagement`节点中,在`spring-boot-dependencies`实体前插入一个节点。例如,为了将Spring Data升级到另一个发布版本,你需要将以下配置添加到`pom.xml`中: -```xml - - - - - org.springframework.data - spring-data-releasetrain - Fowler-SR2 - import - pom - - - org.springframework.boot - spring-boot-dependencies - 2.0.0.M5 - pom - import - - - -``` -**注** 示例中,我们指定了一个BOM,但任何的依赖类型都可以通过这种方式覆盖。 diff --git a/III. Using Spring Boot/13.2.3. Using the Spring Boot Maven plugin.md b/III. Using Spring Boot/13.2.3. Using the Spring Boot Maven Plugin.md similarity index 100% rename from III. Using Spring Boot/13.2.3. Using the Spring Boot Maven plugin.md rename to III. Using Spring Boot/13.2.3. Using the Spring Boot Maven Plugin.md diff --git a/III. Using Spring Boot/13.3. Gradle.md b/III. Using Spring Boot/13.3. Gradle.md index 25de92cf..b47a24f1 100644 --- a/III. Using Spring Boot/13.3. Gradle.md +++ b/III. Using Spring Boot/13.3. Gradle.md @@ -2,5 +2,5 @@ 想要学习用Gradle配置Spring Boot,请参考Spring Boot的Gradle插件的文档。 - - Reference ( [HTML](http://docs.spring.io/spring-boot/docs/2.0.0.M3/gradle-plugin//reference/html) and [PDF](http://docs.spring.io/spring-boot/docs/2.0.0.M3/gradle-plugin//reference/pdf/spring-boot-gradle-plugin-reference.pdf) ) - - [API](http://docs.spring.io/spring-boot/docs/2.0.0.M3/gradle-plugin//api) \ No newline at end of file + - 参考([HTML](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/gradle-plugin/reference/html) 与 [PDF](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/gradle-plugin/reference/pdf/spring-boot-gradle-plugin-reference.pdf)) + - [API](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/gradle-plugin/api) diff --git a/III. Using Spring Boot/13.4. Ant.md b/III. Using Spring Boot/13.4. Ant.md index 747e725c..fa538582 100644 --- a/III. Using Spring Boot/13.4. Ant.md +++ b/III. Using Spring Boot/13.4. Ant.md @@ -21,7 +21,7 @@ xmlns:spring-boot="antlib:org.springframework.boot.ant" name="myapp" default="build"> - + @@ -51,4 +51,4 @@ ``` -**注** 如果你不想使用`spring-boot-antlib`模块,那查看[章节 85.9,使用Ant构建可执行存档(不使用spring-boot-antlib)](../IX. ‘How-to’ guides/85.9 Build an executable archive from Ant without using spring-boot-antlib.md)获取更多指导。 +**注** 如果你不想使用`spring-boot-antlib`模块,那查看[章节 86.9,使用Ant构建可执行存档(不使用spring-boot-antlib)](../IX. ‘How-to’ guides/86.9 Build an Executable Archive from Ant without Using spring-boot-antlib.md)获取更多指导。 \ No newline at end of file diff --git a/III. Using Spring Boot/13.5. Starters.md b/III. Using Spring Boot/13.5. Starters.md index f19714ed..eb350159 100644 --- a/III. Using Spring Boot/13.5. Starters.md +++ b/III. Using Spring Boot/13.5. Starters.md @@ -1,10 +1,11 @@ ### 13.5. Starters -Starters是一个依赖描述符的集合,你可以将它包含进项目中,这样添加依赖就非常方便。你可以获取所有Spring及相关技术的一站式服务,而不需要翻阅示例代码,拷贝粘贴大量的依赖描述符。例如,如果你想使用Spring和JPA进行数据库访问,只需要在项目中包含`spring-boot-starter-data-jpa`依赖,然后你就可以开始了。 +Starters是一个依赖描述符的集合,你可以将它包含进项目中,这样添加依赖就非常方便。你可以获取所有Spring及相关技术的一站式服务,而不需要翻阅示例代码,拷贝粘贴大量的依赖描述符。例如,如果你想使用Spring和JPA进行数据库访问,需要在项目中包含`spring-boot-starter-data-jpa`依赖。 该starters包含很多搭建,快速运行项目所需的依赖,并提供一致的,可管理传递性的依赖集。 -**名字有什么含义**:所有官方starters遵循相似的命名模式:`spring-boot-starter-*`,在这里`*`是一种特殊的应用程序类型。该命名结构旨在帮你找到需要的starter。很多集成于IDEs中的Maven插件允许你通过名称name搜索依赖。例如,使用相应的Eclipse或STS插件,你可以简单地在POM编辑器中点击`ctrl-space`,然后输入"spring-boot-starter"就可以获取一个完整列表。正如[Creating your own starter](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-custom-starter)章节中讨论的,第三方starters不应该以`spring-boot`开头,因为它跟Spring Boot官方artifacts冲突。一个acme的第三方starter通常命名为`acme-spring-boot-starter`。 +**名字有什么含义**:所有官方starters遵循相似的命名模式:`spring-boot-starter-*`,在这里`*`是一种特殊的应用程序类型。该命名结构旨在帮你找到需要的starter。很多集成于IDEs中的Maven插件让你通过名称搜索依赖。例如,使用相应的Eclipse或STS插件,你可以在POM编辑器中点击`ctrl-space`,然后输入"spring-boot-starter"就可以获取一个完整列表。 +正如[创建自己的starter](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-custom-starter)章节中讨论的,第三方starters不应该以`spring-boot`开头,因为它跟Spring Boot官方artifacts冲突。第三方starter通常会用项目的名称开头。例如,一个叫做`thirdpartyproject`的第三方starter项目,通常会被命名为`thirdpartyproject-spring-boot-starter`。 以下应用程序starters是Spring Boot在`org.springframework.boot` group下提供的: @@ -12,53 +13,51 @@ Starters是一个依赖描述符的集合,你可以将它包含进项目中, |名称|描述|Pom| |------|:-----|:-----| -|spring-boot-starter|核心starter,包括自动配置支持,日志和YAML|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter/pom.xml)| -|spring-boot-starter-activemq|用于使用Apache ActiveMQ实现JMS消息|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-activemq/pom.xml)| -|spring-boot-starter-amqp|用于使用Spring AMQP和Rabbit MQ|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-amqp/pom.xml)| -|spring-boot-starter-aop|用于使用Spring AOP和AspectJ实现面向切面编程|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-aop/pom.xml)| -|spring-boot-starter-artemis|使用Apache Artemis实现JMS消息|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-artemis/pom.xml)| -|spring-boot-starter-batch|对Spring Batch的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-batch/pom.xml)| -|spring-boot-starter-cache|用于使用Spring框架的缓存支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-cache/pom.xml)| -|spring-boot-starter-cloud-connectors|对Spring Cloud Connectors的支持,用于简化云平台下(例如Cloud Foundry 和Heroku)服务的连接|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-cloud-connectors/pom.xml)| -|spring-boot-starter-data-cassandra|用于使用分布式数据库Cassandra和Spring Data Cassandra|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-cassandra/pom.xml)| -|spring-boot-starter-data-cassandra-reactive|用于使用分布式数据库Cassandra和Spring Data Cassandra Reactive|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-cassandra-reactive/pom.xml)| -|spring-boot-starter-data-couchbase|用于使用基于文档的数据库Couchbase和Spring Data Couchbase|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-couchbase/pom.xml)| -|spring-boot-starter-data-elasticsearch|用于使用Elasticsearch搜索,分析引擎和Spring Data Elasticsearch|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-elasticsearch/pom.xml)| -|spring-boot-starter-data-jpa|用于使用Hibernate实现Spring Data JPA|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-jpa/pom.xml)| -|spring-boot-starter-data-ldap|用于Spring Data LDAP|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-ldap/pom.xml)| -|spring-boot-starter-data-mongodb|用于使用基于文档的数据库MongoDB和Spring Data MongoDB|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-mongodb/pom.xml)| -|spring-boot-starter-data-mongodb-reactive|用于使用基于文档的数据库MongoDB和Spring Data MongoDB Reactive|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-mongodb-reactive/pom.xml)| -|spring-boot-starter-data-neo4j|用于使用图数据库Neo4j和Spring Data Neo4j|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-neo4j/pom.xml)| -|spring-boot-starter-data-redis|用于使用Spring Data Redis和Lettuce客户端操作键-值存储的Redis|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-redis/pom.xml)| -|spring-boot-starter-data-rest|用于使用Spring Data REST暴露基于REST的Spring Data仓库|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-rest/pom.xml)| -|spring-boot-starter-data-solr|通过Spring Data Solr使用Apache Solr搜索平台|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-data-solr/pom.xml)| -|spring-boot-starter-freemarker|用于使用FreeMarker模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-freemarker/pom.xml)| -|spring-boot-starter-groovy-templates|用于使用Groovy模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-groovy-templates/pom.xml)| -|spring-boot-starter-hateoas|用于使用Spring MVC和Spring HATEOAS实现基于超媒体的RESTful web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-hateoas/pom.xml)| -|spring-boot-starter-integration|用于使用Spring Integration|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-integration/pom.xml)| -|spring-boot-starter-jdbc|对JDBC的支持(使用Tomcat JDBC连接池)|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-jdbc/pom.xml)| -|spring-boot-starter-jersey|用于使用JAX-RS和Jersey构建RESTful web应用,可使用[spring-boot-starter-web](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#spring-boot-starter-web)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-jersey/pom.xml)| -|spring-boot-starter-jooq|用于使用JOOQ访问SQL数据库,可使用[spring-boot-starter-data-jpa](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#spring-boot-starter-data-jpa)或[spring-boot-starter-jdbc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#spring-boot-starter-jdbc)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-jooq/pom.xml)| -|spring-boot-starter-json|用于读写json|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-json/pom.xmll)| -|spring-boot-starter-jta-atomikos|用于使用Atomikos实现JTA事务|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-atomikos/pom.xml)| -|spring-boot-starter-jta-bitronix|用于使用Bitronix实现JTA事务|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-bitronix/pom.xml)| -|spring-boot-starter-jta-narayana|Spring Boot Narayana JTA Starter|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-narayana/pom.xml)| -|spring-boot-starter-mail|用于使用Java Mail和Spring框架email发送支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-mail/pom.xml)| -|spring-boot-starter-mobile|用于使用Spring Mobile开发web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-mobile/pom.xml)| -|spring-boot-starter-mustache|用于使用Mustache模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-mustache/pom.xml)| -|spring-boot-starter-quartz|Spring Boot Quartz Starter|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-quartz/pom.xml)| -|spring-boot-starter-security|对Spring Security的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-security/pom.xml)| -|spring-boot-starter-security-reactive|对响应式Spring Security的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-security-reactive/pom.xml)| -|spring-boot-starter-social-facebook|用于使用Spring Social Facebook|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-social-facebook/pom.xml)| -|spring-boot-starter-social-linkedin|用于使用Spring Social LinkedIn|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-social-linkedin/pom.xml)| -|spring-boot-starter-social-twitter|对使用Spring Social Twitter的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-social-twitter/pom.xml)| -|spring-boot-starter-test|用于测试Spring Boot应用,支持常用测试类库,包括JUnit, Hamcrest和Mockito|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-test/pom.xml)| -|spring-boot-starter-thymeleaf|用于使用Thymeleaf模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-thymeleaf/pom.xml)| -|spring-boot-starter-validation|用于使用Hibernate Validator实现Java Bean校验|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-validation/pom.xml)| -|spring-boot-starter-web|用于使用Spring MVC构建web应用,包括RESTful。Tomcat是默认的内嵌容器|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-web/pom.xml)| -|spring-boot-starter-web-services|对Spring Web服务的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-web-services/pom.xml)| -|spring-boot-starter-webflux|提供用Spring框架创建webflux应用的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-webflux/pom.xml)| -|spring-boot-starter-websocket|用于使用Spring框架的WebSocket支持构建WebSocket应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-websocket/pom.xml)| +|spring-boot-starter|核心starter,包括自动配置支持,日志和YAML|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter/pom.xml)| +|spring-boot-starter-activemq|用于使用Apache ActiveMQ实现JMS消息|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-activemq/pom.xml)| +|spring-boot-starter-amqp|用于使用Spring AMQP和Rabbit MQ|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-amqp/pom.xml)| +|spring-boot-starter-aop|用于使用Spring AOP和AspectJ实现面向切面编程|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-aop/pom.xml)| +|spring-boot-starter-artemis|使用Apache Artemis实现JMS消息|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-artemis/pom.xml)| +|spring-boot-starter-batch|对Spring Batch的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-batch/pom.xml)| +|spring-boot-starter-cache|用于使用Spring框架的缓存支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-cache/pom.xml)| +|spring-boot-starter-cloud-connectors|对Spring Cloud Connectors的支持,用于简化云平台下(例如Cloud Foundry 和Heroku)服务的连接|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-cloud-connectors/pom.xml)| +|spring-boot-starter-data-cassandra|用于使用分布式数据库Cassandra和Spring Data Cassandra|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-cassandra/pom.xml)| +|spring-boot-starter-data-cassandra-reactive|用于使用分布式数据库Cassandra和Spring Data Cassandra Reactive|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-cassandra-reactive/pom.xml)| +|spring-boot-starter-data-couchbase|用于使用基于文档的数据库Couchbase和Spring Data Couchbase|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-couchbase/pom.xml)| +|spring-boot-starter-data-couchbase-reactive|用于使用基于文档的数据库Couchbase和Spring Data Couchbase Reactive|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-couchbase-reactive/pom.xml)| +|spring-boot-starter-data-elasticsearch|用于使用Elasticsearch搜索,分析引擎和Spring Data Elasticsearch|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-elasticsearch/pom.xml)| +|spring-boot-starter-data-jpa|用于使用Hibernate实现Spring Data JPA|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-jpa/pom.xml)| +|spring-boot-starter-data-ldap|用于Spring Data LDAP|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-ldap/pom.xml)| +|spring-boot-starter-data-mongodb|用于使用基于文档的数据库MongoDB和Spring Data MongoDB|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-mongodb/pom.xml)| +|spring-boot-starter-data-mongodb-reactive|用于使用基于文档的数据库MongoDB和Spring Data MongoDB Reactive|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-mongodb-reactive/pom.xml)| +|spring-boot-starter-data-neo4j|用于使用图数据库Neo4j和Spring Data Neo4j|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-neo4j/pom.xml)| +|spring-boot-starter-data-redis|用于使用Spring Data Redis和Lettuce客户端操作键-值存储的Redis|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-redis/pom.xml)| +|spring-boot-starter-data-redis-reactive|用于使用Spring Data Redis reactive和Lettuce客户端操作键-值存储的Redis|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-redis-reactive/pom.xml)| +|spring-boot-starter-data-rest|用于使用Spring Data REST暴露基于REST的Spring Data仓库|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-rest/pom.xml)| +|spring-boot-starter-data-solr|通过Spring Data Solr使用Apache Solr搜索平台|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-data-solr/pom.xml)| +|spring-boot-starter-freemarker|用于使用FreeMarker模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-freemarker/pom.xml)| +|spring-boot-starter-groovy-templates|用于使用Groovy模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-groovy-templates/pom.xml)| +|spring-boot-starter-hateoas|用于使用Spring MVC和Spring HATEOAS实现基于超媒体的RESTful web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-hateoas/pom.xml)| +|spring-boot-starter-integration|用于使用Spring Integration|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-integration/pom.xml)| +|spring-boot-starter-jdbc|对JDBC的支持(使用Tomcat JDBC连接池)|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-jdbc/pom.xml)| +|spring-boot-starter-jersey|用于使用JAX-RS和Jersey构建RESTful web应用,可使用[spring-boot-starter-web](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-starter-web)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-jersey/pom.xml)| +|spring-boot-starter-jooq|用于使用JOOQ访问SQL数据库,可使用[spring-boot-starter-data-jpa](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-starter-data-jpa)或[spring-boot-starter-jdbc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-starter-jdbc)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-jooq/pom.xml)| +|spring-boot-starter-json|用于读写json|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-json/pom.xmll)| +|spring-boot-starter-jta-atomikos|用于使用Atomikos实现JTA事务|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-atomikos/pom.xml)| +|spring-boot-starter-jta-bitronix|用于使用Bitronix实现JTA事务|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-bitronix/pom.xml)| +|spring-boot-starter-jta-narayana|Spring Boot Narayana JTA Starter|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-narayana/pom.xml)| +|spring-boot-starter-mail|用于使用Java Mail和Spring框架email发送支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-mail/pom.xml)| +|spring-boot-starter-mustache|用于使用Mustache模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-mustache/pom.xml)| +|spring-boot-starter-quartz|Spring Boot Quartz Starter|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-quartz/pom.xml)| +|spring-boot-starter-security|对Spring Security的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-security/pom.xml)| +|spring-boot-starter-security-reactive|对响应式Spring Security的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-security-reactive/pom.xml)| +|spring-boot-starter-test|用于测试Spring Boot应用,支持常用测试类库,包括JUnit, Hamcrest和Mockito|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-test/pom.xml)| +|spring-boot-starter-thymeleaf|用于使用Thymeleaf模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-thymeleaf/pom.xml)| +|spring-boot-starter-validation|用于使用Hibernate Validator实现Java Bean校验|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-validation/pom.xml)| +|spring-boot-starter-web|用于使用Spring MVC构建web应用,包括RESTful。Tomcat是默认的内嵌容器|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-web/pom.xml)| +|spring-boot-starter-web-services|对Spring Web服务的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-web-services/pom.xml)| +|spring-boot-starter-webflux|提供用Spring框架创建webflux应用的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-webflux/pom.xml)| +|spring-boot-starter-websocket|用于使用Spring框架的WebSocket支持构建WebSocket应用|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-websocket/pom.xml)| 除了应用程序starters,以下starters可用于添加[production ready](../V. Spring Boot Actuator/README.md)的功能: @@ -67,20 +66,20 @@ Starters是一个依赖描述符的集合,你可以将它包含进项目中, |名称|描述|Pom| |----|:----|:----| -|spring-boot-starter-actuator|用于使用Spring Boot的Actuator,它提供了production ready功能来帮助你监控和管理应用程序|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-actuator/pom.xml)| +|spring-boot-starter-actuator|用于使用Spring Boot的Actuator,它提供了production ready功能来帮助你监控和管理应用程序|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-actuator/pom.xml)| -最后,Spring Boot还包含一些用于排除或交换某些特定技术方面的starters: +最后,Spring Boot还包含以下用于排除或交换某些特定技术方面的starters: **表 13.3. Spring Boot技术性starters** |名称|描述|Pom| |------|:------|:------| -|spring-boot-starter-jetty|用于使用Jetty作为内嵌servlet容器,可使用[spring-boot-starter-tomcat](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#spring-boot-starter-tomcat)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-jetty/pom.xml)| -|spring-boot-starter-log4j2|用于使用Log4j2记录日志,可使用[spring-boot-starter-logging](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#spring-boot-starter-logging)代替|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-log4j2/pom.xml)| -|spring-boot-starter-logging|用于使用Logback记录日志,默认的日志starter|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-logging/pom.xml)| -|spring-boot-starter-reactor-netty|使用Reactor Netty做为内嵌的HTTP服务器|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-reactor-netty/pom.xml)| -|spring-boot-starter-tomcat|用于使用Tomcat作为内嵌servlet容器,[spring-boot-starter-web](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#spring-boot-starter-web)使用的默认servlet容器|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-tomcat/pom.xml)| -|spring-boot-starter-undertow|用于使用Undertow作为内嵌servlet容器,可使用[spring-boot-starter-tomcat](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#spring-boot-starter-tomcat)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-starters/spring-boot-starter-undertow/pom.xml)| +|spring-boot-starter-jetty|用于使用Jetty作为内嵌servlet容器,可使用[spring-boot-starter-tomcat](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-starter-tomcat)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-jetty/pom.xml)| +|spring-boot-starter-log4j2|用于使用Log4j2记录日志,可使用[spring-boot-starter-logging](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-starter-logging)代替|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-log4j2/pom.xml)| +|spring-boot-starter-logging|用于使用Logback记录日志,默认的日志starter|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-logging/pom.xml)| +|spring-boot-starter-reactor-netty|使用Reactor Netty做为内嵌的HTTP服务器|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-reactor-netty/pom.xml)| +|spring-boot-starter-tomcat|用于使用Tomcat作为内嵌servlet容器,[spring-boot-starter-web](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-starter-web)使用的默认servlet容器|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-tomcat/pom.xml)| +|spring-boot-starter-undertow|用于使用Undertow作为内嵌servlet容器,可使用[spring-boot-starter-tomcat](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-starter-tomcat)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-starters/spring-boot-starter-undertow/pom.xml)| **注**:查看GitHub上位于`spring-boot-starters`模块内的[README文件](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-starters/README.adoc),可以获取到一个社区贡献的其他starters列表。 diff --git a/III. Using Spring Boot/14. Structuring Your Code.md b/III. Using Spring Boot/14. Structuring Your Code.md new file mode 100644 index 00000000..dcced825 --- /dev/null +++ b/III. Using Spring Boot/14. Structuring Your Code.md @@ -0,0 +1,3 @@ +### 14. 组织你的代码 + +Spring Boot不要求使用任何特殊的代码结构。不过,遵循以下的一些最佳实践还是挺有帮助的。 diff --git a/III. Using Spring Boot/14. Structuring your code.md b/III. Using Spring Boot/14. Structuring your code.md deleted file mode 100644 index 7ad1771a..00000000 --- a/III. Using Spring Boot/14. Structuring your code.md +++ /dev/null @@ -1,3 +0,0 @@ -### 14. 组织你的代码 - -Spring Boot不要求使用任何特殊的代码结构,不过,遵循以下的一些最佳实践还是挺有帮助的。 diff --git "a/III. Using Spring Boot/14.1. Using the \342\200\234default\342\200\235 package.md" "b/III. Using Spring Boot/14.1. Using the \342\200\234default\342\200\235 Package.md" similarity index 100% rename from "III. Using Spring Boot/14.1. Using the \342\200\234default\342\200\235 package.md" rename to "III. Using Spring Boot/14.1. Using the \342\200\234default\342\200\235 Package.md" diff --git a/III. Using Spring Boot/14.2. Locating the main application class.md b/III. Using Spring Boot/14.2. Locating the Main Application Class.md similarity index 100% rename from III. Using Spring Boot/14.2. Locating the main application class.md rename to III. Using Spring Boot/14.2. Locating the Main Application Class.md diff --git a/III. Using Spring Boot/15. Configuration Classes.md b/III. Using Spring Boot/15. Configuration Classes.md new file mode 100644 index 00000000..8f39dbec --- /dev/null +++ b/III. Using Spring Boot/15. Configuration Classes.md @@ -0,0 +1,5 @@ +### 15. 配置类 + +Spring Boot提倡基于Java的配置。尽管你可以通过XML源来使用`SpringApplication`,不过还是建议你使用`@Configuration`类作为主要配置源。通常定义了`main`方法的类是使用`@Configuration`注解的一个很好的替补。 + +**注**:虽然网络上有很多使用XML配置的Spring示例,但你应该尽可能的使用基于Java的配置,搜索查看`Enable*`注解就是一个好的开端。 diff --git a/III. Using Spring Boot/15. Configuration classes.md b/III. Using Spring Boot/15. Configuration classes.md deleted file mode 100644 index b655b3e1..00000000 --- a/III. Using Spring Boot/15. Configuration classes.md +++ /dev/null @@ -1,5 +0,0 @@ -### 15. 配置类 - -Spring Boot提倡基于Java的配置。尽管你可以通过XML源来使用`SpringApplication`,不过还是建议你使用`@Configuration`类作为主要配置源。通常定义了`main`方法的类也是使用`@Configuration`注解的一个很好的替补。 - -**注**:虽然网络上有很多使用XML配置的Spring示例,但你应该尽可能的使用基于Java的配置,搜索查看`Enable*`注解就是一个好的开端。 diff --git a/III. Using Spring Boot/15.1. Importing additional configuration classes.md b/III. Using Spring Boot/15.1. Importing Additional Configuration Classes.md similarity index 100% rename from III. Using Spring Boot/15.1. Importing additional configuration classes.md rename to III. Using Spring Boot/15.1. Importing Additional Configuration Classes.md diff --git a/III. Using Spring Boot/15.2. Importing XML configuration.md b/III. Using Spring Boot/15.2. Importing XML Configuration.md similarity index 100% rename from III. Using Spring Boot/15.2. Importing XML configuration.md rename to III. Using Spring Boot/15.2. Importing XML Configuration.md diff --git a/III. Using Spring Boot/16.1. Gradually Replacing Auto-configuration.md b/III. Using Spring Boot/16.1. Gradually Replacing Auto-configuration.md new file mode 100644 index 00000000..eaa69040 --- /dev/null +++ b/III. Using Spring Boot/16.1. Gradually Replacing Auto-configuration.md @@ -0,0 +1,5 @@ +### 16.1. 逐步替换自动配置 + +自动配置(Auto-configuration)是非侵入性的,任何时候你都可以定义自己的配置类来替换自动配置的特定部分。例如,如果你添加自己的`DataSource` bean,默认的内嵌数据库支持将不被考虑。 + +如果需要查看当前应用启动了哪些自动配置项,你可以在运行应用时打开`--debug`开关,这将为核心日志开启debug日志级别,并将配置情况输出到控制台。 diff --git a/III. Using Spring Boot/16.1. Gradually replacing auto-configuration.md b/III. Using Spring Boot/16.1. Gradually replacing auto-configuration.md deleted file mode 100644 index d0794200..00000000 --- a/III. Using Spring Boot/16.1. Gradually replacing auto-configuration.md +++ /dev/null @@ -1,5 +0,0 @@ -### 16.1. 逐步替换自动配置 - -自动配置(Auto-configuration)是非侵入性的,任何时候你都可以定义自己的配置类来替换自动配置的特定部分。例如,如果你添加自己的`DataSource` bean,默认的内嵌数据库支持将不被考虑。 - -如果需要查看当前应用启动了哪些自动配置项,你可以在运行应用时打开`--debug`开关,这将为核心日志开启debug日志级别,并将自动配置相关的日志输出到控制台。 diff --git a/III. Using Spring Boot/16.2. Disabling Specific Auto-configuration Classes.md b/III. Using Spring Boot/16.2. Disabling Specific Auto-configuration Classes.md new file mode 100644 index 00000000..b56a20fb --- /dev/null +++ b/III. Using Spring Boot/16.2. Disabling Specific Auto-configuration Classes.md @@ -0,0 +1,16 @@ +### 16.2. 禁用特定的自动配置类 + +如果发现启用了不想要的自动配置类,你可以使用`@EnableAutoConfiguration`注解的exclude属性禁用它们: +```java +import org.springframework.boot.autoconfigure.*; +import org.springframework.boot.autoconfigure.jdbc.*; +import org.springframework.context.annotation.*; + +@Configuration +@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) +public class MyConfiguration { +} +``` +如果该类不在classpath中,你可以使用该注解的excludeName属性,并指定全限定名来达到相同效果。最后,你可以通过`spring.autoconfigure.exclude`属性exclude多个自动配置项(一个自动配置项集合)。 + +**注** 通过注解级别或exclude属性都可以定义排除项。 diff --git a/III. Using Spring Boot/16.2. Disabling specific auto-configuration.md b/III. Using Spring Boot/16.2. Disabling specific auto-configuration.md deleted file mode 100644 index 2807663f..00000000 --- a/III. Using Spring Boot/16.2. Disabling specific auto-configuration.md +++ /dev/null @@ -1,16 +0,0 @@ -### 16.2. 禁用特定的自动配置项 - -如果发现启用了不想要的自动配置项,你可以使用`@EnableAutoConfiguration`注解的exclude属性禁用它们: -```java -import org.springframework.boot.autoconfigure.*; -import org.springframework.boot.autoconfigure.jdbc.*; -import org.springframework.context.annotation.*; - -@Configuration -@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) -public class MyConfiguration { -} -``` -如果该类不在classpath中,你可以使用该注解的excludeName属性,并指定全限定名来达到相同效果。最后,你可以通过`spring.autoconfigure.exclude`属性exclude多个自动配置项(一个自动配置项集合)。 - -**注** 通过注解级别或exclude属性都可以定义排除项。 diff --git a/III. Using Spring Boot/17. Spring Beans and Dependency Injection.md b/III. Using Spring Boot/17. Spring Beans and Dependency Injection.md new file mode 100644 index 00000000..c54c5519 --- /dev/null +++ b/III. Using Spring Boot/17. Spring Beans and Dependency Injection.md @@ -0,0 +1,44 @@ +### 17. Spring Beans和依赖注入 + +你可以自由地使用任何标准的Spring框架技术去定义bean和它们注入的依赖。简单起见,我们经常发现使用`@ComponentScan`(用来注解搜索bean)和`@Autowired`(用来构造器注入)能够很好地工作。 + +如果遵循以上的建议组织代码结构(将应用的main类放到包的最上层,即root package),那么你就可以添加`@ComponentScan`注解而不需要任何参数,所有应用组件(`@Component`, `@Service`, `@Repository`, `@Controller`等)都会自动注册成Spring Beans。 + +下面是一个`@Service` Bean的示例,它使用构建器注入获取一个需要的`RiskAssessor` bean: +```java +package com.example.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class DatabaseAccountService implements AccountService { + + private final RiskAssessor riskAssessor; + + @Autowired + public DatabaseAccountService(RiskAssessor riskAssessor) { + this.riskAssessor = riskAssessor; + } + + // ... +} +``` + +如果bean里面有一个构造器,你可以省略`@Autowired`。 +```java +@Service +public class DatabaseAccountService implements AccountService { + + private final RiskAssessor riskAssessor; + + public DatabaseAccountService(RiskAssessor riskAssessor) { + + this .riskAssessor = riskAssessor; + } + +// ... + +} +``` +**注** 注意使用构建器注入允许`riskAssessor`字段被标记为`final`,这意味着`riskAssessor`后续是不能改变的。 diff --git a/III. Using Spring Boot/17. Spring Beans and dependency injection.md b/III. Using Spring Boot/17. Spring Beans and dependency injection.md deleted file mode 100644 index d08ad1a4..00000000 --- a/III. Using Spring Boot/17. Spring Beans and dependency injection.md +++ /dev/null @@ -1,44 +0,0 @@ -### 17. Spring Beans和依赖注入 - -你可以自由地使用任何标准的Spring框架技术去定义beans和它们注入的依赖。简单起见,我们经常使用`@ComponentScan`注解搜索beans,并结合`@Autowired`构造器注入。 - -如果遵循以上的建议组织代码结构(将应用的main类放到包的最上层,即root package),那么你就可以添加`@ComponentScan`注解而不需要任何参数,所有应用组件(`@Component`, `@Service`, `@Repository`, `@Controller`等)都会自动注册成Spring Beans。 - -下面是一个`@Service` Bean的示例,它使用构建器注入获取一个需要的`RiskAssessor` bean。 -```java -package com.example.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class DatabaseAccountService implements AccountService { - - private final RiskAssessor riskAssessor; - - @Autowired - public DatabaseAccountService(RiskAssessor riskAssessor) { - this.riskAssessor = riskAssessor; - } - - // ... -} -``` - -如果bean里面有一个构造器,你可以省略`@Autowired`。 -```java -@Service -public class DatabaseAccountService implements AccountService { - - private final RiskAssessor riskAssessor; - - public DatabaseAccountService(RiskAssessor riskAssessor) { - - this .riskAssessor = riskAssessor; - } - -// ... - -} -``` -**注** 注意使用构建器注入允许`riskAssessor`字段被标记为`final`,这意味着`riskAssessor`后续是不能改变的。 diff --git a/III. Using Spring Boot/18. Using the @SpringBootApplication annotation.md b/III. Using Spring Boot/18. Using the @SpringBootApplication Annotation.md similarity index 100% rename from III. Using Spring Boot/18. Using the @SpringBootApplication annotation.md rename to III. Using Spring Boot/18. Using the @SpringBootApplication Annotation.md diff --git a/III. Using Spring Boot/19. Running Your Application.md b/III. Using Spring Boot/19. Running Your Application.md new file mode 100644 index 00000000..a6e5505b --- /dev/null +++ b/III. Using Spring Boot/19. Running Your Application.md @@ -0,0 +1,5 @@ +### 19. 运行应用程序 + +将应用打包成jar,并使用内嵌HTTP服务器的一个最大好处是,你可以像其他方式那样运行你的应用程序。调试Spring Boot应用也很简单。你都不需要任何特殊IDE插件或扩展。 + +**注**:本章节只覆盖基于jar的打包。如果选择将应用打包成war文件,你最好参考相关的服务器和IDE文档。 diff --git a/III. Using Spring Boot/19. Running your application.md b/III. Using Spring Boot/19. Running your application.md deleted file mode 100644 index b7b6c8d3..00000000 --- a/III. Using Spring Boot/19. Running your application.md +++ /dev/null @@ -1,5 +0,0 @@ -### 19. 运行应用程序 - -将应用打包成jar,并使用内嵌HTTP服务器的一个最大好处是,你可以像其他方式那样运行你的应用程序。调试Spring Boot应用也很简单,你都不需要任何特殊IDE插件或扩展! - -**注**:本章节只覆盖基于jar的打包,如果选择将应用打包成war文件,你最好参考相关的服务器和IDE文档。 diff --git a/III. Using Spring Boot/19.1. Running from an IDE.md b/III. Using Spring Boot/19.1. Running from an IDE.md index a2d272de..3f7c2d8f 100644 --- a/III. Using Spring Boot/19.1. Running from an IDE.md +++ b/III. Using Spring Boot/19.1. Running from an IDE.md @@ -1,7 +1,7 @@ ### 19.1. 从IDE中运行 -你可以从IDE中运行Spring Boot应用,就像一个简单的Java应用,但首先需要导入项目。导入步骤取决于你的IDE和构建系统,大多数IDEs能够直接导入Maven项目,例如Eclipse用户可以选择`File`菜单的`Import…​` --> `Existing Maven Projects`。 +你可以从IDE中运行Spring Boot应用,就像一个简单的Java应用。但首先需要导入项目。导入步骤取决于你的IDE和构建系统,大多数IDEs能够直接导入Maven项目。例如Eclipse用户可以选择`File`菜单的`Import…` --> `Existing Maven Projects`。 -如果不能直接将项目导入IDE,你可以使用构建系统生成IDE的元数据。Maven有针对[Eclipse](http://maven.apache.org/plugins/maven-eclipse-plugin/)和[IDEA](http://maven.apache.org/plugins/maven-idea-plugin/)的插件;Gradle为[各种IDEs](http://www.gradle.org/docs/current/userguide/ide_support.html)提供插件。 +如果不能直接将项目导入IDE,你可以使用构建系统生成IDE的元数据。Maven有针对[Eclipse](http://maven.apache.org/plugins/maven-eclipse-plugin/)和[IDEA](http://maven.apache.org/plugins/maven-idea-plugin/)的插件。Gradle为[各种IDEs](http://www.gradle.org/docs/current/userguide/ide_support.html)提供插件。 **注** 如果意外地多次运行一个web应用,你将看到一个"端口已被占用"的错误。STS用户可以使用`Relaunch`而不是`Run`按钮,以确保任何存在的实例是关闭的。 diff --git a/III. Using Spring Boot/19.2. Running as a packaged application.md b/III. Using Spring Boot/19.2. Running as a Packaged Application.md similarity index 100% rename from III. Using Spring Boot/19.2. Running as a packaged application.md rename to III. Using Spring Boot/19.2. Running as a Packaged Application.md diff --git a/III. Using Spring Boot/19.3. Using the Maven Plugin.md b/III. Using Spring Boot/19.3. Using the Maven Plugin.md new file mode 100644 index 00000000..a91f3eab --- /dev/null +++ b/III. Using Spring Boot/19.3. Using the Maven Plugin.md @@ -0,0 +1,10 @@ +### 19.3. 使用Maven插件运行 + +Spring Boot Maven插件包含一个`run`目标,可用来快速编译和运行应用程序,并且跟在IDE运行一样支持热加载。下面的例子展示了运行Spring Boot应用的一个典型的Maven命令: +```shell +$ mvn spring-boot:run +``` +你可能还会想使用操作系统环境变量`MAVEN_OPTS`: +```shell +$ export MAVEN_OPTS=-Xmx1024m +``` diff --git a/III. Using Spring Boot/19.3. Using the Maven plugin.md b/III. Using Spring Boot/19.3. Using the Maven plugin.md deleted file mode 100644 index d4351558..00000000 --- a/III. Using Spring Boot/19.3. Using the Maven plugin.md +++ /dev/null @@ -1,10 +0,0 @@ -### 19.3. 使用Maven插件运行 - -Spring Boot Maven插件包含一个`run`目标,可用来快速编译和运行应用程序,并且跟在IDE运行一样支持热加载。 -```shell -$ mvn spring-boot:run -``` -你可以使用一些有用的操作系统环境变量: -```shell -$ export MAVEN_OPTS=-Xmx1024m -``` diff --git a/III. Using Spring Boot/19.4. Using the Gradle Plugin.md b/III. Using Spring Boot/19.4. Using the Gradle Plugin.md new file mode 100644 index 00000000..b1fc822e --- /dev/null +++ b/III. Using Spring Boot/19.4. Using the Gradle Plugin.md @@ -0,0 +1,10 @@ +### 19.4. 使用Gradle插件运行 + +Spring Boot Gradle插件也包含一个`bootRun`任务,可用来运行你的应用程序。无论你何时应用 `org.springframework.boot`和`java plugins`,`bootRun`任务总会被添加进去。 +```shell +$ gradle bootRun +``` +你可能还会想使用操作系统环境变量`JAVA_OPTS`: +```shell +$ export JAVA_OPTS=-Xmx1024m +``` diff --git a/III. Using Spring Boot/19.4. Using the Gradle plugin.md b/III. Using Spring Boot/19.4. Using the Gradle plugin.md deleted file mode 100644 index 6372fb55..00000000 --- a/III. Using Spring Boot/19.4. Using the Gradle plugin.md +++ /dev/null @@ -1,10 +0,0 @@ -### 19.4. 使用Gradle插件运行 - -Spring Boot Gradle插件也包含一个`bootRun`任务,可用来运行你的应用程序。无论你何时应用 `org.springframework.boot`和`java plugins`,`bootRun`任务总会被添加进去。 -```shell -$ gradle bootRun -``` -你可能想使用一些有用的操作系统环境变量: -```shell -$ export JAVA_OPTS=-Xmx1024m -``` diff --git a/III. Using Spring Boot/19.5. Hot Swapping.md b/III. Using Spring Boot/19.5. Hot Swapping.md new file mode 100755 index 00000000..45ce21f6 --- /dev/null +++ b/III. Using Spring Boot/19.5. Hot Swapping.md @@ -0,0 +1,5 @@ +### 19.5. 热交换 + +由于Spring Boot应用只是普通的Java应用,所以JVM热交换(hot-swapping)也能开箱即用。不过JVM热交换能替换的字节码有限制。想要更彻底的解决方案可以使用[JRebel](http://zeroturnaround.com/software/jrebel/)。 + +`spring-boot-devtools`模块也支持应用快速重启(restart)。详情参考下面的[章节 20,开发者工具](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-devtools)和[“How-to”](../IX. ‘How-to’ guides/README.md)章节。 diff --git a/III. Using Spring Boot/19.5. Hot swapping.md b/III. Using Spring Boot/19.5. Hot swapping.md deleted file mode 100644 index b5a8f9b0..00000000 --- a/III. Using Spring Boot/19.5. Hot swapping.md +++ /dev/null @@ -1,5 +0,0 @@ -### 19.5. 热交换 - -由于Spring Boot应用只是普通的Java应用,所以JVM热交换(hot-swapping)也能开箱即用。不过JVM热交换能替换的字节码有限制,想要更彻底的解决方案可以使用[JRebel](http://zeroturnaround.com/software/jrebel/)。`spring-boot-devtools`模块也支持应用快速重启(restart)。 - -详情参考下面的[Chapter 20, Developer tools](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-devtools)和[“How-to”](../IX. ‘How-to’ guides/README.md)章节。 diff --git a/III. Using Spring Boot/20. Developer Tools.md b/III. Using Spring Boot/20. Developer Tools.md new file mode 100644 index 00000000..28ad3c7b --- /dev/null +++ b/III. Using Spring Boot/20. Developer Tools.md @@ -0,0 +1,23 @@ +### 20. 开发者工具 + +Spring Boot包含了一些额外的工具集,用于提升Spring Boot应用的开发体验。`spring-boot-devtools`模块可以included到任何模块中,以提供development-time特性,你只需将该模块的依赖添加到构建中: + +**Maven** +```xml + + + org.springframework.boot + spring-boot-devtools + true + + +``` +**Gradle** +```properties +dependencies { + compile("org.springframework.boot:spring-boot-devtools") +} +``` +**注** 在运行一个完整的,打包过的应用时,开发者工具(devtools)会被自动禁用。如果应用使用`java -jar`或特殊的类加载器启动,都会被认为是一个产品级的应用(production application),从而禁用开发者工具。为了防止devtools传递到项目中的其他模块,设置该依赖级别为optional是个不错的实践。不过Gradle不支持`optional`依赖,所以你可能要了解下[propdeps-plugin](https://github.com/spring-projects/gradle-plugins/tree/master/propdeps-plugin)。 + +**注** 重新打包的归档文件默认不包含开发者工具。如果你想使用某些远程的开发者工具特性,你需要禁用`excludeDevtools`构建属性。Maven和Gradle都支持该属性。 diff --git a/III. Using Spring Boot/20. Developer tools.md b/III. Using Spring Boot/20. Developer tools.md deleted file mode 100644 index d26286f5..00000000 --- a/III. Using Spring Boot/20. Developer tools.md +++ /dev/null @@ -1,20 +0,0 @@ -###20. 开发者工具 -Spring Boot包含了一些额外的工具集,用于提升Spring Boot应用的开发体验。`spring-boot-devtools`模块可以included到任何模块中,以提供development-time特性,你只需简单的将该模块的依赖添加到构建中: - -**Maven** -```xml - - - org.springframework.boot - spring-boot-devtools - true - - -``` -**Gradle** -```properties -dependencies { - compile("org.springframework.boot:spring-boot-devtools") -} -``` -**注** 在运行一个完整的,打包过的应用时,开发者工具(devtools)会被自动禁用。如果应用使用`java -jar`或特殊的类加载器启动,都会被认为是一个产品级的应用(production application),从而禁用开发者工具。为了防止devtools传递到项目中的其他模块,设置该依赖级别为optional是个不错的实践。不过Gradle不支持`optional`依赖,所以你可能要了解下[propdeps-plugin](https://github.com/spring-projects/gradle-plugins/tree/master/propdeps-plugin)。重新打包的归档文件默认不包含开发者工具。如果你想使用某些远程的开发者工具特性,你需要禁用`excludeDevtools`构建属性。Maven和Gradle都支持该属性。 diff --git a/III. Using Spring Boot/20.1. Property Defaults.md b/III. Using Spring Boot/20.1. Property Defaults.md new file mode 100644 index 00000000..1fa55953 --- /dev/null +++ b/III. Using Spring Boot/20.1. Property Defaults.md @@ -0,0 +1,7 @@ +### 20.1 默认属性 + +Spring Boot支持的一些库使用缓存提高性能,比如模板引擎将缓存编译完的模板以避免重复解析模板文件。另外,当服务静态资源时,Spring MVC能够加入HTTP缓存头来进行回应。 +虽然缓存在产品中很有用,但开发期间就是个累赘了,因为缓存会阻碍你看到在应用中刚刚做出的修改。正是因为这个原因,`spring-boot-devtools`默认禁用那些缓存选项。 +缓存选项通常配置在`application.properties`文件中,比如Thymeleaf提供了`spring.thymeleaf.cache`属性,`spring-boot-devtools`模块会自动应用敏感的`development-time`配置,而不是手动设置这些属性。 + +**注** 查看[DevToolsPropertyDefaultsPostProcessor](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java)获取完整的被应用的属性列表。 diff --git a/III. Using Spring Boot/20.1. Property defaults.md b/III. Using Spring Boot/20.1. Property defaults.md deleted file mode 100644 index 3b8812a0..00000000 --- a/III. Using Spring Boot/20.1. Property defaults.md +++ /dev/null @@ -1,6 +0,0 @@ -###20.1 默认属性 - -Spring Boot支持的一些库使用缓存提高性能,比如模板引擎将缓存编译完的模板以避免重复解析模板文件。另外,当服务静态资源时,Spring MVC能够加入HTTP缓存头来进行回应。虽然缓存在产品中很有用,但开发期间就是个累赘了,因为缓存会阻碍你看到在应用中刚刚做出的修改。正是因为这个原因,`spring-boot-devtools`将会默认禁用那些缓存选项。 -缓存选项通常配置在`application.properties`文件中,比如Thymeleaf提供了`spring.thymeleaf.cache`属性,`spring-boot-devtools`模块会自动应用敏感的`development-time`配置,而不是手动设置这些属性。 - -**注** 查看[DevToolsPropertyDefaultsPostProcessor](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java)获取完整的被应用的属性列表。 diff --git a/III. Using Spring Boot/20.2. Automatic Restart.md b/III. Using Spring Boot/20.2. Automatic Restart.md new file mode 100644 index 00000000..3272682b --- /dev/null +++ b/III. Using Spring Boot/20.2. Automatic Restart.md @@ -0,0 +1,19 @@ +### 20.2 自动重启 + +如果应用使用`spring-boot-devtools`,则只要classpath下的文件有变动,它就会自动重启。这在使用IDE时非常有用,因为可以很快得到代码改变的反馈。默认情况下,classpath下任何指向文件夹的实体都会被监控,注意一些资源的修改比如静态assets,视图模板不需要重启应用。 + +**触发重启** 由于DevTools监控classpath下的资源,所以唯一触发重启的方式就是更新classpath。引起classpath更新的方式依赖于你使用的IDE,在Eclipse里,保存一个修改的文件会引起classpath更新,并触发重启。在IntelliJ IDEA中,构建工程(Build → Make Project)有同样效果。 + +**注** 只要开启了fork功能,你也可以通过支持的构建工具(Maven和Gradle)启动应用。因为DevTools需要一个隔离的应用类加载器执行正确的操作。当发现类路径中存在DevTools时,Gradle和Maven会默认执行该行为。 + +自动重启跟LiveReload可以一起很好的工作,具体参考[LiveReload章节](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-devtools-livereload)。如果你使用JRebel,自动重启会被禁用以支持动态类加载,其他devtools特性(比如,LiveReload和属性覆盖)仍旧可以使用。 + +DevTools依赖应用上下文的shutdown钩子来关闭处于重启过程的应用,如果禁用shutdown钩子(`SpringApplication.setRegisterShutdownHook(false)`),它将不能正常工作。 + +当判定classpath下实体的改变是否会触发重启时,DevTools自动忽略以下工程:`spring-boot`,`spring-boot-devtools`,`spring-boot-autoconfigure`,`spring-boot-actuator`和`spring-boot-starter`。 + +DevTools需要自定义`ApplicationContext`使用的资源加载器。如果你的应用已经提供了一个,它将会被覆盖。直接覆盖`ApplicationContext`的getResource方法不被支持。 + +**Restart vs Reload** Spring Boot提供的重启技术是通过使用两个类加载器实现的。没有变化的类(比如那些第三方jars)会加载进一个基础的类加载器,正在开发的类会加载进一个重启的类加载器。当应用重启时,重启的类加载器会被丢弃,并创建一个新的。这种方式意味着应用重启通常比冷启动快很多,因为基础类加载器已经可用并且填充完成。 + +如果发现重启对于你的应用来说不够快,或遇到类加载的问题,那你可以考虑reload技术,比如[JRebel](http://zeroturnaround.com/software/jrebel/),这些技术是通过重写它们加载过的类实现的。 diff --git a/III. Using Spring Boot/20.2. Automatic restart.md b/III. Using Spring Boot/20.2. Automatic restart.md deleted file mode 100644 index 5a88550f..00000000 --- a/III. Using Spring Boot/20.2. Automatic restart.md +++ /dev/null @@ -1,20 +0,0 @@ -###20.2 自动重启 - -如果应用使用`spring-boot-devtools`,则只要classpath下的文件有变动,它就会自动重启。这在使用IDE时非常有用,因为可以很快得到代码改变的反馈。默认情况下,classpath下任何指向文件夹的实体都会被监控,注意一些资源的修改比如静态assets,视图模板不需要重启应用。 - -**触发重启** 由于DevTools监控classpath下的资源,所以唯一触发重启的方式就是更新classpath。引起classpath更新的方式依赖于你使用的IDE,在Eclipse里,保存一个修改的文件将引起classpath更新,并触发重启。在IntelliJ IDEA中,构建工程(Build → Make Project)有同样效果。 - -**注** 你也可以通过支持的构建工具(比如,Maven和Gradle)启动应用,只要开启fork功能,因为DevTools需要一个隔离的应用类加载器执行正确的操作。当发现类路径中存在DevTools时,Gradle和Maven会默认执行该行为, - -自动重启跟LiveReload可以一起很好的工作,具体参考[下面章节](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-devtools-livereload)。如果你使用JRebel,自动重启将禁用以支持动态类加载,其他devtools特性,比如LiveReload,属性覆盖仍旧可以使用。 - -DevTools依赖应用上下文的shutdown钩子来关闭处于重启过程的应用,如果禁用shutdown钩子(`SpringApplication.setRegisterShutdownHook(false)`),它将不能正常工作。 - -当判定classpath下实体的改变是否会触发重启时,DevTools自动忽略以下工程:`spring-boot`,`spring-boot-devtools`,`spring-boot-autoconfigure`,`spring-boot-actuator`和`spring-boot-starter`。 - -DevTools需要自定义`ApplicationContext`使用的资源加载器。如果你的应用已经提供了一个,它将会被覆盖。直接覆盖`ApplicationContext`的getResource方法不被支持。 - -**Restart vs Reload** Spring Boot提供的重启技术是通过使用两个类加载器实现的。没有变化的类(比如那些第三方jars)会加载进一个基础(basic)classloader,正在开发的类会加载进一个重启(restart)classloader。当应用重启时,restart类加载器会被丢弃,并创建一个新的。这种方式意味着应用重启通常比冷启动(cold starts)快很多,因为基础类加载器已经可用,并且populated(意思是基础类加载器加载的类比较多?)。 - -如果发现重启对于你的应用来说不够快,或遇到类加载的问题,那你可以考虑reload技术,比如[JRebel](http://zeroturnaround.com/software/jrebel/),这些技术是通过重写它们加载过的类实现的。 - diff --git a/III. Using Spring Boot/20.2.1. Excluding resources.md b/III. Using Spring Boot/20.2.1. Excluding resources.md deleted file mode 100644 index 41d7ca5d..00000000 --- a/III. Using Spring Boot/20.2.1. Excluding resources.md +++ /dev/null @@ -1,8 +0,0 @@ -### 20.2.1 排除资源 - -某些资源的变化没必要触发重启,比如Thymeleaf模板可以随时编辑。默认情况下,位于`/META-INF/maven`,`/META-INF/resources`,`/resources`,`/static`,`/public`或`/templates`下的资源变更不会触发重启,但会触发实时加载(live reload)。你可以使用`spring.devtools.restart.exclude`属性自定义这些排除规则,比如,为了只排除`/static`和`/public`,你可以这样设置: -```properties -spring.devtools.restart.exclude=static/**,public/** -``` - -**注** 如果你想保留默认属性,并添加其他的排除规则,可以使用`spring.devtools.restart.additional-exclude`属性作为代替。 diff --git a/III. Using Spring Boot/20.2.1. Logging changes in condition evaluation.md b/III. Using Spring Boot/20.2.1. Logging changes in condition evaluation.md new file mode 100644 index 00000000..ffb89675 --- /dev/null +++ b/III. Using Spring Boot/20.2.1. Logging changes in condition evaluation.md @@ -0,0 +1,8 @@ +### 20.2.1 在状况评估里记录更改 + +默认地,每次应用重启,都会记录一份展示状况评估差量的报告。报告展示了对应用的自动配置所做的更改,比如添加或者移除bean、设置配置属性。 + +禁用记录报告,设置以下属性: +```properties +spring.devtools.restart.log-condition-evaluation-delta=false +``` \ No newline at end of file diff --git a/III. Using Spring Boot/20.2.2. Excluding Resources.md b/III. Using Spring Boot/20.2.2. Excluding Resources.md new file mode 100644 index 00000000..0ae04c9f --- /dev/null +++ b/III. Using Spring Boot/20.2.2. Excluding Resources.md @@ -0,0 +1,8 @@ +### 20.2.2 排除资源 + +某些资源的变化没必要触发重启,比如Thymeleaf模板可以随时编辑。默认情况下,位于`/META-INF/maven`,`/META-INF/resources`,`/resources`,`/static`,`/public`或`/templates`下的资源变更不会触发重启,但会触发实时重载(live reload)。你可以使用`spring.devtools.restart.exclude`属性自定义这些排除规则,比如,为了只排除`/static`和`/public`,你可以设置如下属性: +```properties +spring.devtools.restart.exclude=static/**,public/** +``` + +**注** 如果你想保留默认属性,并添加其他的排除规则,可以使用`spring.devtools.restart.additional-exclude`属性作为代替。 diff --git a/III. Using Spring Boot/20.2.2. Watching additional paths.md b/III. Using Spring Boot/20.2.2. Watching additional paths.md deleted file mode 100644 index b2145a57..00000000 --- a/III. Using Spring Boot/20.2.2. Watching additional paths.md +++ /dev/null @@ -1,3 +0,0 @@ -###20.2.2 查看其他路径 - -如果想让应用在改变没有位于classpath下的文件时也会重启或重新加载,你可以使用`spring.devtools.restart.additional-paths`属性来配置监控变化的额外路径。你可以使用[上面描述](./20.2.1 Excluding resources.md)过的`spring.devtools.restart.exclude`属性去控制额外路径下的变化是否触发一个完整重启或只是一个实时重新加载。 diff --git a/III. Using Spring Boot/20.2.3. Disabling restart.md b/III. Using Spring Boot/20.2.3. Disabling restart.md deleted file mode 100644 index fe0e1796..00000000 --- a/III. Using Spring Boot/20.2.3. Disabling restart.md +++ /dev/null @@ -1,11 +0,0 @@ -###20.2.3 禁用重启 - -如果不想使用重启特性,你可以通过`spring.devtools.restart.enabled`属性来禁用它,通常情况下可以在`application.properties`文件中设置(依旧会初始化重启类加载器,但它不会监控文件变化)。 - -如果需要彻底禁用重启支持,比如,不能跟某个特殊库一块工作,你需要在调用`SpringApplication.run(…​)`之前设置一个系统属性,如下: -```java -public static void main(String[] args) { - System.setProperty("spring.devtools.restart.enabled", "false"); - SpringApplication.run(MyApp.class, args); -} -``` diff --git a/III. Using Spring Boot/20.2.3. Watching Additional Paths.md b/III. Using Spring Boot/20.2.3. Watching Additional Paths.md new file mode 100644 index 00000000..dda43811 --- /dev/null +++ b/III. Using Spring Boot/20.2.3. Watching Additional Paths.md @@ -0,0 +1,3 @@ +### 20.2.3 查看其他路径 + +如果想让应用在改变没有位于classpath下的文件时也会重启或重新加载,你可以使用`spring.devtools.restart.additional-paths`属性来配置监控变化的额外路径。你可以使用[之前描述](./20.2.2 Excluding Resources.md)过的`spring.devtools.restart.exclude`属性去控制额外路径下的变化是否触发一个完整重启或一个实时重新加载。 diff --git a/III. Using Spring Boot/20.2.4. Disabling Restart.md b/III. Using Spring Boot/20.2.4. Disabling Restart.md new file mode 100644 index 00000000..56aefed9 --- /dev/null +++ b/III. Using Spring Boot/20.2.4. Disabling Restart.md @@ -0,0 +1,11 @@ +### 20.2.4 禁用重启 + +如果不想使用重启特性,你可以通过`spring.devtools.restart.enabled`属性来禁用它。通常情况下可以在`application.properties`文件中设置(依旧会初始化重启类加载器,但它不会监控文件变化)。 + +如果需要彻底禁用重启支持(比如,不能跟某个特殊库一块工作),你需要在调用`SpringApplication.run(…)`之前,把系统属性`spring.devtools.restart.enabled`设置为`false`,如下: +```java +public static void main(String[] args) { + System.setProperty("spring.devtools.restart.enabled", "false"); + SpringApplication.run(MyApp.class, args); +} +``` diff --git a/III. Using Spring Boot/20.2.4. Using a trigger file.md b/III. Using Spring Boot/20.2.4. Using a trigger file.md deleted file mode 100644 index 4bc94c30..00000000 --- a/III. Using Spring Boot/20.2.4. Using a trigger file.md +++ /dev/null @@ -1,7 +0,0 @@ -###20.2.4 使用触发器文件 - -如果使用一个IDE连续不断地编译变化的文件,你可能倾向于只在特定时间触发重启,触发器文件可以帮你实现该功能。触发器文件是一个特殊的文件,只有修改它才能实际触发一个重启检测。改变该文件只会触发检测,实际的重启只会在Devtools发现它必须这样做的时候,触发器文件可以手动更新,也可以通过IDE插件更新。 - -使用`spring.devtools.restart.trigger-file`属性可以指定触发器文件。 - -**注** 你可能想将`spring.devtools.restart.trigger-file`属性设置为[全局设置](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-devtools-globalsettings),这样所有的工程表现都会相同。 diff --git a/III. Using Spring Boot/20.2.5. Customizing the restart classloader.md b/III. Using Spring Boot/20.2.5. Customizing the restart classloader.md deleted file mode 100644 index 2e8bf124..00000000 --- a/III. Using Spring Boot/20.2.5. Customizing the restart classloader.md +++ /dev/null @@ -1,12 +0,0 @@ -###20.2.5 自定义restart类加载器 - -正如以上[Restart vs Reload](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-spring-boot-restart-vs-reload)章节讨论的,重启功能是通过两个类加载器实现的。对于大部分应用来说是没问题的,但有时候它可能导致类加载问题。 - -默认情况,在IDE里打开的项目会通过'restart'类加载器加载,其他常规的`.jar`文件会使用'basic'类加载器加载。如果你工作在一个多模块的项目下,并且不是每个模块都导入IDE里,你可能需要自定义一些东西。你需要创建一个`META-INF/spring-devtools.properties`文件,`spring-devtools.properties`文件可以包含`restart.exclude.`,`restart.include.`前缀的属性。`include`元素定义了那些需要加载进'restart'类加载器中的实体,`exclude`元素定义了那些需要加载进'basic'类加载器中的实体,这些属性的值是一个将应用到classpath的正则表达式。 - -例如: -```properties -restart.include.companycommonlibs=/mycorp-common-[\\w-]+\.jar -restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar -``` -**注** 所有属性的keys必须唯一,只要以`restart.include.`或`restart.exclude.`开头都会考虑进去。所有来自classpath的`META-INF/spring-devtools.properties`都会被加载,你可以将文件打包进工程或工程使用的库里。 diff --git a/III. Using Spring Boot/20.2.5. Using a Trigger File.md b/III. Using Spring Boot/20.2.5. Using a Trigger File.md new file mode 100644 index 00000000..ff9d4f6d --- /dev/null +++ b/III. Using Spring Boot/20.2.5. Using a Trigger File.md @@ -0,0 +1,7 @@ +### 20.2.5 使用触发器文件 + +如果使用一个IDE连续不断地编译变化的文件,你可能倾向于只在特定时间触发重启,触发器文件可以帮你实现该功能。触发器文件是一个特殊的文件,只有修改它才能实际触发一个重启检测。改变该文件只会触发检测,实际的重启只会在Devtools发现它必须这样做的时候。触发器文件可以手动更新,也可以通过IDE插件更新。 + +为了使用触发器文件,把`spring.devtools.restart.trigger-file`属性设置为你的触发器文件的路径。 + +**注** 你可能想将`spring.devtools.restart.trigger-file`属性设置为[全局设置](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-devtools-globalsettings),这样所有的工程表现都会相同。 diff --git a/III. Using Spring Boot/20.2.6. Customizing the Restart Classloader.md b/III. Using Spring Boot/20.2.6. Customizing the Restart Classloader.md new file mode 100644 index 00000000..32a16242 --- /dev/null +++ b/III. Using Spring Boot/20.2.6. Customizing the Restart Classloader.md @@ -0,0 +1,12 @@ +### 20.2.6 自定义restart类加载器 + +正如之前[Restart vs Reload](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-spring-boot-restart-vs-reload)章节讨论的,重启功能是通过两个类加载器实现的。对于大部分应用来说是没问题的,但有时候它可能导致类加载问题。 + +默认情况,在IDE里打开的项目会通过'restart'类加载器加载,其他常规的`.jar`文件会使用'basic'类加载器加载。如果你工作在一个多模块的项目下,并且不是每个模块都导入IDE里,你可能需要自定义一些东西。你需要创建一个`META-INF/spring-devtools.properties`文件,`spring-devtools.properties`文件可以包含`restart.exclude.`,`restart.include.`前缀的属性。`include`元素定义了那些需要加载进'restart'类加载器中的实体,`exclude`元素定义了那些需要加载进'basic'类加载器中的实体,这些属性的值是一个将应用到classpath的正则表达式。例如: +```properties +restart.include.companycommonlibs=/mycorp-common-[\\w-]+\.jar +restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar +``` +**注** 所有属性的keys必须唯一,只要以`restart.include.`或`restart.exclude.`开头都会考虑进去。 + +**注** 所有来自classpath的`META-INF/spring-devtools.properties`都会被加载,你可以将文件打包进工程或工程使用的库里。 diff --git a/III. Using Spring Boot/20.2.6. Known limitations.md b/III. Using Spring Boot/20.2.6. Known limitations.md deleted file mode 100644 index b7a4e045..00000000 --- a/III. Using Spring Boot/20.2.6. Known limitations.md +++ /dev/null @@ -1,5 +0,0 @@ -###20.2.6 已知限制 - -重启功能不能跟使用标准`ObjectInputStream`反序列化的对象工作,如果需要反序列化数据,你可能需要使用Spring的`ConfigurableObjectInputStream`,并结合`Thread.currentThread().getContextClassLoader()`。 - -不幸的是,一些第三方库反序列化时没有考虑上下文类加载器,如果发现这样的问题,你需要请求原作者给处理下。 diff --git a/III. Using Spring Boot/20.2.7. Known Limitations.md b/III. Using Spring Boot/20.2.7. Known Limitations.md new file mode 100644 index 00000000..d27a5d0c --- /dev/null +++ b/III. Using Spring Boot/20.2.7. Known Limitations.md @@ -0,0 +1,5 @@ +### 20.2.7 已知限制 + +重启功能不能跟使用标准`ObjectInputStream`反序列化的对象工作,如果需要反序列化数据,你可能需要使用Spring的`ConfigurableObjectInputStream`,并结合`Thread.currentThread().getContextClassLoader()`。 + +不幸的是,一些第三方库反序列化时没有考虑上下文类加载器,如果发现这样的问题,你需要请求原作者给处理下。 diff --git a/III. Using Spring Boot/20.3. LiveReload.md b/III. Using Spring Boot/20.3. LiveReload.md index e9be8d28..d83c6ddc 100644 --- a/III. Using Spring Boot/20.3. LiveReload.md +++ b/III. Using Spring Boot/20.3. LiveReload.md @@ -1,7 +1,7 @@ -###20.3 LiveReload +### 20.3 LiveReload `spring-boot-devtools`模块包含一个内嵌的LiveReload服务器,它可以在资源改变时触发浏览器刷新。LiveReload浏览器扩展可以免费从[livereload.com](http://livereload.com/extensions/)站点获取,支持Chrome,Firefox,Safari等浏览器。 如果不想在运行应用时启动LiveReload服务器,你可以将`spring.devtools.livereload.enabled`属性设置为false。 -**注** 每次只能运行一个LiveReload服务器。在启动应用之前,确保没有其它的LiveReload服务器正在运行。如果你在IDE中启动多个应用,只有第一个能够获得动态加载功能。 +**注** 每次只能运行一个LiveReload服务器。在启动应用之前,确保没有其它的LiveReload服务器正在运行。如果你在IDE中启动多个应用,只有第一个能够获得动态重载功能。 diff --git a/III. Using Spring Boot/20.4. Global Settings.md b/III. Using Spring Boot/20.4. Global Settings.md new file mode 100644 index 00000000..9f38d0f4 --- /dev/null +++ b/III. Using Spring Boot/20.4. Global Settings.md @@ -0,0 +1,8 @@ +### 20.4 全局设置 + +在`$HOME`文件夹下添加一个`.spring-boot-devtools.properties`的文件可以用来配置全局的devtools设置(注意文件名以"."开头),添加进该文件的任何属性都会应用到你机器上使用该devtools的Spring Boot应用。例如,想使用触发器文件进行重启,可以添加如下属性: + +**~/.spring-boot-devtools.properties.** +```properties +spring.devtools.reload.trigger-file=.reloadtrigger +``` diff --git a/III. Using Spring Boot/20.4. Global settings.md b/III. Using Spring Boot/20.4. Global settings.md deleted file mode 100644 index f1dfe24a..00000000 --- a/III. Using Spring Boot/20.4. Global settings.md +++ /dev/null @@ -1,8 +0,0 @@ -###20.4 全局设置 - -在`$HOME`文件夹下添加一个`.spring-boot-devtools.properties`的文件可以用来配置全局的devtools设置(注意文件名以"."开头),添加进该文件的任何属性都会应用到你机器上使用该devtools的Spring Boot应用。例如,想使用触发器文件进行重启,可以添加如下配置: - -~/.spring-boot-devtools.properties. -```properties -spring.devtools.reload.trigger-file=.reloadtrigger -``` diff --git a/III. Using Spring Boot/20.5. Remote Applications.md b/III. Using Spring Boot/20.5. Remote Applications.md new file mode 100644 index 00000000..6446aa43 --- /dev/null +++ b/III. Using Spring Boot/20.5. Remote Applications.md @@ -0,0 +1,23 @@ +### 20.5 远程应用 + +Spring Boot开发者工具并不仅限于本地开发,在运行远程应用时你也可以使用一些特性。远程支持是可选的。启用远程支持,你需要确保开发者工具被包含在重新打包的归档文件中。 +```properties + + + + org.springframework.boot + spring-boot-maven-plugin + + false + + + + +``` +之后,你需要通过设置`spring.devtools.remote.secret`属性启用它,例如: +```properties +spring.devtools.remote.secret=mysecret +``` +**注** 在远程应用上启用`spring-boot-devtools`有一定的安全风险,生产环境中最好不要使用。 + +远程devtools支持分两部分:一个是接收连接的服务端端点,另一个是运行在IDE里的客户端应用。如果设置`spring.devtools.remote.secret`属性,服务端组件会自动启用,客户端组件必须手动启动。 diff --git a/III. Using Spring Boot/20.5. Remote applications.md b/III. Using Spring Boot/20.5. Remote applications.md deleted file mode 100644 index c6b686b9..00000000 --- a/III. Using Spring Boot/20.5. Remote applications.md +++ /dev/null @@ -1,23 +0,0 @@ -###20.5 远程应用 - -Spring Boot开发者工具并不仅限于本地开发,在运行远程应用时你也可以使用一些特性。远程支持是可选的,你需要确保开发者工具被包含在重新打包的归档文件中。 -```properties - - - - org.springframework.boot - spring-boot-maven-plugin - - false - - - - -``` -之后,你需要通过设置`spring.devtools.remote.secret`属性启用它,例如: -```properties -spring.devtools.remote.secret=mysecret -``` -**注** 在远程应用上启用`spring-boot-devtools`有一定的安全风险,生产环境中最好不要使用。 - -远程devtools支持分两部分:一个是接收连接的服务端端点,另一个是运行在IDE里的客户端应用。如果设置`spring.devtools.remote.secret`属性,服务端组件会自动启用,客户端组件必须手动启动。 diff --git a/III. Using Spring Boot/20.5.1. Running the Remote Client Application.md b/III. Using Spring Boot/20.5.1. Running the Remote Client Application.md new file mode 100644 index 00000000..27d01a68 --- /dev/null +++ b/III. Using Spring Boot/20.5.1. Running the Remote Client Application.md @@ -0,0 +1,31 @@ +### 20.5.1 运行远程客户端应用 + +远程客户端应用程序(remote client application)需要在你的IDE中运行。你需要使用跟将要连接的远程应用相同的classpath运行`org.springframework.boot.devtools.RemoteSpringApplication`。应用需要的唯一一个参数是你要连接的远程应用URL。例如,你正在使用Eclipse或STS,并有一个部署到Cloud Foundry的`my-app`工程,远程连接该应用需要做以下操作: +* 从`Run`菜单选择`Run Configurations…`。 +* 创建一个新的`Java Application`启动配置(launch configuration)。 +* 浏览`my-app`工程。 +* 将`org.springframework.boot.devtools.RemoteSpringApplication`作为main类。 +* 将`https://myapp.cfapps.io`作为参数传递给`RemoteSpringApplication`(或其他任何远程URL)。 + +运行中的远程客户端看起来如下: +``` + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \ + \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / + =========|_|==============|___/===================================/_/_/_/ + :: Spring Boot Remote :: 2.0.0.RELEASE + +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) +``` + +**注** 因为远程客户端使用的classpath跟真实应用相同,所以它能直接读取应用配置,这就是`spring.devtools.remote.secret`如何被读取和传递给服务器做验证的。 + +强烈建议使用`https://`作为连接协议,这样传输通道是加密的,密码也不会被截获。 + +如果需要使用代理连接远程应用,你需要配置`spring.devtools.remote.proxy.host`和`spring.devtools.remote.proxy.port`属性。 diff --git a/III. Using Spring Boot/20.5.1. Running the remote client application.md b/III. Using Spring Boot/20.5.1. Running the remote client application.md deleted file mode 100644 index f205a9ca..00000000 --- a/III. Using Spring Boot/20.5.1. Running the remote client application.md +++ /dev/null @@ -1,31 +0,0 @@ -###20.5.1 运行远程客户端应用 -远程客户端应用程序(remote client application)需要在你的IDE中运行,你需要使用跟将要连接的远程应用相同的classpath运行`org.springframework.boot.devtools.RemoteSpringApplication`,传参为你要连接的远程应用URL。例如,你正在使用Eclipse或STS,并有一个部署到Cloud Foundry的`my-app`工程,远程连接该应用需要做以下操作: -* 从`Run`菜单选择`Run Configurations…`。 -* 创建一个新的`Java Application`启动配置(launch configuration)。 -* 浏览`my-app`工程。 -* 将`org.springframework.boot.devtools.RemoteSpringApplication`作为main类。 -* 将`https://myapp.cfapps.io`作为参数传递给`RemoteSpringApplication`(或其他任何远程URL)。 - -运行中的远程客户端看起来如下: -```shell - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ -( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \ - \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / - =========|_|==============|___/===================================/_/_/_/ - :: Spring Boot Remote :: 2.0.0.M5 - -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) -``` - -**注** 因为远程客户端使用的classpath跟真实应用相同,所以它能直接读取应用配置,这就是`spring.devtools.remote.secret`如何被读取和传递给服务器做验证的。 - -强烈建议使用`https://`作为连接协议,这样传输通道是加密的,密码也不会被截获。 - -如果需要使用代理连接远程应用,你需要配置`spring.devtools.remote.proxy.host`和`spring.devtools.remote.proxy.port`属性。 - diff --git a/III. Using Spring Boot/20.5.2. Remote Update.md b/III. Using Spring Boot/20.5.2. Remote Update.md new file mode 100644 index 00000000..d9bf0017 --- /dev/null +++ b/III. Using Spring Boot/20.5.2. Remote Update.md @@ -0,0 +1,5 @@ +### 20.5.2 远程更新 + +远程客户端将监听应用的classpath变化。任何更新的资源都会发布到远程应用,并触发重启。这在你使用云服务迭代某个特性时非常有用。通常远程更新和重启比完整rebuild和deploy快多了。 + +**注** 文件只有在远程客户端运行时才监控。如果你在启动远程客户端之前改变一个文件,它是不会被发布到远程server的。 diff --git a/III. Using Spring Boot/20.5.2. Remote update.md b/III. Using Spring Boot/20.5.2. Remote update.md deleted file mode 100644 index 6c3b7f69..00000000 --- a/III. Using Spring Boot/20.5.2. Remote update.md +++ /dev/null @@ -1,4 +0,0 @@ -###20.5.2 远程更新 -远程客户端将监听应用的classpath变化,任何更新的资源都会发布到远程应用,并触发重启,这在你使用云服务迭代某个特性时非常有用。通常远程更新和重启比完整rebuild和deploy快多了。 - -**注** 文件只有在远程客户端运行时才监控。如果你在启动远程客户端之前改变一个文件,它是不会被发布到远程server的。 diff --git a/III. Using Spring Boot/21. Packaging your application for production.md b/III. Using Spring Boot/21. Packaging Your Application for Production.md similarity index 100% rename from III. Using Spring Boot/21. Packaging your application for production.md rename to III. Using Spring Boot/21. Packaging Your Application for Production.md diff --git a/III. Using Spring Boot/22. What to Read Next.md b/III. Using Spring Boot/22. What to Read Next.md new file mode 100644 index 00000000..79f7e020 --- /dev/null +++ b/III. Using Spring Boot/22. What to Read Next.md @@ -0,0 +1,3 @@ +### 22. 接下来阅读什么 + +现在你应该明白怎么结合最佳实践使用Spring Boot,接下来可以深入学习特殊的部分[Spring Boot特性](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features),或者你可以跳过开头,阅读Spring Boot的[production ready](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready)部分。 diff --git a/III. Using Spring Boot/22. What to read next.md b/III. Using Spring Boot/22. What to read next.md deleted file mode 100644 index 196f025d..00000000 --- a/III. Using Spring Boot/22. What to read next.md +++ /dev/null @@ -1,2 +0,0 @@ -### 22. 接下来阅读什么 -现在你应该明白怎么结合最佳实践使用Spring Boot,接下来可以深入学习特殊的部分[Spring Boot features](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features),或者你可以跳过开头,阅读Spring Boot的[production ready](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#production-ready)部分。 diff --git a/IV. Spring Boot features/23. SpringApplication.md b/IV. Spring Boot features/23. SpringApplication.md index 6f53dc15..da829b86 100644 --- a/IV. Spring Boot features/23. SpringApplication.md +++ b/IV. Spring Boot features/23. SpringApplication.md @@ -1,5 +1,6 @@ -###23. SpringApplication -SpringApplication类提供了一种快捷方式,用于从`main()`方法启动Spring应用。多数情况下,你只需要将该任务委托给`SpringApplication.run`静态方法: +### 23. SpringApplication + +SpringApplication类提供了一种快捷方式,用于从`main()`方法启动Spring应用。多数情况下,你可以将该任务委托给`SpringApplication.run`静态方法: ```java public static void main(String[] args){ SpringApplication.run(MySpringConfiguration.class, args); @@ -13,11 +14,11 @@ public static void main(String[] args){ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: v2.0.0.M5 + :: Spring Boot :: v2.0.0.RELEASE 2013-07-31 00:08:16.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb) 2013-07-31 00:08:16.166 INFO 56603 --- [ main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy 2014-03-04 13:09:54.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080 2014-03-04 13:09:56.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658) ``` -默认情况下会显示INFO级别的日志信息,包括一些相关的启动详情,比如启动应用的用户等。 +默认情况下会显示`INFO`级别的日志信息,包括一些相关的启动详情,比如启动应用的用户等。如果你需要`INFO`之外的日志级别,你可以参考[章节 26.4 日志级别](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-custom-log-levels)进行设置。 diff --git a/IV. Spring Boot features/23.1. Startup Failure.md b/IV. Spring Boot features/23.1. Startup Failure.md new file mode 100644 index 00000000..15cdde23 --- /dev/null +++ b/IV. Spring Boot features/23.1. Startup Failure.md @@ -0,0 +1,24 @@ +### 23.1 启动失败 + +如果应用启动失败,注册的`FailureAnalyzers`就有机会提供一个特定的错误信息,及具体的解决该问题的动作。例如,如果在`8080`端口启动一个web应用,而该端口已被占用,那你应该可以看到类似如下的信息: +```properties +*************************** +APPLICATION FAILED TO START +*************************** + +Description: + +Embedded servlet container failed to start. Port 8080 was already in use. + +Action: + +Identify and stop the process that's listening on port 8080 or configure this application to listen on another port. +``` +**注** Spring Boot提供很多的`FailureAnalyzer`实现。你也可以[自己实现](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-failure-analyzer)。 + +如果没有可用于处理该异常的失败分析器(failure analyzers),你需要展示完整的情况报告以便更好的查看出问题的地方,因此你需要启用`org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener`的[debug](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config)属性,或开启[DEBUG日志级别](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-custom-log-levels)。 + +例如,使用`java -jar`运行应用时,你可以通过如下命令启用`debug`属性: +```shell +$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug +``` diff --git a/IV. Spring Boot features/23.1. Startup failure.md b/IV. Spring Boot features/23.1. Startup failure.md deleted file mode 100644 index 10532436..00000000 --- a/IV. Spring Boot features/23.1. Startup failure.md +++ /dev/null @@ -1,23 +0,0 @@ -###23.1 启动失败 -如果应用启动失败,注册的`FailureAnalyzers`就有机会提供一个特定的错误信息,及具体的解决该问题的动作。例如,如果在`8080`端口启动一个web应用,而该端口已被占用,那你应该可以看到类似如下的内容: -```properties -*************************** -APPLICATION FAILED TO START -*************************** - -Description: - -Embedded servlet container failed to start. Port 8080 was already in use. - -Action: - -Identify and stop the process that's listening on port 8080 or configure this application to listen on another port. -``` -**注** Spring Boot提供很多的`FailureAnalyzer`实现,你[自己实现](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-failure-analyzer)也很容易。 - -如果没有可用于处理该异常的失败分析器(failure analyzers),你需要展示完整的auto-configuration报告以便更好的查看出问题的地方,因此你需要启用`org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer`的[debug](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config)属性,或开启[DEBUG日志级别](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-custom-log-levels)。 - -例如,使用`java -jar`运行应用时,你可以通过如下命令启用`debug`属性: -```shell -$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug -``` diff --git a/IV. Spring Boot features/23.10. Admin Features.md b/IV. Spring Boot features/23.10. Admin Features.md new file mode 100644 index 00000000..b12d8cb3 --- /dev/null +++ b/IV. Spring Boot features/23.10. Admin Features.md @@ -0,0 +1,7 @@ +### 23.10 Admin特性 + +通过设置`spring.application.admin.enabled`属性可以启用管理相关的(admin-related)特性,这将暴露[SpringApplicationAdminMXBean](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBean.java)到平台的`MBeanServer`,你可以使用该特性远程管理Spring Boot应用。这个特性对任何service包装器(wrapper)实现也有用。 + +**注** 通过`local.server.port`可以获取该应用运行的HTTP端口。 + +**警告** 启用该特性时需要注意MBean会暴露一个方法去关闭应用。 diff --git a/IV. Spring Boot features/23.10. Admin features.md b/IV. Spring Boot features/23.10. Admin features.md deleted file mode 100644 index e9cc1174..00000000 --- a/IV. Spring Boot features/23.10. Admin features.md +++ /dev/null @@ -1,6 +0,0 @@ -### 23.10 Admin特性 - -通过设置`spring.application.admin.enabled`属性可以启用管理相关的(admin-related)特性,这将暴露[SpringApplicationAdminMXBean](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBean.java)到平台的`MBeanServer`,你可以使用该特性远程管理Spring Boot应用,这对任何service包装器(wrapper)实现也有用。 - -**注** 通过`local.server.port`可以获取该应用运行的HTTP端口。启用该特性时需要注意MBean会暴露一个方法去关闭应用。 - diff --git a/IV. Spring Boot features/23.2. Customizing the Banner.md b/IV. Spring Boot features/23.2. Customizing the Banner.md index b249cd64..ef6722a5 100644 --- a/IV. Spring Boot features/23.2. Customizing the Banner.md +++ b/IV. Spring Boot features/23.2. Customizing the Banner.md @@ -1,6 +1,6 @@ ### 23.2. 自定义Banner -通过在classpath下添加一个`banner.txt`或设置`banner.location`来指定相应的文件可以改变启动过程中打印的banner。如果这个文件有特殊的编码,你可以使用`banner.encoding`设置它(默认为UTF-8)。除了文本文件,你也可以添加一个`banner.gif`,`banner.jpg`或`banner.png`图片,或设置`banner.image.location`属性。图片会转换为字符画(ASCII art)形式,并在所有文本banner上方显示。 +通过在classpath下添加一个`banner.txt`或设置`spring.banner.location`属性来指定相应的文件,可以改变启动过程中打印的banner。如果这个文件不是以UTF-8编码,你可以设置`spring.banner.charset`。除了文本文件,你也可以添加一个`banner.gif`,`banner.jpg`或`banner.png`图片,或设置`spring.banner.image.location`属性。图片会转换为字符画(ASCII art)形式,并在所有文本banner上方显示。 在banner.txt中可以使用如下占位符: @@ -8,9 +8,9 @@ | ----------- | :--------| |${application.version}|MANIFEST.MF中声明的应用版本号,例如`Implementation-Version: 1.0`会打印`1.0`| |${application.formatted-version}|MANIFEST.MF中声明的被格式化后的应用版本号(被括号包裹且以v作为前缀),用于显示,例如(`v1.0`)| -|${spring-boot.version}|当前Spring Boot的版本号,例如`2.0.0.M5`| -|${spring-boot.formatted-version}|当前Spring Boot被格式化后的版本号(被括号包裹且以v作为前缀), 用于显示,例如(`v2.0.0.M5`)| -|${Ansi.NAME}(或${AnsiColor.NAME},${AnsiBackground.NAME}, ${AnsiStyle.NAME})|NAME代表一种ANSI编码,具体详情查看[AnsiPropertySource](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java)| +|${spring-boot.version}|当前Spring Boot的版本号,例如`2.0.0.RELEASE`| +|${spring-boot.formatted-version}|当前Spring Boot被格式化后的版本号(被括号包裹且以v作为前缀), 用于显示,例如(`v2.0.0.RELEASE`)| +|${Ansi.NAME}(或${AnsiColor.NAME},${AnsiBackground.NAME}, ${AnsiStyle.NAME})|NAME代表一种ANSI编码,具体详情查看[AnsiPropertySource](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java)| |${application.title}|`MANIFEST.MF`中声明的应用title,例如`Implementation-Title: MyApp`会打印`MyApp`| **注** 如果想以编程的方式产生一个banner,可以使用`SpringBootApplication.setBanner(…)`方法,并实现`org.springframework.boot.Banner`接口的`printBanner()`方法。 @@ -19,7 +19,7 @@ 打印的banner将注册成一个名为`springBootBanner`的单例bean。 -**注** YAML会将`off`映射为`false`,如果想在应用中禁用banner,你需要确保`off`添加了括号: +**注** YAML会将`off`映射为`false`,如果想在应用中禁用banner,你需要确保`off`添加了引号: ```json spring: main: diff --git a/IV. Spring Boot features/23.3. Customizing SpringApplication.md b/IV. Spring Boot features/23.3. Customizing SpringApplication.md index 63033d20..9bd19920 100644 --- a/IV. Spring Boot features/23.3. Customizing SpringApplication.md +++ b/IV. Spring Boot features/23.3. Customizing SpringApplication.md @@ -8,6 +8,6 @@ public static void main(String[] args) { app.run(args); } ``` -**注**:传递给`SpringApplication`的构造器参数将作为spring beans的配置源,多数情况下,它们是一些`@Configuration`类的引用,但也可能是XML配置或要扫描包的引用。 +**注**:传递给`SpringApplication`的构造器参数将作为Spring bean的配置源,多数情况下,它们是一些`@Configuration`类的引用,但也可能是XML配置或要扫描包的引用。 -你也可以使用`application.properties`文件来配置`SpringApplication`,具体参考[24. Externalized 配置](24. Externalized Configuration.md),访问[SpringApplication Javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/SpringApplication.html)可获取完整的配置选项列表. +你也可以使用`application.properties`文件来配置`SpringApplication`,具体参考[24. Externalized 配置](24. Externalized Configuration.md),访问[SpringApplication Javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/SpringApplication.html)可获取完整的配置选项列表. diff --git a/IV. Spring Boot features/23.4. Fluent Builder API.md b/IV. Spring Boot features/23.4. Fluent Builder API.md new file mode 100644 index 00000000..0dc4f7ef --- /dev/null +++ b/IV. Spring Boot features/23.4. Fluent Builder API.md @@ -0,0 +1,12 @@ +### 23.4. 流式构建API + +如果需要创建一个分层的`ApplicationContext`(多个具有父子关系的上下文),或喜欢使用流式(fluent)构建API,那你可以使用SpringApplicationBuilder。 +SpringApplicationBuilder让你以链式方式调用多个方法,包括parent和child方法,这样就可以创建多层次结构,例如: +```java +new SpringApplicationBuilder() + .sources(Parent.class) + .child(Application.class) + .bannerMode(Banner.Mode.OFF) + .run(args); +``` +**注**:创建ApplicationContext层次时有些限制。比如,Web组件必须包含在子上下文中,并且父上下文和子上下文使用相同的Environment。具体参考[SpringApplicationBuilder javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/builder/SpringApplicationBuilder.html)。 diff --git a/IV. Spring Boot features/23.4. Fluent builder API.md b/IV. Spring Boot features/23.4. Fluent builder API.md deleted file mode 100644 index 12127154..00000000 --- a/IV. Spring Boot features/23.4. Fluent builder API.md +++ /dev/null @@ -1,12 +0,0 @@ -### 23.4. 流式构建API - -如果需要创建一个分层的`ApplicationContext`(多个具有父子关系的上下文),或只是喜欢使用流式(fluent)构建API,那你可以使用SpringApplicationBuilder。 -SpringApplicationBuilder允许你以链式方式调用多个方法,包括parent和child方法,这样就可以创建多层次结构,例如: -```java -new SpringApplicationBuilder() - .sources(Parent.class) - .child(Application.class) - .bannerMode(Banner.Mode.OFF) - .run(args); -``` -**注**:创建ApplicationContext层次时有些限制,比如,Web组件必须包含在子上下文中,并且父上下文和子上下文使用相同的Environment,具体参考[SpringApplicationBuilder javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/builder/SpringApplicationBuilder.html)。 diff --git a/IV. Spring Boot features/23.5. Application Events and Listeners.md b/IV. Spring Boot features/23.5. Application Events and Listeners.md new file mode 100644 index 00000000..093926b3 --- /dev/null +++ b/IV. Spring Boot features/23.5. Application Events and Listeners.md @@ -0,0 +1,23 @@ +### 23.5. 应用事件和监听器 + +除了常见的Spring框架事件,比如[ContextRefreshedEvent](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html),`SpringApplication`也会发送其他的应用事件。 + +**注** 有些事件实际上是在`ApplicationContext`创建前触发的,所以你不能在那些事件(处理类)中通过`@Bean`注册监听器,只能通过`SpringApplication.addListeners(…)`或`SpringApplicationBuilder.listeners(…)`方法注册。如果想让监听器自动注册,而不关心应用的创建方式,你可以在工程中添加一个`META-INF/spring.factories`文件,并使用`org.springframework.context.ApplicationListener`作为key指向那些监听器,如下: +```properties +org.springframework.context.ApplicationListener=com.example.project.MyListener +``` + +应用运行时,事件会以下面的次序发送: + +1. 在运行开始,但除了监听器注册和初始化以外的任何处理之前,会发送一个`ApplicationStartingEvent`。 +2. 在Environment将被用于已知的上下文,但在上下文被创建前,会发送一个`ApplicationEnvironmentPreparedEvent`。 +3. 在refresh开始前,但在bean定义已被加载后,会发送一个`ApplicationPreparedEvent`。 +4. 在上下文更新后,但在任何应用和命令行运行器被调用前,会发送一个`ApplicationStartedEvent`。 +5. 在任何应用和命令行运行器被调用后,会发送一个`ApplicationReadyEvent`,表示应用准备好接收请求了。 +6. 启动过程中如果出现异常,会发送一个`ApplicationFailedEvent`。 + +**注** 通常不需要使用应用事件,但知道它们的存在是有用的(在某些场合可能会使用到),比如,在Spring Boot内部会使用事件处理各种任务。 + +应用事件通过Spring框架的事件发布机制发送。此机制的一部分确保了一个发布到子上下文里的监听器的事件,也会发布到任何祖先上下文里的监听器。因此,如果你的应用使用`SpringApplication`实例的层级,监听器可能会接收到应用事件的多个相同类型的实例。 + +为了让你的监听器区分一个事件是对应它的上下文还是子孙上下文,它应当请求它的应用上下文被注入,然后比较注入的上下文与事件的上下文。上下文可以通过实现`ApplicationContextAware`注入。或者,如果监听器是一个bean,可以使用`@Autowired`。 diff --git a/IV. Spring Boot features/23.5. Application events and listeners.md b/IV. Spring Boot features/23.5. Application events and listeners.md deleted file mode 100644 index 056a92e7..00000000 --- a/IV. Spring Boot features/23.5. Application events and listeners.md +++ /dev/null @@ -1,18 +0,0 @@ -### 23.5. Application事件和监听器 - -除了常见的Spring框架事件,比如[ContextRefreshedEvent](https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html),`SpringApplication`也会发送其他的application事件。 - -**注** 有些事件实际上是在`ApplicationContext`创建前触发的,所以你不能在那些事件(处理类)中通过`@Bean`注册监听器,只能通过`SpringApplication.addListeners(…)`或`SpringApplicationBuilder.listeners(…)`方法注册。如果想让监听器自动注册,而不关心应用的创建方式,你可以在工程中添加一个`META-INF/spring.factories`文件,并使用`org.springframework.context.ApplicationListener`作为key指向那些监听器,如下: -```properties -org.springframework.context.ApplicationListener=com.example.project.MyListener -``` - -应用运行时,事件会以下面的次序发送: - -1. 在运行开始,但除了监听器注册和初始化以外的任何处理之前,会发送一个`ApplicationStartingEvent`。 -2. 在Environment将被用于已知的上下文,但在上下文被创建前,会发送一个`ApplicationEnvironmentPreparedEvent`。 -3. 在refresh开始前,但在bean定义已被加载后,会发送一个`ApplicationPreparedEvent`。 -4. 在refresh之后,相关的回调处理完,会发送一个`ApplicationReadyEvent`,表示应用准备好接收请求了。 -4. 启动过程中如果出现异常,会发送一个`ApplicationFailedEvent`。 - -**注** 通常不需要使用application事件,但知道它们的存在是有用的(在某些场合可能会使用到),比如,在Spring Boot内部会使用事件处理各种任务。 diff --git a/IV. Spring Boot features/23.6. Web environment.md b/IV. Spring Boot features/23.6. Web Environment.md similarity index 100% rename from IV. Spring Boot features/23.6. Web environment.md rename to IV. Spring Boot features/23.6. Web Environment.md diff --git a/IV. Spring Boot features/23.7. Accessing application arguments.md b/IV. Spring Boot features/23.7. Accessing Application Arguments.md similarity index 100% rename from IV. Spring Boot features/23.7. Accessing application arguments.md rename to IV. Spring Boot features/23.7. Accessing Application Arguments.md diff --git a/IV. Spring Boot features/23.8. Using the ApplicationRunner or CommandLineRunner.md b/IV. Spring Boot features/23.8. Using the ApplicationRunner or CommandLineRunner.md index 29531eed..67d86c21 100644 --- a/IV. Spring Boot features/23.8. Using the ApplicationRunner or CommandLineRunner.md +++ b/IV. Spring Boot features/23.8. Using the ApplicationRunner or CommandLineRunner.md @@ -2,7 +2,7 @@ 如果需要在`SpringApplication`启动后执行一些特殊的代码,你可以实现`ApplicationRunner`或`CommandLineRunner`接口,这两个接口工作方式相同,都只提供单一的`run`方法,该方法仅在`SpringApplication.run(…)`完成之前调用。 -`CommandLineRunner`接口能够访问string数组类型的应用参数,而`ApplicationRunner`使用的是上面描述过的`ApplicationArguments`接口: +`CommandLineRunner`接口能够访问string数组类型的应用参数,而`ApplicationRunner`使用的是之前描述过的`ApplicationArguments`接口: ```java import org.springframework.boot.* import org.springframework.stereotype.* diff --git a/IV. Spring Boot features/23.9. Application Exit.md b/IV. Spring Boot features/23.9. Application Exit.md new file mode 100644 index 00000000..309c8417 --- /dev/null +++ b/IV. Spring Boot features/23.9. Application Exit.md @@ -0,0 +1,22 @@ +### 23.9 应用退出 + +为确保`ApplicationContext`在退出时被平静的(gracefully)关闭,每个`SpringApplication`都会注册一个JVM的shutdown钩子,所有标准的Spring生命周期回调(比如`DisposableBean`接口或`@PreDestroy`注解)都能使用。 + +此外,如果想在`SpringApplication.exit()`被调用时返回特定的退出码(exit code),这些beans可以实现`org.springframework.boot.ExitCodeGenerator`接口。这个退出码之后会被传递到`System.exit()`,作为状态码返回。 +```java +@SpringBootApplication +public class ExitCodeApplication { + + @Bean + public ExitCodeGenerator exitCodeGenerator() { + return () -> 42; + } + + public static void main(String[] args) { + System.exit(SpringApplication + .exit(SpringApplication.run(ExitCodeApplication.class, args))); + } + +} +``` +`ExitCodeGenerator`接口也可以被异常实现。当遇到这样的一个异常,Spring Boot将返回由被实现了的`getExitCode()`方法提供的退出码。 diff --git a/IV. Spring Boot features/23.9. Application exit.md b/IV. Spring Boot features/23.9. Application exit.md deleted file mode 100644 index 55b14ea7..00000000 --- a/IV. Spring Boot features/23.9. Application exit.md +++ /dev/null @@ -1,22 +0,0 @@ -### 23.9 Application退出 - -为确保`ApplicationContext`在退出时被平静的(gracefully)关闭,每个`SpringApplication`都会注册一个JVM的shutdown钩子,所有标准的Spring生命周期回调(比如`DisposableBean`接口或`@PreDestroy`注解)都能使用。 - -此外,如果想在`SpringApplication.exit()`被调用时返回特定的退出码(exit code),这些beans可以实现`org.springframework.boot.ExitCodeGenerator`接口。这个退出码之后会被传递到`System.exit()`,作为状态码返回。 -```java -@SpringBootApplication -public class ExitCodeApplication { - - @Bean - public ExitCodeGenerator exitCodeGenerator() { - return () -> 42; - } - - public static void main(String[] args) { - System.exit(SpringApplication - .exit(SpringApplication.run(ExitCodeApplication.class, args))); - } - -} -``` -`ExitCodeGenerator`接口也可以被异常实现。当遇到这样的一个异常,Spring Boot将返回由被实现了的`getExitCode()`方法提供的退出码。 \ No newline at end of file diff --git a/IV. Spring Boot features/24. Externalized Configuration.md b/IV. Spring Boot features/24. Externalized Configuration.md index 73bfe7d3..e612de08 100644 --- a/IV. Spring Boot features/24. Externalized Configuration.md +++ b/IV. Spring Boot features/24. Externalized Configuration.md @@ -1,12 +1,12 @@ ### 24.外部化配置 -Spring Boot允许将配置外部化(externalize),这样你就能够在不同的环境下使用相同的代码。你可以使用properties文件,YAML文件,环境变量和命令行参数来外部化配置。使用@Value注解,可以直接将属性值注入到beans中,然后通过Spring的`Environment`抽象或通过`@ConfigurationProperties`[绑定到结构化对象](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties)来访问。 +Spring Boot允许将配置外部化(externalize),这样你就能够在不同的环境下使用相同的代码。你可以使用properties文件,YAML文件,环境变量和命令行参数来外部化配置。使用@Value注解,可以直接将属性值注入到beans中,然后通过Spring的`Environment`抽象或通过`@ConfigurationProperties`[绑定到结构化对象](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties)来访问。 Spring Boot设计了一个非常特别的`PropertySource`顺序,以允许对属性值进行合理的覆盖,属性会以如下的顺序进行设值: -1. home目录下的[devtools全局设置属性](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#using-boot-devtools-globalsettings)(`~/.spring-boot-devtools.properties`,如果devtools激活)。 -2. 测试用例上的[@TestPropertySource](https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html)注解。 -3. 测试用例上的[@SpringBootTest#properties](http://docs.spring.io/spring-boot/docs/2.0.0.M5/api/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTest.html)注解。 +1. home目录下的[devtools全局设置属性](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-devtools-globalsettings)(`~/.spring-boot-devtools.properties`,如果devtools激活)。 +2. 测试用例上的[@TestPropertySource](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html)注解。 +3. 测试用例上的[@SpringBootTest#properties](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTest.html)注解。 4. 命令行参数 5. 来自`SPRING_APPLICATION_JSON`的属性(环境变量或系统属性中内嵌的内联JSON)。 6. `ServletConfig`初始化参数。 @@ -15,12 +15,12 @@ Spring Boot设计了一个非常特别的`PropertySource`顺序,以允许对 9. Java系统属性(System.getProperties())。 10. 操作系统环境变量。 11. RandomValuePropertySource,只包含`random.*`中的属性。 -12. 没有打进jar包的[Profile-specific应用属性](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-profile-specific-properties)(`application-{profile}.properties`和YAML变量)。 -13. 打进jar包中的[Profile-specific应用属性](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-profile-specific-properties)(`application-{profile}.properties`和YAML变量)。 +12. 没有打进jar包的[Profile-specific应用属性](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-profile-specific-properties)(`application-{profile}.properties`和YAML变量)。 +13. 打进jar包中的[Profile-specific应用属性](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-profile-specific-properties)(`application-{profile}.properties`和YAML变量)。 14. 没有打进jar包的应用配置(`application.properties`和YAML变量)。 15. 打进jar包中的应用配置(`application.properties`和YAML变量)。 -16. `@Configuration`类上的[`@PropertySource`注解](https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/org/springframework/context/annotation/PropertySource.html)。 -17. 默认属性(使用`SpringApplication.setDefaultProperties`指定)。 +16. `@Configuration`类上的[`@PropertySource`注解](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/PropertySource.html)。 +17. 默认属性(通过设置`SpringApplication.setDefaultProperties`指定)。 下面是具体的示例,假设你开发一个使用name属性的`@Component`: ```java @@ -38,14 +38,14 @@ public class MyBean { **注** `SPRING_APPLICATION_JSON`属性可以通过命令行的环境变量设置,例如,在一个UNIX shell中可以这样: ```shell -$ SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar +$ SPRING_APPLICATION_JSON='{"acme":{"name":"test"}}' java -jar myapp.jar ``` -本示例中,如果是Spring `Environment`,你可以以`foo.bar=spam`结尾;如果在一个系统变量中,可以提供作为`spring.application.json`的JSON字符串: +在之前的例子里,如果是Spring `Environment`,你可以以`acme.name=test`结尾;如果在一个系统属性中,可以提供作为`spring.application.json`的JSON字符串: ```shell -$ java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar +$ java -Dspring.application.json='{"name":"test"}' -jar myapp.jar ``` 或命令行参数: ```shell -$ java -jar myapp.jar --spring.application.json='{"foo":"bar"}' +$ java -jar myapp.jar --spring.application.json='{"name":"test"}' ``` 或作为一个JNDI变量`java:comp/env/spring.application.json`。 diff --git a/IV. Spring Boot features/24.1. Configuring random values.md b/IV. Spring Boot features/24.1. Configuring Random Values.md similarity index 100% rename from IV. Spring Boot features/24.1. Configuring random values.md rename to IV. Spring Boot features/24.1. Configuring Random Values.md diff --git a/IV. Spring Boot features/24.2. Accessing Command Line Properties.md b/IV. Spring Boot features/24.2. Accessing Command Line Properties.md new file mode 100644 index 00000000..3412354a --- /dev/null +++ b/IV. Spring Boot features/24.2. Accessing Command Line Properties.md @@ -0,0 +1,5 @@ +### 24.2. 访问命令行属性 + +默认情况下,`SpringApplication`会将所有命令行配置参数(以--开头,比如`--server.port=9000`)转化成一个`property`,并将其添加到Spring `Environment`中。正如以上章节提过的,命令行属性总是优先于其他属性源。 + +如果不想将命令行属性添加到`Environment`,你可以使用`SpringApplication.setAddCommandLineProperties(false)`来禁用它们。 diff --git a/IV. Spring Boot features/24.2. Accessing command line properties.md b/IV. Spring Boot features/24.2. Accessing command line properties.md deleted file mode 100644 index 3f2354bc..00000000 --- a/IV. Spring Boot features/24.2. Accessing command line properties.md +++ /dev/null @@ -1,5 +0,0 @@ -### 24.2. 访问命令行属性 - -默认情况下,`SpringApplication`会将所有命令行配置参数(以'--'开头,比如`--server.port=9000`)转化成一个`property`,并将其添加到Spring `Environment`中。正如以上章节提过的,命令行属性总是优先于其他属性源。 - -如果不想将命令行属性添加到`Environment`,你可以使用`SpringApplication.setAddCommandLineProperties(false)`来禁用它们。 diff --git a/IV. Spring Boot features/24.3. Application Property Files.md b/IV. Spring Boot features/24.3. Application Property Files.md new file mode 100644 index 00000000..d182ab84 --- /dev/null +++ b/IV. Spring Boot features/24.3. Application Property Files.md @@ -0,0 +1,51 @@ +### 24.3. 应用属性文件 + +`SpringApplication`从以下位置加载`application.properties`文件,并把它们添加到Spring `Environment`中: + +1. 当前目录下的`/config`子目录 +2. 当前目录 +3. classpath下的`/config`包 +4. classpath根路径(root) + +该列表是按优先级排序的(列表中位置高的路径下定义的属性将覆盖位置低的)。 + +**注** 你可以使用[YAML('.yml')文件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-yaml)替代'.properties'。 + +如果不喜欢将`application.properties`作为配置文件名,你可以通过指定`spring.config.name`环境属性来切换其它的文件名,也可以使用`spring.config.location`环境属性引用一个明确的路径(目录位置或文件路径列表以逗号分割)。下面的例子展示了怎么指定一个不同的文件名: +```shell +$ java -jar myproject.jar --spring.config.name=myproject +``` +下面的例子展示了怎么指定两个路径: +```shell +$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties +``` +**注** 在初期需要根据`spring.config.name`和`spring.config.location`决定加载哪个文件,所以它们必须定义为环境属性(通常为OS环境变量,系统属性或命令行参数)。 + +如果`spring.config.location`包含目录(相对于文件),那它们应该以`/`结尾(运行时,`spring.config.name`关联的名称会在被加载前被追加到后面,包括profile-specific的文件名)。`spring.config.location`下定义的文件使用方法跟往常一样,没有profile-specific变量支持的属性,会被profile-specific的属性覆盖。 + +配置位置按相反的顺序搜索。默认地,配置好的位置是`classpath:/,classpath:/config/,file:./,file:./config/`。产生的搜索顺序为: + +1. `file:./config/` +2. `file:./` +3. `classpath:/config/` +4. `classpath:/` + +当使用`spring.config.location`配置好自定义的配置位置时,它们会代替默认位置。比如,如果用值`classpath:/custom-config/,file:./custom-config/`配置了`spring.config.location`,搜索顺序会变成: + +1. `file:./custom-config/` +2. `classpath:custom-config/` + +或者,当使用`spring.config.additional-location`配置好自定义的配置位置时,,它们会在默认位置的基础上被使用。自定义的位置会在默认位置之前被搜索。例如,如果配置了自定义的位置`classpath:/custom-config/,file:./custom-config/`,搜索的顺序会变成: + +1. `file:./custom-config/` +2. `classpath:custom-config/` +3. `file:./config/` +4. `file:./` +5. `classpath:/config/` +6. `classpath:/` + +这种搜索排序允许你在一个配置文件里指定默认值,然后有选择地覆盖那些值。你可以选择默认位置中的一处,在这儿的`application.properties`(或者任何由`spring.config.name`指定的名字)里为应用设置默认值。然后,在运行时使用在自定义的位置上的不同的文件,覆盖这些默认值。 + +**注** 如果使用环境变量而不是系统属性,需要注意多数操作系统的key名称不允许以句号分割(period-separated),但你可以使用下划线(underscores)代替(比如,使用`SPRING_CONFIG_NAME`代替`spring.config.name`)。 + +**注** 如果你的应用运行在容器中,那么JNDI属性(java:comp/env)或servlet上下文初始化参数可以用来代替环境变量或系统属性,当然也可以使用环境变量或系统属性。 diff --git a/IV. Spring Boot features/24.3. Application property files.md b/IV. Spring Boot features/24.3. Application property files.md deleted file mode 100644 index 30906df0..00000000 --- a/IV. Spring Boot features/24.3. Application property files.md +++ /dev/null @@ -1,46 +0,0 @@ -### 24.3. Application属性文件 - -`SpringApplication`将从以下位置加载`application.properties`文件,并把它们添加到Spring `Environment`中: - -1. 当前目录下的`/config`子目录。 -2. 当前目录。 -3. classpath下的`/config`包。 -4. classpath根路径(root)。 - -该列表是按优先级排序的(列表中位置高的路径下定义的属性将覆盖位置低的)。 - -**注** 你可以使用[YAML('.yml')文件](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-yaml)替代'.properties'。 - -如果不喜欢将`application.properties`作为配置文件名,你可以通过指定`spring.config.name`环境属性来切换其他的名称,也可以使用`spring.config.location`环境属性引用一个明确的路径(目录位置或文件路径列表以逗号分割)。 -```shell -$ java -jar myproject.jar --spring.config.name=myproject -``` -或 -```shell -$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties -``` -**注** 在初期需要根据`spring.config.name`和`spring.config.location`决定加载哪个文件,所以它们必须定义为environment属性(通常为OS env,系统属性或命令行参数)。 - -如果`spring.config.location`包含目录(相对于文件),那它们应该以`/`结尾(在被加载前,`spring.config.name`关联的名称将被追加到后面,包括profile-specific的文件名)。`spring.config.location`下定义的文件使用方法跟往常一样,没有profile-specific变量支持的属性,将被profile-specific的属性覆盖。 - -配置位置按相反的顺序搜索。默认地,配置好的位置是`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:/` - -这种搜索排序允许你在一个配置文件里指定默认值,然后有选择地覆盖那些值。你可以选择默认位置中的一处,在这儿的`application.properties`(或者任何由`spring.config.name`指定的名字)里为应用设置默认值。然后,在运行时使用在自定义的位置上的不同的文件,覆盖这些默认值。 - -**注** 如果使用环境变量而不是系统属性,需要注意多数操作系统的key名称不允许以句号分割(period-separated),但你可以使用下划线(underscores)代替(比如,使用`SPRING_CONFIG_NAME`代替`spring.config.name`)。 - -**注** 如果应用运行在容器中,那么JNDI属性(java:comp/env)或servlet上下文初始化参数可以用来代替环境变量或系统属性,当然也可以使用环境变量或系统属性。 diff --git a/IV. Spring Boot features/24.4. Profile-specific Properties.md b/IV. Spring Boot features/24.4. Profile-specific Properties.md new file mode 100644 index 00000000..1618d4bb --- /dev/null +++ b/IV. Spring Boot features/24.4. Profile-specific Properties.md @@ -0,0 +1,9 @@ +### 24.4. Profile-specific属性 + +除了`application.properties`文件,profile-specific属性也能通过命名惯例`application-{profile}.properties`定义。`Environment`(Spring的环境抽象接口)有个默认profiles集合(默认情况为`[default]`),在没有设置激活的profiles时会被使用。换句话说,如果没有明确指定激活的profiles,`application-default.properties`中的属性会被加载。 + +Profile-specific属性加载路径和标准的`application.properties`相同,并且profile-specific文件总是会覆盖non-specific文件,不管profile-specific文件是否被打包到jar中。 + +如果定义多个profiles,最后一个将获胜。例如,`spring.profiles.active`定义的profiles被添加到通过`SpringApplication`API定义的profiles后面,因此优先级更高。 + +**注** 如果你已经在`spring.config.location`下定义所有文件(非目录),那些profile-specific的文件将不被考虑。如果想使用profile-specific属性,那就在`spring.config.location`下使用目录。 diff --git a/IV. Spring Boot features/24.4. Profile-specific properties.md b/IV. Spring Boot features/24.4. Profile-specific properties.md deleted file mode 100644 index 908fc5c6..00000000 --- a/IV. Spring Boot features/24.4. Profile-specific properties.md +++ /dev/null @@ -1,11 +0,0 @@ -### 24.4. Profile-specific属性 - -除了`application.properties`文件,profile-specific属性也能通过命名惯例`application-{profile}.properties`定义。`Environment`(Spring的环境抽象接口)有个默认profiles集合(默认情况为`[default]`),在没有设置激活的profiles时会被使用(例如,如果没有明确指定激活的profiles,`application-default.properties`中的属性会被加载)。 - -Profile-specific属性加载路径和标准的`application.properties`相同,并且profile-specific文件总是会覆盖non-specific文件,不管profile-specific文件是否被打包到jar中。 - -如果定义多个profiles,最后一个将获胜。例如,`spring.profiles.active`定义的profiles被添加到通过`SpringApplication`API定义的profiles后面,因此优先级更高。 - -**注** 如果你已经在`spring.config.location`下定义所有文件(非目录),那些profile-specific的文件将不被考虑。如果想使用profile-specific属性,那就在`spring.config.location`下使用目录。 - - diff --git a/IV. Spring Boot features/24.5. Placeholders in Properties.md b/IV. Spring Boot features/24.5. Placeholders in Properties.md new file mode 100644 index 00000000..f15ead3d --- /dev/null +++ b/IV. Spring Boot features/24.5. Placeholders in Properties.md @@ -0,0 +1,8 @@ +### 24.5. 属性占位符 + +当使用`application.properties`定义的属性时,Spring会先通过已经存在的`Environment`查找该属性,所以你可以引用事先定义的值(比如,系统属性): +```java +app.name=MyApp +app.description=${app.name} is a Spring Boot application +``` +**注** 你也可以使用该技巧为存在的Spring Boot属性创建'短'变量,具体参考[章节 74.4,使用'short'命令行参数](../IX. ‘How-to’ guides/74.4 Use ‘Short’ Command Line Arguments.md)。 diff --git a/IV. Spring Boot features/24.5. Placeholders in properties.md b/IV. Spring Boot features/24.5. Placeholders in properties.md deleted file mode 100644 index 02aeb779..00000000 --- a/IV. Spring Boot features/24.5. Placeholders in properties.md +++ /dev/null @@ -1,8 +0,0 @@ -### 24.5. 属性占位符 - -当使用`application.properties`定义的属性时,Spring会先通过已经存在的`Environment`查找该属性,所以你可以引用事先定义的值(比如,系统属性): -```java -app.name=MyApp -app.description=${app.name} is a Spring Boot application -``` -**注** 你也可以使用该技巧为存在的Spring Boot属性创建'短'变量,具体参考[章节 73.4,使用'short'命令行参数](../IX. ‘How-to’ guides/73.4 Use ‘short’ command line arguments.md)。 diff --git a/IV. Spring Boot features/24.6. Using YAML Instead of Properties.md b/IV. Spring Boot features/24.6. Using YAML Instead of Properties.md new file mode 100644 index 00000000..582b53bd --- /dev/null +++ b/IV. Spring Boot features/24.6. Using YAML Instead of Properties.md @@ -0,0 +1,5 @@ +### 24.6. 使用YAML代替Properties + +[YAML](http://yaml.org/)是JSON的一个超集,也是一种方便的定义层次配置数据的格式。只要你将[SnakeYAML ](http://code.google.com/p/snakeyaml/)库放到classpath下,`SpringApplication`就会自动支持YAML,以作为properties的替换。 + +**注** 如果你使用“Starters”,添加`spring-boot-starter`依赖会自动加载SnakeYAML。 diff --git a/IV. Spring Boot features/24.6. Using YAML instead of Properties.md b/IV. Spring Boot features/24.6. Using YAML instead of Properties.md deleted file mode 100644 index 8e648269..00000000 --- a/IV. Spring Boot features/24.6. Using YAML instead of Properties.md +++ /dev/null @@ -1,5 +0,0 @@ -### 24.6. 使用YAML代替Properties - -[YAML](http://yaml.org/)是JSON的一个超集,也是一种方便的定义层次配置数据的格式。只要你将[SnakeYAML ](http://code.google.com/p/snakeyaml/)库放到classpath下,`SpringApplication`就会自动支持YAML,以作为properties的替换。 - -**注** 如果你使用'Starters',添加`spring-boot-starter`依赖会自动加载SnakeYAML。 diff --git a/IV. Spring Boot features/24.6.1. Loading YAML.md b/IV. Spring Boot features/24.6.1. Loading YAML.md index 9fefdfbc..9ea301c3 100644 --- a/IV. Spring Boot features/24.6.1. Loading YAML.md +++ b/IV. Spring Boot features/24.6.1. Loading YAML.md @@ -6,32 +6,32 @@ Spring框架提供两个便利的类用于加载YAML文档,`YamlPropertiesFact ```json environments: dev: - url: http://dev.bar.com + url: http://dev.example.com name: Developer Setup prod: - url: http://foo.bar.com + url: http://another.example.com name: My Cool App ``` -会被转化到这些属性: +会被转化为如下属性: ```java -environments.dev.url=http://dev.bar.com +environments.dev.url=http://dev.example.com environments.dev.name=Developer Setup -environments.prod.url=http://foo.bar.com +environments.prod.url=http://another.example.com environments.prod.name=My Cool App ``` YAML列表被表示成使用`[index]`间接引用作为属性keys的形式,例如下面的YAML: ```json my: servers: - - dev.bar.com - - foo.bar.com + - dev.example.com + - another.example.com ``` 将会转化到这些属性: ```java -my.servers[0]=dev.bar.com -my.servers[1]=foo.bar.com +my.servers[0]=dev.example.com +my.servers[1]=another.example.com ``` -使用Spring `DataBinder`工具集绑定这些属性(这是`@ConfigurationProperties`做的事)时,你需要确保目标bean有个`java.util.List`或`Set`类型的属性,并且需要提供一个setter或使用可变的值初始化它,比如,下面的代码将绑定上面的属性: +使用Spring `DataBinder`工具集绑定这些属性(这是`@ConfigurationProperties`做的事)时,你需要确保目标bean有个`java.util.List`或`Set`类型的属性,并且需要提供一个setter或使用可变的值初始化它,比如,下面的代码将绑定之前的属性: ```java @ConfigurationProperties(prefix="my") public class Config { @@ -42,8 +42,4 @@ public class Config { } ``` -**注** 当配置列表时需要格外小心,因为重写并不会像你期望的那样发生。在上面的例子中,当my.servers在几个地方被重新定义时,个别的元素会被重写,而不是列表。 为了确保拥有更高优先权的属性源能够重写列表,你需要把它定义为单个的属性: -```java - my : - servers : dev.bar.com,foo.bar.com -``` +**注** 当多个位置配置了列表,重写通过替换整个列表发生。在之前的例子里,当在几个地方定义了`my.servers`,来自`PropertySource`拥有更高优先级的整个列表会重写那个列表的任何其它的配置。可以使用逗号分隔的列表和YAML列表来完全重写列表的内容。 diff --git a/IV. Spring Boot features/24.6.2. Exposing YAML as Properties in the Spring Environment.md b/IV. Spring Boot features/24.6.2. Exposing YAML as Properties in the Spring Environment.md new file mode 100644 index 00000000..19196af0 --- /dev/null +++ b/IV. Spring Boot features/24.6.2. Exposing YAML as Properties in the Spring Environment.md @@ -0,0 +1,3 @@ +### 24.6.2. 在Spring环境中使用YAML暴露属性 + +`YamlPropertySourceLoader`类能够将YAML作为`PropertySource`导出到Sprig `Environment`,这允许你使用`@Value`注解配合占位符语法访问YAML属性。 diff --git a/IV. Spring Boot features/24.6.2. Exposing YAML as properties in the Spring Environment.md b/IV. Spring Boot features/24.6.2. Exposing YAML as properties in the Spring Environment.md deleted file mode 100644 index 707a396d..00000000 --- a/IV. Spring Boot features/24.6.2. Exposing YAML as properties in the Spring Environment.md +++ /dev/null @@ -1,3 +0,0 @@ -### 24.6.2. 在Spring环境中使用YAML暴露属性 - -`YamlPropertySourceLoader`类能够将YAML作为`PropertySource`导出到Sprig `Environment`,这允许你使用常用的`@Value`注解配合占位符语法访问YAML属性。 diff --git a/IV. Spring Boot features/24.6.3. Multi-profile YAML Documents.md b/IV. Spring Boot features/24.6.3. Multi-profile YAML Documents.md new file mode 100644 index 00000000..29bfda51 --- /dev/null +++ b/IV. Spring Boot features/24.6.3. Multi-profile YAML Documents.md @@ -0,0 +1,40 @@ +### 24.6.3. Multi-profile YAML文档 + +你可以在单个文件中定义多个特定配置(profile-specific)的YAML文档,并通过`spring.profiles`标示生效的文档,例如: +```json +server: + address: 192.168.1.100 +--- +spring: + profiles: development +server: + address: 127.0.0.1 +--- +spring: + profiles: production +server: + address: 192.168.1.120 +``` +在之前的例子中,如果`development` profile被激活,`server.address`属性将是`127.0.0.1`。相似的,如果`production` profile被激活,`server.address`属性将是`192.168.1.120`。如果`development`和`production` profiles没有启用,则该属性的值将是`192.168.1.100`。 + +在应用上下文启动时,如果没有明确指定激活的profiles,则默认的profiles将生效。所以,在下面的文档中我们为`spring.security.user.password`设置了一个值,该值只在"default" profile中有效: +```properties +server: + port: 8000 +--- +spring: + profiles: default +security: + user: + password: weak +``` +然而,在这个示例中,由于没有关联任何profile,密码总是会设置,并且如果有必要的话可以在其他profiles中显式重置: +```properties +server: + port: 8000 +spring: + security: + user: + password: weak +``` +通过`!`可以对`spring.profiles`指定的profiles进行取反(negated,跟java中的`!`作用一样),如果negated和non-negated profiles都指定一个单一文件,至少需要匹配一个non-negated profile,可能不会匹配任何negated profiles。 diff --git a/IV. Spring Boot features/24.6.3. Multi-profile YAML documents.md b/IV. Spring Boot features/24.6.3. Multi-profile YAML documents.md deleted file mode 100644 index 570e7001..00000000 --- a/IV. Spring Boot features/24.6.3. Multi-profile YAML documents.md +++ /dev/null @@ -1,39 +0,0 @@ -### 24.6.3. Multi-profile YAML文档 - -你可以在单个文件中定义多个特定配置(profile-specific)的YAML文档,并通过`spring.profiles`标示生效的文档,例如: -```json -server: - address: 192.168.1.100 ---- -spring: - profiles: development -server: - address: 127.0.0.1 ---- -spring: - profiles: production -server: - address: 192.168.1.120 -``` -在以上例子中,如果`development` profile被激活,`server.address`属性将是`127.0.0.1`;如果`development`和`production` profiles没有启用,则该属性的值将是`192.168.1.100`。 - -在应用上下文启动时,如果没有明确指定激活的profiles,则默认的profiles将生效。所以,在下面的文档中我们为`security.user.password`设置了一个值,该值只在"default" profile中有效: -```properties -server: - port: 8000 ---- -spring: - profiles: default -security: - user: - password: weak -``` -然而,在这个示例中,由于没有关联任何profile,密码总是会设置,并且如果有必要的话可以在其他profiles中显式重置: -```properties -server: - port: 8000 -security: - user: - password: weak -``` -通过`!`可以对`spring.profiles`指定的profiles进行取反(negated,跟java中的`!`作用一样),如果negated和non-negated profiles都指定一个单一文件,至少需要匹配一个non-negated profile,可能不会匹配任何negated profiles。 diff --git a/IV. Spring Boot features/24.6.4. YAML shortcomings.md b/IV. Spring Boot features/24.6.4. YAML Shortcomings.md similarity index 100% rename from IV. Spring Boot features/24.6.4. YAML shortcomings.md rename to IV. Spring Boot features/24.6.4. YAML Shortcomings.md diff --git a/IV. Spring Boot features/24.6.5. Merging YAML Lists.md b/IV. Spring Boot features/24.6.5. Merging YAML Lists.md new file mode 100644 index 00000000..63dabeb6 --- /dev/null +++ b/IV. Spring Boot features/24.6.5. Merging YAML Lists.md @@ -0,0 +1,46 @@ +### 24.6.5 合并YAML列表 + +正如[之前](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-loading-yaml)展示的,所有YAML最终都转换为properties,在通过一个profile覆盖"list"属性时这个过程可能不够直观(counter intuitive)。例如,假设有一个`MyPojo`对象,默认它的`name`和`description`属性都为`null`。下面的例子从`AcmeProperties`暴露一个`MyPojo`对象列表(list): +```java +@ConfigurationProperties("acme") +public class AcmeProperties { + + private final List list = new ArrayList<>(); + + public List getList() { + return this.list; + } + +} +``` +考虑如下配置: +```properties +acme: + list: + - name: my name + description: my description +--- +spring: + profiles: dev +acme: + list: + - name: my another name +``` +如果`dev` profile没有激活,`AcmeProperties.list`将包括一个如之前定义的`MyPojo`实体。即使`dev`生效,该`list`仍旧只包含一个实体(`name`值为`my another name`,`description`值为`null`)。此配置不会向该列表添加第二个`MyPojo`实例,也不会对该项进行合并。 + +当一个集合定义在多个profiles时,只使用优先级最高的。考虑下面的例子: +```properties +acme: + list: + - name: my name + description: my description + - name: another name + description: another description +--- +spring: + profiles: dev +acme: + list: + - name: my another name +``` +在之前的示例中,如果`dev` profile激活,`AcmeProperties.list`将包含一个`MyPojo`实体(`name`值为`my another name`,`description`值为`null`)。 diff --git a/IV. Spring Boot features/24.6.5. Merging YAML lists.md b/IV. Spring Boot features/24.6.5. Merging YAML lists.md deleted file mode 100644 index 1cd200b4..00000000 --- a/IV. Spring Boot features/24.6.5. Merging YAML lists.md +++ /dev/null @@ -1,46 +0,0 @@ -###24.6.5 合并YAML列表 - -正如[上面](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-loading-yaml)看到的,所有YAML最终都转换为properties,在通过一个profile覆盖"list"属性时这个过程可能不够直观(counter intuitive)。例如,假设有一个`MyPojo`对象,默认它的`name`和`description`属性都为`null`,下面我们将从`FooProperties`暴露一个`MyPojo`对象列表(list): -```java -@ConfigurationProperties("foo") -public class FooProperties { - - private final List list = new ArrayList<>(); - - public List getList() { - return this.list; - } - -} -``` -考虑如下配置: -```properties -foo: - list: - - name: my name - description: my description ---- -spring: - profiles: dev -foo: - list: - - name: my another name -``` -如果`dev` profile没有激活,`FooProperties.list`将包括一个如上述定义的`MyPojo`实体,即使`dev`生效,该`list`仍旧只包含一个实体(`name`值为`my another name`,`description`值为`null`)。此配置不会向该列表添加第二个`MyPojo`实例,也不会对该项进行合并。 - -当一个集合定义在多个profiles时,只使用优先级最高的: -```properties -foo: - list: - - name: my name - description: my description - - name: another name - description: another description ---- -spring: - profiles: dev -foo: - list: - - name: my another name -``` -在以上示例中,如果`dev` profile激活,`FooProperties.list`将包含一个`MyPojo`实体(`name`值为`my another name`,`description`值为`null`)。 diff --git a/IV. Spring Boot features/24.7. Type-safe Configuration Properties.md b/IV. Spring Boot features/24.7. Type-safe Configuration Properties.md index 76679e17..86feb628 100644 --- a/IV. Spring Boot features/24.7. Type-safe Configuration Properties.md +++ b/IV. Spring Boot features/24.7. Type-safe Configuration Properties.md @@ -1,6 +1,6 @@ ### 24.7. 类型安全的配置属性 -使用`@Value("${property}")`注解注入配置属性有时会比较麻烦(cumbersome),特别是需要使用多个properties,或数据本身有层次结构。Spring Boot提供一种使用配置的替代方法,这种方法允许强类型的beans以管理和校验应用的配置。 +使用`@Value("${property}")`注解注入配置属性有时会比较难处理,特别是但你需要使用多个properties,或者数据本身有层次结构的时候。Spring Boot提供一种可选的使用配置的方法,这种方法让强类型的beans来管理和校验应用的配置,如下所示: ```java package com.example; @@ -11,8 +11,8 @@ import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; -@ConfigurationProperties("foo") -public class FooProperties { +@ConfigurationProperties("acme") +public class AcmeProperties { private boolean enabled; @@ -53,46 +53,46 @@ public class FooProperties { } } ``` -上面的POJO定义了如下的属性: +之前的POJO定义了如下的属性: -- foo.enabled,默认为false +- acme.enabled,默认值为false -- foo.remote-address,带有一个能从String转换的类型 +- acme.remote-address,带有一个能从String转换的类型 -- foo.security.username,有一个嵌套的“security”,它的名字由属性名定义。特别的,返回类型没有在那儿被使用,本来可以是SecurityProperties。 +- acme.security.username,有一个嵌套的“security”对象,它的名字由属性名定义。特别的,返回类型没有在那儿被使用,本来可以是SecurityProperties。 -- foo.security.password +- acme.security.password -- foo.security.roles,一个String的集合 +- acme.security.roles,一个String的集合 **注意** getters和setters时常是必须的。因为跟Spring MVC一样,绑定是通过标准的Java Beans属性描述符进行的。但是也有不需要setter的情况: - Maps,只要它们被初始化了,需要getter,但setter不是必须的。因为binder能够改变它们。 -- Collections和arrays能够通过索引(通常用YAML),或者使用单个的由逗号分隔的值(属性)存取。 在后面的情况下,setter是必须的。对于这些类型,我们建议总是加上setter。如果你初始化一个collection,确保它不是不可变的(如同上面的例子)。 +- Collections和arrays能够通过索引(通常用YAML),或者使用单个的由逗号分隔的值(属性)存取。 在后面的情况下,setter是必须的。对于这些类型,我们建议总是加上setter。如果你初始化一个collection,确保它不是不可变的(如同之前的例子)。 -- 如果嵌套的POJO属性被初始化(就像上面例子里的Security域),setter就不需要。如果你想要binder使用它默认的构造器,即时创建一个实例,你就需要一个setter。 +- 如果嵌套的POJO属性被初始化(就像之前例子里的Security域),setter就不需要。如果你想要binder使用它默认的构造器,即时创建一个实例,你就需要一个setter。 有些人使用Project Lombok自动添加getters和setters。确保Lombok不会为这些类型生成任何特别的构造器,因为它会自动地被容器使用,来实例化对象。 -**提示** 查看[@Value和@ConfigurationProperties](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-vs-value)之间的区别。 +**提示** 查看[@Value和@ConfigurationProperties](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-vs-value)之间的区别。 -你需要在`@EnableConfigurationProperties`注解中列出要注册的属性类: +你需要在`@EnableConfigurationProperties`注解中列出要注册的属性类,如下所示: ```java @Configuration -@EnableConfigurationProperties(FooProperties.class) +@EnableConfigurationProperties(AcmeProperties.class) public class MyConfiguration { } ``` -**注** 当`@ConfigurationProperties` bean以这种方式注册时,该bean将有个约定的名称:`-`,``是`@ConfigurationProperties`注解中定义的environment key前缀,``是bean的全限定名。如果注解中没有提供任何前缀,那就只使用bean的全限定名。上述示例中的bean名称将是`foo-com.example.FooProperties`。 +**注** 当`@ConfigurationProperties` bean以这种方式注册时,该bean将有个约定的名称:`-`,``是`@ConfigurationProperties`注解中定义的environment key前缀,``是bean的全限定名。如果注解中没有提供任何前缀,那就只使用bean的全限定名。上述示例中的bean名称将是`acme-com.example.AcmeProperties`。 -尽管上述配置为`FooProperties`创建了一个常规的bean,不过我们建议`@ConfigurationProperties`只用来处理environment(只用于注入配置,系统环境之类的),特别是不要注入上下文中的其他beans。话虽如此,`@EnableConfigurationProperties`注解会自动应用到你的项目,任何存在的,注解`@ConfigurationProperties`的bean将会从`Environment`中得到配置。只要确定`FooProperties`是一个已存在的bean,`MyConfiguration`就可以不用了。 +尽管上述配置为`FooProperties`创建了一个常规的bean,不过我们建议`@ConfigurationProperties`只用来处理environment(只用于注入配置,系统环境之类的),特别是不要注入上下文中的其他beans。话虽如此,`@EnableConfigurationProperties`注解会自动应用到你的项目,任何存在的,注解`@ConfigurationProperties`的bean将会从`Environment`中得到配置。只要确定`AcmeProperties`是一个已存在的bean,`MyConfiguration`就可以不用了。 ```java @Component -@ConfigurationProperties(prefix="foo") -public class FooProperties { +@ConfigurationProperties(prefix="acme") +public class AcmeProperties { - // ... see above + // ... see the preceding example } ``` @@ -100,10 +100,10 @@ public class FooProperties { ```json # application.yml -foo: +acme: remote-address: 192.168.1.1 security: - username: foo + username: admin roles: - USER - ADMIN @@ -115,10 +115,10 @@ foo: @Service public class MyService { - private final FooProperties properties; + private final AcmeProperties properties; @Autowired - public MyService(FooProperties properties) { + public MyService(AcmeProperties properties) { this.properties = properties; } @@ -133,5 +133,3 @@ public class MyService { } ``` **注** 使用`@ConfigurationProperties`能够产生可被IDEs使用的元数据文件,来为你自己的键值提供自动补全,具体参考[Appendix B, Configuration meta-data](../X. Appendices/B. Configuration meta-data.md)。 - -**此章节翻译的不好,后续整理*** diff --git a/IV. Spring Boot features/24.7.1. Third-party Configuration.md b/IV. Spring Boot features/24.7.1. Third-party Configuration.md new file mode 100644 index 00000000..3a9dc764 --- /dev/null +++ b/IV. Spring Boot features/24.7.1. Third-party Configuration.md @@ -0,0 +1,13 @@ +### 24.7.1. 第三方配置 + +`@ConfigurationProperties`不仅可以注解在类上,也可以注解在public `@Bean`方法上,当你需要为不受控的第三方组件绑定属性时,该方法将非常有用。 + +为了从`Environment`属性中配置一个bean,你需要使用`@ConfigurationProperties`注解该bean: +```java +@ConfigurationProperties(prefix = "another") +@Bean +public AnotherComponent anotherComponent() { + ... +} +``` +和之前的`AcmeProperties`的示例方式相同,所有以`another`为前缀的属性定义都会被映射到`AnotherComponent`上。 diff --git a/IV. Spring Boot features/24.7.1. Third-party configuration.md b/IV. Spring Boot features/24.7.1. Third-party configuration.md deleted file mode 100644 index 39ca58af..00000000 --- a/IV. Spring Boot features/24.7.1. Third-party configuration.md +++ /dev/null @@ -1,13 +0,0 @@ -### 24.7.1. 第三方配置 - -`@ConfigurationProperties`不仅可以注解在类上,也可以注解在public `@Bean`方法上,当你需要为不受控的第三方组件绑定属性时,该方法将非常有用。 - -为了从`Environment`属性中配置一个bean,你需要使用`@ConfigurationProperties`注解该bean: -```java -@ConfigurationProperties(prefix = "bar") -@Bean -public BarComponent barComponent() { - ... -} -``` -和上面`FooProperties`的示例方式相同,所有以`bar`为前缀的属性定义都会被映射到`BarComponent`上。 diff --git a/IV. Spring Boot features/24.7.2. Relaxed Binding.md b/IV. Spring Boot features/24.7.2. Relaxed Binding.md new file mode 100644 index 00000000..0d8e1dc3 --- /dev/null +++ b/IV. Spring Boot features/24.7.2. Relaxed Binding.md @@ -0,0 +1,44 @@ +### 24.7.2. Relaxed绑定 + +Spring Boot将`Environment`属性绑定到`@ConfigurationProperties` beans时会使用一些宽松的规则,所以`Environment`属性名和bean属性名不需要精确匹配。常见的示例中有用的包括虚线分割(比如,`context-path`绑定到`contextPath`),将environment属性转为大写字母(比如,`PORT`绑定`port`)。 + +例如,考虑以下`@ConfigurationProperties`类: +```java +@ConfigurationProperties(prefix="acme.my-project.person") +public class OwnerProperties { + + private String firstName; + + public String getFirstName() { + return this.firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + +} +``` +在之前的例子里,下面的属性名都能使用: + +表格 24.1. relaxed绑定 + +| 属性 | 说明 | +| -------- | :----- | +|`acme.my-project.person.firstName`|标准驼峰命名语法| +|`acme.my-project.person.first-name`|短横线隔开表示,推荐用于`.properties`和`.yml`文件中| +|`acme.my-project.person.first_name`|下划线表示,用于`.properties`和`.yml`文件的可选格式| +|`ACME_MYPROJECT_PERSON_FIRSTNAME`|大写形式,推荐用于系统环境变量| + +**注** 注解的`前缀`值必须用短横线隔开表示,即小写并用`-`隔开,比如`acme.my-project.person`。 + +表格 24.2. 各个属性源的relaxed绑定规则 + +| 属性源 | Simple | List | +| -------- | :----- | :----- | +|Properties文件|驼峰命名法,短横线隔开表示,下划线表示|使用`[ ]`的标准list语法,或者由逗号分隔的值| +|YAML文件|驼峰命名法,短横线隔开表示,下划线表示|标准的YAML list语法,或者由逗号分隔的值| +|环境变量|下划线作为分隔符的大写格式。`_`不应当用在属性名上|被下划线环绕的数值。比如:`MY_ACME_1_OTHER = my.acme[1].other`| +|系统属性|驼峰命名法,短横线隔开表示,下划线表示|使用`[ ]`的标准list语法,或者由逗号分隔的值| + +**提示** 我们推荐:当可能时,属性用小写短横线隔开的格式储存。比如,`my.property-name=acme` diff --git a/IV. Spring Boot features/24.7.2. Relaxed binding.md b/IV. Spring Boot features/24.7.2. Relaxed binding.md deleted file mode 100644 index 4544f2a6..00000000 --- a/IV. Spring Boot features/24.7.2. Relaxed binding.md +++ /dev/null @@ -1,42 +0,0 @@ -### 24.7.2. Relaxed绑定 - -Spring Boot将`Environment`属性绑定到`@ConfigurationProperties` beans时会使用一些宽松的规则,所以`Environment`属性名和bean属性名不需要精确匹配。常见的示例中有用的包括虚线分割(比如,`context-path`绑定到`contextPath`),将environment属性转为大写字母(比如,`PORT`绑定`port`)。 - -例如,给定以下`@ConfigurationProperties`类: -```java -@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. relaxed绑定 -| 属性 | 说明 | -| -------- | :----- | -|`person.firstName`|标准驼峰命名语法| -|`person.first-name`|短横线隔开表示,推荐用于`.properties`和`.yml`文件中| -|`person.first_name`|下划线表示,用于`.properties`和`.yml`文件的可选格式| -|`PERSON_FIRST_NAME`|大写形式,推荐用于系统环境变量| - -**注** 注解的`前缀`值必须用短横线隔开表示,即小写并用`-`隔开。 - -表格 24.2. 各个属性源的relaxed绑定规则 -| 属性源 | Simple | List | -| -------- | :----- | -|Properties文件|驼峰命名法,短横线隔开表示,下划线表示|使用`[ ]`的标准list语法,或者由逗号分隔的值| -|YAML文件|驼峰命名法,短横线隔开表示,下划线表示|标准的YAML list语法,或者由逗号分隔的值| -|环境变量|下划线作为分隔符的大写格式。`_`不应当用在属性名上|被下划线环绕的数值。比如:`MY_FOO_1_BAR = my.foo[1].bar`| -|系统属性|驼峰命名法,短横线隔开表示,下划线表示|使用`[ ]`的标准list语法,或者由逗号分隔的值| - -**提示** 我们推荐:当可能时,属性用小写短横线隔开的格式储存。比如,`my.property-name=foo` \ No newline at end of file diff --git a/IV. Spring Boot features/24.7.3. Properties Conversion.md b/IV. Spring Boot features/24.7.3. Properties Conversion.md new file mode 100644 index 00000000..7ff906c1 --- /dev/null +++ b/IV. Spring Boot features/24.7.3. Properties Conversion.md @@ -0,0 +1,56 @@ +### 24.7.3 属性转换 + +将外部应用配置绑定到`@ConfigurationProperties` beans时,Spring Boot会尝试将属性强制转换为正确的类型。如果需要自定义类型转换器,你可以提供一个`ConversionService` bean(名为`conversionService`的bean),或自定义属性编辑器(通过`CustomEditorConfigurer` bean),或自定义`Converters`(bean定义时需要注解`@ConfigurationPropertiesBinding`)。 + +**注** 由于该bean在应用程序生命周期的早期就需要使用,所以确保限制你的`ConversionService`使用的依赖。通常,在创建时期任何你需要的依赖可能都没完全初始化。如果强制配置关键字不需要它,而且只依赖满足`@ConfigurationPropertiesBinding`的自定义的转换器,你可能想要重命名自定义的`ConversionService`。 + +**时间段转换** + +Spring Boot对表达时间段有专门的支持。 如果你暴露了`java.time.Duration`属性,可用下列格式的应用属性: + +- 常规的 `long`表示(默认单位为毫秒,除非指定了`@DefaultUnit`) +- [`java.util.Duration`使用的](https://docs.oracle.com/javase/8/docs/api//java/time/Duration.html#parse-java.lang.CharSequence-)标准的ISO-8601格式 +- 组合了值与单位的更加易读的格式(比如`10s`表示10秒) + +考虑下面的例子: +```java +@ConfigurationProperties("app.system") +public class AppSystemProperties { + + @DurationUnit(ChronoUnit.SECONDS) + private Duration sessionTimeout = Duration.ofSeconds(30); + + private Duration readTimeout = Duration.ofMillis(1000); + + public Duration getSessionTimeout() { + return this.sessionTimeout; + } + + public void setSessionTimeout(Duration sessionTimeout) { + this.sessionTimeout = sessionTimeout; + } + + public Duration getReadTimeout() { + return this.readTimeout; + } + + public void setReadTimeout(Duration readTimeout) { + this.readTimeout = readTimeout; + } + +} +``` +为了将会话超时指定为30秒,`30`, `PT30S`和 `30s`都是等价的。将读取超时指定为500毫秒,可以用下列格式里的任何一种:`500`, `PT0.5S`与`500ms`。 + +你也可以使用任何支持的单位: + +- ns用于纳秒 +- ms用于毫秒 +- s用于秒 +- m用于分 +- h用于小时 +- d应用日 + +默认单位是毫秒,可以使用`@DefaultUnit`重写。 + +**注** 如果你正在升级之前的版本,之前的版本简单地使用`Long`来表达时间段,如果切换到`Duration`时不是毫秒,要确保定义了单位(使用`@DefaultUnit`)。这样做的话,在支持更加丰富的格式的同时,升级也能更加透明。 \ No newline at end of file diff --git a/IV. Spring Boot features/24.7.3. Properties conversion.md b/IV. Spring Boot features/24.7.3. Properties conversion.md deleted file mode 100644 index b6382c15..00000000 --- a/IV. Spring Boot features/24.7.3. Properties conversion.md +++ /dev/null @@ -1,5 +0,0 @@ -### 24.7.3 属性转换 - -将外部应用配置绑定到`@ConfigurationProperties` beans时,Spring会尝试将属性强制转换为正确的类型。如果需要自定义类型转换器,你可以提供一个`ConversionService` bean(bean id为`conversionService`),或自定义属性编辑器(通过`CustomEditorConfigurer` bean),或自定义`Converters`(bean定义时需要注解`@ConfigurationPropertiesBinding`)。 - -**注** 由于该bean在应用程序生命周期的早期就需要使用,所以确保限制你的`ConversionService`使用的依赖。通常,在创建时期任何你需要的依赖可能都没完全初始化。 diff --git a/IV. Spring Boot features/24.7.4. @ConfigurationProperties Validation.md b/IV. Spring Boot features/24.7.4. @ConfigurationProperties Validation.md index 6d985aef..cbf6d5ed 100644 --- a/IV. Spring Boot features/24.7.4. @ConfigurationProperties Validation.md +++ b/IV. Spring Boot features/24.7.4. @ConfigurationProperties Validation.md @@ -1,10 +1,10 @@ ### 24.7.4. @ConfigurationProperties校验 -Spring Boot将尝试校验`@ConfigurationProperties`类,只要它们标注了Spring的`@Validated`。你可以在你的配置类中直接使用JSR-303 `javax.validation`约束标注。确保在你的类路径中存在适用的JSR-303实现,,再添加约束标注在你的域中: +Spring Boot会尝试校验`@ConfigurationProperties`类,只要它们标注了Spring的`@Validated`。你可以在你的配置类中直接使用JSR-303 `javax.validation`约束标注。确保在你的类路径中存在适用的JSR-303实现,再添加约束标注在你的域中: ```java -@ConfigurationProperties(prefix="foo") +@ConfigurationProperties(prefix="acme") @Validated -public class FooProperties { +public class AcmeProperties { @NotNull private InetAddress remoteAddress; @@ -13,11 +13,14 @@ public class FooProperties { } ``` +**注** 你也可以通过标注`@Bean`方法触发验证,用`@Validated`创建配置属性。 + +尽管在绑定后,内嵌属性也会被验证,但还是把相关的域标注上`@Valid`不失为一种良好的实践。这确保了即使没有找到内嵌属性,验证还是会被触发。下面的例子建立在之前的`AcmeProperties`示例之上: 为了校验内嵌属性的值,你需要使用`@Valid`注解关联的字段以触发它的校验,例如,建立在上面的FooProperties示例之上: ```java -@ConfigurationProperties(prefix="connection") +@ConfigurationProperties(prefix="acme") @Validated -public class FooProperties { +public class AcmeProperties { @NotNull private InetAddress remoteAddress; @@ -38,6 +41,6 @@ public class FooProperties { } ``` -你也可以通过创建一个叫做`configurationPropertiesValidator`的bean来添加自定义的Spring `Validator`。`@Bean`方法需要声明为`static`,因为配置属性校验器在应用程序生命周期中创建的比较早,将`@Bean`方法声明为`static`允许该bean在创建时不需要实例化`@Configuration`类,从而避免了早期实例化(early instantiation)的所有问题。相关的示例可以看[这里](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples/spring-boot-sample-property-validation)。 +你也可以通过创建一个叫做`configurationPropertiesValidator`的bean来添加自定义的Spring `Validator`。`@Bean`方法需要声明为`static`,因为配置属性校验器在应用程序生命周期中创建的比较早,将`@Bean`方法声明为`static`允许该bean在创建时不需要实例化`@Configuration`类,从而避免了早期实例化(early instantiation)的所有问题。相关的示例可以看[这里](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-property-validation)。 -**注** `spring-boot-actuator`模块包含一个暴露所有`@ConfigurationProperties` beans的端点(endpoint),通过浏览器打开`/application/configprops`进行浏览,或使用等效的JMX端点,具体参考[Production ready features](../V. Spring Boot Actuator/49. Endpoints.md)。 +**注** `spring-boot-actuator`模块包含一个暴露所有`@ConfigurationProperties` beans的端点(endpoint),通过浏览器打开`/actuator/configprops`进行浏览,或使用等效的JMX端点,具体参考[Production ready features](../V. Spring Boot Actuator/50. Endpoints.md)。 diff --git a/IV. Spring Boot features/24.7.5. @ConfigurationProperties vs. @Value.md b/IV. Spring Boot features/24.7.5. @ConfigurationProperties vs. @Value.md index 1c523e22..d3a81f27 100644 --- a/IV. Spring Boot features/24.7.5. @ConfigurationProperties vs. @Value.md +++ b/IV. Spring Boot features/24.7.5. @ConfigurationProperties vs. @Value.md @@ -1,11 +1,11 @@ ### 24.7.5 @ConfigurationProperties vs. @Value -`@Value`是Spring容器的一个核心特性,它没有提供跟type-safe Configuration Properties相同的特性。下面的表格总结了`@ConfigurationProperties`和`@Value`支持的特性: +`@Value`标注是Spring容器的一个核心特性,它没有提供跟类型安全的配置属性相同的特性。下面的表格总结了`@ConfigurationProperties`和`@Value`支持的特性: |特性|`@ConfigurationProperties`|`@Value`| |---|---|---| -|[Relaxed绑定](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-relaxed-binding)|Yes|No| -|[Meta-data支持](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#configuration-metadata)|Yes|No| +|[Relaxed绑定](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-relaxed-binding)|Yes|No| +|[Meta-data支持](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#configuration-metadata)|Yes|No| |`SpEL`表达式|No|Yes| -如果你为自己的组件定义了一系列的配置keys,我们建议你将它们以`@ConfigurationProperties`注解的POJO进行分组。由于`@Value`不支持relaxed绑定,所以如果你使用环境变量提供属性值的话,它就不是很好的选择。最后,尽管`@Value`可以写`SpEL`表达式,但这些表达式不会处理来自[Application属性文件](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-application-property-files)的属性。 +如果你为自己的组件定义了一系列的配置keys,我们建议你将它们以`@ConfigurationProperties`注解的POJO进行分组。由于`@Value`不支持relaxed绑定,所以如果你使用环境变量提供属性值的话,它就不是很好的选择。最后,尽管`@Value`可以写`SpEL`表达式,但这些表达式不会处理来自[Application属性文件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-application-property-files)的属性。 diff --git a/IV. Spring Boot features/25. Profiles.md b/IV. Spring Boot features/25. Profiles.md index c35f8272..4606d080 100644 --- a/IV. Spring Boot features/25. Profiles.md +++ b/IV. Spring Boot features/25. Profiles.md @@ -1,4 +1,5 @@ ### 25. Profiles + Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只在特定的环境下生效。任何`@Component`或`@Configuration`都能注解`@Profile`,从而限制加载它的时机: ```java @Configuration @@ -9,7 +10,7 @@ public class ProductionConfiguration { } ``` -以正常的Spring方式,你可以使用`spring.profiles.active`的`Environment`属性来指定哪个配置生效。你可以使用通常的任何方式来指定该属性,例如,可以将它包含到`application.properties`中: +你可以使用`spring.profiles.active`的`Environment`属性来指定哪个配置生效。你可以使用在这一章的前面描述过的任何方式来指定该属性。例如,可以将它包含到`application.properties`中: ```java spring.profiles.active=dev,hsqldb ``` diff --git a/IV. Spring Boot features/25.1. Adding Active Profiles.md b/IV. Spring Boot features/25.1. Adding Active Profiles.md new file mode 100644 index 00000000..32fde7ba --- /dev/null +++ b/IV. Spring Boot features/25.1. Adding Active Profiles.md @@ -0,0 +1,17 @@ +### 25.1. 添加激活的配置(profiles) + +`spring.profiles.active`属性和其他属性一样都遵循相同的排列规则:优先级最高的`PropertySource`获胜,也就是说,你可以在`application.properties`中指定生效的配置,然后使用命令行开关替换它们。 + +有时,将profile-specific的属性添加到激活的配置中而不是直接替换它们是有好处的。`spring.profiles.include`属性可以用来无条件的添加激活的配置,而`SpringApplication`的入口点也提供了一个用于设置其他配置的Java API,通过它设置的active配置优先级高于`spring.profiles.active`,具体参考`setAdditionalProfiles()`方法。 + +例如,当一个应用使用下面的属性,并用`--spring.profiles.active=prod`开关运行,那`proddb`和`prodmq` profiles也会激活: +```java +--- +my.property: fromyamlfile +--- +spring.profiles: prod +spring.profiles.include: + - proddb + - prodmq +``` +**注** `spring.profiles`属性可以定义到YAML文档中,以决定何时将该文档包含进配置,具体参考[章节 74.7 根据环境改变配置](../IX. ‘How-to’ guides/74.7 Change configuration depending on the environment.md) diff --git a/IV. Spring Boot features/25.1. Adding active profiles.md b/IV. Spring Boot features/25.1. Adding active profiles.md deleted file mode 100644 index 8eeed3ae..00000000 --- a/IV. Spring Boot features/25.1. Adding active profiles.md +++ /dev/null @@ -1,17 +0,0 @@ -### 25.1. 添加激活的配置(profiles) - -`spring.profiles.active`属性和其他属性一样都遵循相同的排列规则,优先级最高的`PropertySource`获胜,也就是说,你可以在`application.properties`中指定生效的配置,然后使用命令行开关替换它们。 - -有时,将profile-specific的属性添加到激活的配置中而不是直接替换它们是有好处的。`spring.profiles.include`属性可以用来无条件的添加激活的配置,而`SpringApplication`的入口点也提供了一个用于设置其他配置的Java API,通过它设置的active配置优先级高于`spring.profiles.active`,具体参考`setAdditionalProfiles()`方法。 - -例如,当一个应用使用下面的属性,并用`--spring.profiles.active=prod`开关运行,那`proddb`和`prodmq` profiles也会激活: -```java ---- -my.property: fromyamlfile ---- -spring.profiles: prod -spring.profiles.include: - - proddb - - prodmq -``` -**注** `spring.profiles`属性可以定义到YAML文档中,以决定何时将该文档包含进配置,具体参考[章节 73.7,根据环境改变配置](../IX. ‘How-to’ guides/73.7. Change configuration depending on the environment.md) diff --git a/IV. Spring Boot features/25.2. Programmatically setting profiles.md b/IV. Spring Boot features/25.2. Programmatically Setting Profiles.md similarity index 100% rename from IV. Spring Boot features/25.2. Programmatically setting profiles.md rename to IV. Spring Boot features/25.2. Programmatically Setting Profiles.md diff --git a/IV. Spring Boot features/25.3. Profile specific configuration files.md b/IV. Spring Boot features/25.3. Profile specific configuration files.md deleted file mode 100644 index 9f71dcd9..00000000 --- a/IV. Spring Boot features/25.3. Profile specific configuration files.md +++ /dev/null @@ -1,3 +0,0 @@ -### 25.3. Profile-specific配置文件 - -Profile-specific的配置,不管是`application.properties`(或`application.yml`),还是通过`@ConfigurationProperties`引用的文件都是被当作文件来加载的,具体参考[Section 24.3, “Profile specific properties”](24.4. Profile-specific properties.md)。 diff --git a/IV. Spring Boot features/25.3. Profile-specific Configuration Files.md b/IV. Spring Boot features/25.3. Profile-specific Configuration Files.md new file mode 100644 index 00000000..83acc750 --- /dev/null +++ b/IV. Spring Boot features/25.3. Profile-specific Configuration Files.md @@ -0,0 +1,3 @@ +### 25.3. Profile-specific配置文件 + +Profile-specific的配置,不管是`application.properties`(或`application.yml`),还是通过`@ConfigurationProperties`引用的文件都是被当作文件来加载的,具体参考[Section 24.4, “Profile-specific Properties”](24.4. Profile-specific Properties.md)。 diff --git a/IV. Spring Boot features/26. Logging.md b/IV. Spring Boot features/26. Logging.md index 285428fd..f0d8422b 100644 --- a/IV. Spring Boot features/26. Logging.md +++ b/IV. Spring Boot features/26. Logging.md @@ -1,6 +1,6 @@ ### 26. 日志 Spring Boot内部日志系统使用的是[Commons Logging](http://commons.apache.org/logging),但开放底层的日志实现,默认为会[Java Util Logging](http://docs.oracle.com/javase/7/docs/api/java/util/logging/package-summary.html), [Log4J](http://logging.apache.org/log4j/), [Log4J2](http://logging.apache.org/log4j/2.x/)和[Logback](http://logback.qos.ch/)提供配置。每种情况下都预先配置使用控制台输出,也可以使用可选的文件输出。 -默认情况下,如果你使用'Starters',那么就会使用Logback记录日志。为了确保使用Java Util Logging, Commons Logging, Log4J或SLF4J的依赖库能够正常工作,相应的Logback路由也会包含进来。 +默认情况下,如果你使用“Starters”,那么就会使用Logback记录日志。为了确保使用Java Util Logging, Commons Logging, Log4J或SLF4J的依赖库能够正常工作,相应的Logback路由也会包含进来。 **注** 如果上面的列表看起来令人困惑,不要担心,Java有很多可用的日志框架。通常,你不需要改变日志依赖,Spring Boot默认的就能很好的工作。 diff --git a/IV. Spring Boot features/26.1. Log Format.md b/IV. Spring Boot features/26.1. Log Format.md new file mode 100644 index 00000000..7bca9623 --- /dev/null +++ b/IV. Spring Boot features/26.1. Log Format.md @@ -0,0 +1,21 @@ +### 26.1. 日志格式 + +Spring Boot默认的日志输出格式如下: +```java +2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52 +2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext +2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms +2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] +2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] +``` +输出的节点(items)如下: + +1. 日期和时间:精确到毫秒,且易于排序。 +2. 日志级别:`ERROR`, `WARN`, `INFO`, `DEBUG` 或 `TRACE`。 +3. Process ID。 +4. `---`分隔符,用于区分实际日志信息开头。 +5. 线程名:包括在方括号中(控制台输出可能会被截断)。 +6. 日志名:通常是源class的类名(缩写)。 +7. 日志信息。 + +**注** Logback没有`FATAL`级别。它会映射到`ERROR`。 diff --git a/IV. Spring Boot features/26.1. Log format.md b/IV. Spring Boot features/26.1. Log format.md deleted file mode 100644 index f20d6bca..00000000 --- a/IV. Spring Boot features/26.1. Log format.md +++ /dev/null @@ -1,21 +0,0 @@ -### 26.1. 日志格式 - -Spring Boot默认的日志输出格式如下: -```java -2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52 -2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext -2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms -2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] -2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] -``` -输出的节点(items)如下: - -1. 日期和时间 - 精确到毫秒,且易于排序。 -2. 日志级别 - `ERROR`, `WARN`, `INFO`, `DEBUG` 或 `TRACE`。 -3. Process ID。 -4. `---`分隔符,用于区分实际日志信息开头。 -5. 线程名 - 包括在方括号中(控制台输出可能会被截断)。 -6. 日志名 - 通常是源class的类名(缩写)。 -7. 日志信息。 - -**注** Logback没有`FATAL`级别,它会映射到`ERROR`。 diff --git a/IV. Spring Boot features/26.2. Console output.md b/IV. Spring Boot features/26.2. Console Output.md similarity index 100% rename from IV. Spring Boot features/26.2. Console output.md rename to IV. Spring Boot features/26.2. Console Output.md diff --git a/IV. Spring Boot features/26.2.1. Color-coded Output.md b/IV. Spring Boot features/26.2.1. Color-coded Output.md new file mode 100644 index 00000000..f3f5cd53 --- /dev/null +++ b/IV. Spring Boot features/26.2.1. Color-coded Output.md @@ -0,0 +1,31 @@ +### 26.2.1 Color-coded输出 +如果你的终端支持ANSI,Spring Boot将使用彩色编码(color output)输出日志以增强可读性,你可以将`spring.output.ansi.enabled`设置为一个[支持的值](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/ansi/AnsiOutput.Enabled.html)来覆盖默认设置。 + +彩色编码(Color coding)使用`%clr`表达式进行配置,在其最简单的形式中,转换器会根据日志级别使用不同的颜色输出日志,例如: +```properties +%clr(%5p) +``` +下面的表格描述了日志级别到颜色的映射: + +|级别|颜色| +|---|---| +|`FATAL`|Red| +|`ERROR`|Red| +|`WARN`|Yellow| +|`INFO`|Green| +|`DEBUG`|Green| +|`TRACE`|Green| + +另外,在转换时你可以设定日志展示的颜色或样式,例如,让文本显示成黄色: +```properties +%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} +``` +支持的颜色,样式如下: + +* `blue` +* `cyan` +* `faint` +* `green` +* `magenta` +* `red` +* `yellow` diff --git a/IV. Spring Boot features/26.2.1. Color-coded output.md b/IV. Spring Boot features/26.2.1. Color-coded output.md deleted file mode 100644 index 5faa7e5f..00000000 --- a/IV. Spring Boot features/26.2.1. Color-coded output.md +++ /dev/null @@ -1,33 +0,0 @@ -### 26.2.1 Color-coded输出 -如果你的终端支持ANSI,Spring Boot将使用彩色编码(color output)输出日志以增强可读性,你可以将`spring.output.ansi.enabled`设置为一个[支持的值](http://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/ansi/AnsiOutput.Enabled.html)来覆盖默认设置。 - -彩色编码(Color coding)使用`%clr`表达式进行配置,在其最简单的形式中,转换器会根据日志级别使用不同的颜色输出日志,例如: -```properties -%clr(%5p) -``` -日志级别到颜色的映射如下: - -|Level|Color| -|---|---| -|`FATAL`|Red| -|`ERROR`|Red| -|`WARN`|Yellow| -|`INFO`|Green| -|`DEBUG`|Green| -|`TRACE`|Green| - -另外,在转换时你可以设定日志展示的颜色或样式,例如,让文本显示成黄色: -```properties -%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} -``` -支持的颜色,样式如下: - -* `blue` -* `cyan` -* `faint` -* `green` -* `magenta` -* `red` -* `yellow` - - diff --git a/IV. Spring Boot features/26.3. File Output.md b/IV. Spring Boot features/26.3. File Output.md new file mode 100644 index 00000000..fd26add6 --- /dev/null +++ b/IV. Spring Boot features/26.3. File Output.md @@ -0,0 +1,17 @@ +### 26.3. 文件输出 + +默认情况下,Spring Boot只会将日志记录到控制台,而不写进日志文件,如果需要,你可以设置`logging.file`或`logging.path`属性(例如`application.properties`)。 + +下表展示如何组合使用`logging.*`: + +|logging.file|logging.path| 示例 | 描述 | +| -------- | :----- | :----- | :-----| +| (none) | (none) | | 只记录到控制台 | +|Specific file|(none)|my.log|写到特定的日志文件,名称可以是精确的位置或相对于当前目录| +|(none)|Specific directory|/var/log|写到特定目录下的`spring.log`里,名称可以是精确的位置或相对于当前目录| + +日志文件每达到10MB就会被分割,跟控制台一样,默认记录`ERROR`, `WARN`和`INFO`级别的信息。可以使用`logging.file.max-size`属性改变大小限制。已经分割归档好的文件会无限期地保存下去,除非设置了`logging.file.max-history`属性。 + +**注** 日志系统在应用生命周期的早期初始化。因此,日志属性不能在通过`@PropertySource`标注加载的属性文件里找到。 + +**注** 日志属性独立于实际的日志基础设施。结果就是,特定的配置key(比如Logback的`logback.configurationFile`)不由Spring Boot管理。 diff --git a/IV. Spring Boot features/26.3. File output.md b/IV. Spring Boot features/26.3. File output.md deleted file mode 100644 index b451b50c..00000000 --- a/IV. Spring Boot features/26.3. File output.md +++ /dev/null @@ -1,13 +0,0 @@ -### 26.3. 文件输出 - -默认情况下,Spring Boot只会将日志记录到控制台,而不写进日志文件,如果需要,你可以设置`logging.file`或`logging.path`属性(例如`application.properties`)。 - -下表展示如何组合使用`logging.*`: - -|logging.file|logging.path| 示例 | 描述 | -| -------- | :----- | :----- | :-----| -| (none) | (none) | | 只记录到控制台 | -|Specific file|(none)|my.log|写到特定的日志文件,名称可以是精确的位置或相对于当前目录| -|(none)|Specific directory|/var/log|写到特定目录下的`spring.log`里,名称可以是精确的位置或相对于当前目录| - -日志文件每达到10MB就会被分割,跟控制台一样,默认记录`ERROR`, `WARN`和`INFO`级别的信息。 diff --git a/IV. Spring Boot features/26.4. Log Levels.md b/IV. Spring Boot features/26.4. Log Levels.md index d91c5b6d..43ee27e2 100644 --- a/IV. Spring Boot features/26.4. Log Levels.md +++ b/IV. Spring Boot features/26.4. Log Levels.md @@ -1,11 +1,10 @@ ### 26.4. 日志级别 -所有Spring Boot支持的日志系统都可以在Spring `Environment`中设置级别(`application.properties`里也一样),设置格式为'logging.level.*=LEVEL',其中`LEVEL`是`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`, `OFF`之一: +所有Spring Boot支持的日志系统都可以在Spring `Environment`中设置级别(`application.properties`里也一样),设置格式为logging.level.=,其中`level`是`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`, `OFF`之一。`root`记录器可以使用`logging.level.root`配置。 -以下是`application.properties`示例: +下面的例子展示了`application.properties`里可能的日志设置: ```properties logging.level.root=WARN logging.level.org.springframework.web=DEBUG logging.level.org.hibernate=ERROR ``` -**注** 默认情况,Spring Boot会重新映射Thymeleaf的`INFO`信息到`DEBUG`级别,这能减少标准日志输出的噪声。查看[LevelRemappingAppender](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot/src/main/java/org/springframework/boot/logging/logback/LevelRemappingAppender.java)可以按自己的配置设置映射。 diff --git a/IV. Spring Boot features/26.5. Custom Log Configuration.md b/IV. Spring Boot features/26.5. Custom Log Configuration.md new file mode 100644 index 00000000..77a94a31 --- /dev/null +++ b/IV. Spring Boot features/26.5. Custom Log Configuration.md @@ -0,0 +1,49 @@ +### 26.5. 自定义日志配置 + +通过将相应的库添加到classpath可以激活各种日志系统,然后在classpath根目录下提供合适的配置文件可以进一步定制日志系统,配置文件也可以通过Spring `Environment`的`logging.config`属性指定。 + +使用`org.springframework.boot.logging.LoggingSystem`系统属性可以强制Spring Boot使用指定的日志系统,该属性值需要是`LoggingSystem`实现类的全限定名,如果值为`none`,则彻底禁用Spring Boot的日志配置。 + +**注** 由于日志初始化早于`ApplicationContext`的创建,所以不可能通过`@PropertySources`指定的Spring `@Configuration`文件控制日志,系统属性和Spring Boot外部化配置可以正常工作。 + +以下文件会根据你选择的日志系统进行加载: + +| 日志系统 | 定制配置 | +| -------- | :-----: | +|Logback|`logback-spring.xml`,`logback-spring.groovy`,`logback.xml`或`logback.groovy`| +|Log4j|`log4j.properties`或`log4j.xml`| +|Log4j2|`log4j2-spring.xml`或`log4j2.xml`| +|JDK (Java Util Logging)|`logging.properties`| + +**注** 如果可能的话,建议你使用`-spring`变种形式定义日志配置(例如,使用`logback-spring.xml`而不是`logback.xml`)。如果你使用标准的配置路径,Spring可能不能够完全控制日志初始化。 + +**注** Java Util Logging从可执行jar运行时会导致一些已知的类加载问题,我们建议尽可能不使用它。 + +以下是从Spring `Envrionment`转换为System properties的一些有助于定制的配置属性: + +| Spring Environment| System Property| Comments | +| -------- | :-----: | :----: | +|`logging.exception-conversion-word`|`LOG_EXCEPTION_CONVERSION_WORD`|记录异常使用的关键字| +|`logging.file`|`LOG_FILE`|如果指定就会在默认的日志配置中使用| +|`logging.file.max-size`|`LOG_FILE_MAX_SIZE`|最大日志文件大小(如果LOG_FILE启用)。(只支持默认的Logback设置)| +|`logging.file.max-history`|`LOG_FILE_MAX_HISTORY`|保留的归档文件的最大数量(如果LOG_FILE启用)。(只支持默认的Logback设置)| +|`logging.path`|`LOG_PATH`|如果指定就会在默认的日志配置中使用| +|`logging.pattern.console`|`CONSOLE_LOG_PATTERN`|日志输出到控制台(stdout)时使用的模式(只支持默认的logback设置)| +|`logging.pattern.dateformat`|`LOG_DATEFORMAT_PATTERN`|日志日期格式的输出格式(只支持默认的logback设置)| +|`logging.pattern.file`|`FILE_LOG_PATTERN`|日志输出到文件时使用的模式(如果LOG_FILE启用,只支持默认的logback设置)| +|`logging.pattern.level`|`LOG_LEVEL_PATTERN`|用来渲染日志级别的格式(默认`%5p`,只支持默认的logback设置)| +|`PID`|`PID`|当前的处理进程(process)ID(能够找到,且还没有用作OS环境变量)| + +所有支持的日志系统在解析配置文件时都能获取系统属性的值,具体可以参考`spring-boot.jar`中的默认配置。 + +- [Logback](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml) +- [Log4j 2](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml) +- [Java Util logging](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/java/logging-file.properties) + +**注** 如果想在日志属性中使用占位符,你需要使用[Spring Boot的语法](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-placeholders-in-properties),而不是底层框架的语法。尤其是使用Logback时,你需要使用`:`作为属性名和默认值的分隔符,而不是`:-`。 + +**注** 通过覆盖`LOG_LEVEL_PATTERN`(Logback对应`logging.pattern.level`),你可以向日志中添加MDC和其他ad-hoc的内容。例如,将该值设置为`logging.pattern.level=user:%X{user} %5p`,则默认日志格式将包含一个"user"的MDC实体,如果存在的话,比如: +```properties +2015-09-30 12:30:04.031 user:juergen INFO 22174 --- [ nio-8080-exec-0] demo.Controller +Handling authenticated request +``` diff --git a/IV. Spring Boot features/26.5. Custom log configuration.md b/IV. Spring Boot features/26.5. Custom log configuration.md deleted file mode 100644 index d071a51a..00000000 --- a/IV. Spring Boot features/26.5. Custom log configuration.md +++ /dev/null @@ -1,41 +0,0 @@ -### 26.5. 自定义日志配置 -通过将相应的库添加到classpath可以激活各种日志系统,然后在classpath根目录下提供合适的配置文件可以进一步定制日志系统,配置文件也可以通过Spring `Environment`的`logging.config`属性指定。 - -使用`org.springframework.boot.logging.LoggingSystem`系统属性可以强制Spring Boot使用指定的日志系统,该属性值需要是`LoggingSystem`实现类的全限定名,如果值为`none`,则彻底禁用Spring Boot的日志配置。 - -**注** 由于日志初始化早于`ApplicationContext`的创建,所以不可能通过`@PropertySources`指定的Spring `@Configuration`文件控制日志,系统属性和Spring Boot外部化配置可以正常工作。 - -以下文件会根据你选择的日志系统进行加载: - -| 日志系统 | 定制配置 | -| -------- | :-----: | -|Logback|`logback-spring.xml`,`logback-spring.groovy`,`logback.xml`或`logback.groovy`| -|Log4j|`log4j.properties`或`log4j.xml`| -|Log4j2|`log4j2-spring.xml`或`log4j2.xml`| -|JDK (Java Util Logging)|`logging.properties`| - -**注** 如果可能的话,建议你使用`-spring`变种形式定义日志配置(例如,使用`logback-spring.xml`而不是`logback.xml`)。如果你使用标准的配置路径,Spring可能不能够完全控制日志初始化。 - -**注** Java Util Logging从可执行jar运行时会导致一些已知的类加载问题,我们建议尽可能不使用它。 - -以下是从Spring `Envrionment`转换为System properties的一些有助于定制的配置属性: - -| Spring Environment| System Property| Comments | -| -------- | :-----: | :----: | -|`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`|当前的处理进程(process)ID(能够找到,且还没有用作OS环境变量)| - -所有支持的日志系统在解析配置文件时都能获取系统属性的值,具体可以参考`spring-boot.jar`中的默认配置。 - -**注** 如果想在日志属性中使用占位符,你需要使用[Spring Boot的语法](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-external-config-placeholders-in-properties),而不是底层框架的语法。尤其是使用Logback时,你需要使用`:`作为属性名和默认值的分隔符,而不是`:-`。 - -**注** 通过覆盖`LOG_LEVEL_PATTERN`(Logback对应`logging.pattern.level`),你可以向日志中添加MDC和其他ad-hoc的内容。例如,将该值设置为`logging.pattern.level=user:%X{user} %5p`,则默认日志格式将包含一个"user"的MDC实体,如果存在的话,比如: -```properties -2015-09-30 12:30:04.031 user:juergen INFO 22174 --- [ nio-8080-exec-0] demo.Controller -Handling authenticated request -``` diff --git a/IV. Spring Boot features/26.6. Logback Extensions.md b/IV. Spring Boot features/26.6. Logback Extensions.md new file mode 100644 index 00000000..bb2b1739 --- /dev/null +++ b/IV. Spring Boot features/26.6. Logback Extensions.md @@ -0,0 +1,12 @@ +### 26.6 Logback扩展 + +Spring Boot包含很多有用的Logback扩展,你可以在`logback-spring.xml`配置文件中使用它们。 + +**注** 你不能在标准的`logback.xml`配置文件中使用扩展,因为它加载的太早了,不过可以使用`logback-spring.xml`,或指定`logging.config`属性。 + +**警告** 这些扩展不能和`Logback`的配置扫描一起使用。如果你尝试这样做,改变配置文件会导致类似与下面的错误: + +```properties +ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]] +ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]] +``` diff --git a/IV. Spring Boot features/26.6. Logback extensions.md b/IV. Spring Boot features/26.6. Logback extensions.md deleted file mode 100644 index 63ea38ec..00000000 --- a/IV. Spring Boot features/26.6. Logback extensions.md +++ /dev/null @@ -1,11 +0,0 @@ -### 26.6 Logback扩展 -Spring Boot包含很多有用的Logback扩展,你可以在`logback-spring.xml`配置文件中使用它们。 - -**注** 你不能在标准的`logback.xml`配置文件中使用扩展,因为它加载的太早了,不过可以使用`logback-spring.xml`,或指定`logging.config`属性。 - -**警告⚠️** 这些扩展不能和`Logback`的配置扫描一起使用。如果你尝试这样做,改变配置文件会导致类似与下面的错误:👇 - -```properties -ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]] -ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]] -``` \ No newline at end of file diff --git a/IV. Spring Boot features/26.6.1. Profile-specific Configuration.md b/IV. Spring Boot features/26.6.1. Profile-specific Configuration.md new file mode 100644 index 00000000..34f0edcf --- /dev/null +++ b/IV. Spring Boot features/26.6.1. Profile-specific Configuration.md @@ -0,0 +1,16 @@ +### 26.6.1 Profile-specific配置 + +``标签可用于根据激活的Spring profiles,选择性的包含或排除配置片段。Profile片段可以放在``元素内的任何地方,使用`name`属性定义哪些profile接受该配置,多个profiles以逗号分隔。下面展示了三个profile的示例: +```xml + + + + + + + + + + + +``` diff --git a/IV. Spring Boot features/26.6.1. Profile-specific configuration.md b/IV. Spring Boot features/26.6.1. Profile-specific configuration.md deleted file mode 100644 index 1476f9d0..00000000 --- a/IV. Spring Boot features/26.6.1. Profile-specific configuration.md +++ /dev/null @@ -1,15 +0,0 @@ -### 26.6.1 Profile-specific配置 -``标签可用于根据激活的Spring profiles,选择性的包含或排除配置片段。Profile片段可以放在``元素内的任何地方,使用`name`属性定义哪些profile接受该配置,多个profiles以逗号分隔。 -```xml - - - - - - - - - - - -``` diff --git a/IV. Spring Boot features/26.6.2. Environment Properties.md b/IV. Spring Boot features/26.6.2. Environment Properties.md new file mode 100644 index 00000000..44a0b958 --- /dev/null +++ b/IV. Spring Boot features/26.6.2. Environment Properties.md @@ -0,0 +1,12 @@ +### 26.6.2 Environment属性 + +``标签允许你从Spring `Environment`读取属性,以便在Logback中使用。如果你想在logback配置获取`application.properties`中的属性值,该功能就很有用。该标签工作方式跟Logback标准``标签类似,但不是直接指定`value`值,你需要定义属性的`source`(来自`Environment`),也可以指定存储属性作用域的`scope`。如果`Environment`没有相应属性,你可以通过`defaultValue`设置默认值。下面的例子展示了如何将属性暴露给Logback使用: +```xml + + + ${fluentHost} + ... + +``` +**注** `source`必须使用短横线隔开(`my.property-name`)的格式指定。但是,属性可以通过relaxed规则添加到`Environment`里。 diff --git a/IV. Spring Boot features/26.6.2. Environment properties.md b/IV. Spring Boot features/26.6.2. Environment properties.md deleted file mode 100644 index b4a3d67f..00000000 --- a/IV. Spring Boot features/26.6.2. Environment properties.md +++ /dev/null @@ -1,12 +0,0 @@ -### 26.6.2 Environment属性 - -``标签允许你从Spring `Environment`读取属性,以便在Logback中使用。如果你想在logback配置获取`application.properties`中的属性值,该功能就很有用。该标签工作方式跟Logback标准``标签类似,但不是直接指定`value`值,你需要定义属性的`source`(来自`Environment`),也可以指定存储属性作用域的`scope`。如果`Environment`没有相应属性,你可以通过`defaultValue`设置默认值。 -```xml - - - ${fluentHost} - ... - -``` -**注** `source`必须使用短横线隔开(`my.property-name`)的格式指定。但是,属性可以通过relaxed规则添加到`Environment`里。 \ No newline at end of file diff --git a/IV. Spring Boot features/27. Developing Web Applications.md b/IV. Spring Boot features/27. Developing Web Applications.md new file mode 100644 index 00000000..9a576e04 --- /dev/null +++ b/IV. Spring Boot features/27. Developing Web Applications.md @@ -0,0 +1,5 @@ +### 27. 开发Web应用 + +Spring Boot非常适合开发web应用程序。你可以使用内嵌的Tomcat,Jetty,Undertow或Netty创建一个HTTP服务器。大多数的web应用都可以使用`spring-boot-starter-web`模块进行快速搭建和运行。你也可以使用`spring-boot-starter-webflux`模块,来构建响应式的网络应用。 + +如果没有开发过Spring Boot web应用,可以参考[Getting started章节](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#getting-started-first-application)的"Hello World!"示例。 diff --git a/IV. Spring Boot features/27. Developing web applications.md b/IV. Spring Boot features/27. Developing web applications.md deleted file mode 100644 index 3a35886e..00000000 --- a/IV. Spring Boot features/27. Developing web applications.md +++ /dev/null @@ -1,4 +0,0 @@ -### 27. 开发Web应用 -Spring Boot非常适合开发web应用程序。你可以使用内嵌的Tomcat,Jetty,Undertow或Netty轻轻松松地创建一个HTTP服务器。大多数的web应用都可以使用`spring-boot-starter-web`模块进行快速搭建和运行。你也可以使用`spring-boot-starter-webflux`模块,来构建响应式的网络应用。 - -如果没有开发过Spring Boot web应用,可以参考[Getting started章节](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#getting-started-first-application)的"Hello World!"示例。 diff --git "a/IV. Spring Boot features/27.1. The \342\200\230Spring Web MVC framework\342\200\231.md" "b/IV. Spring Boot features/27.1. The \342\200\230Spring Web MVC framework\342\200\231.md" deleted file mode 100644 index 3ba19648..00000000 --- "a/IV. Spring Boot features/27.1. The \342\200\230Spring Web MVC framework\342\200\231.md" +++ /dev/null @@ -1,28 +0,0 @@ -### 27.1. Spring Web MVC框架 - -Spring Web MVC框架(通常简称为"Spring MVC")是一个富“模型,视图,控制器”web框架, -允许用户创建特定的`@Controller`或`@RestController` beans来处理传入的HTTP请求,通过`@RequestMapping`注解可以将控制器中的方法映射到相应的HTTP请求。 - -示例: -```java -@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 getUserCustomers(@PathVariable Long user) { - // ... - } - - @RequestMapping(value="/{user}", method=RequestMethod.DELETE) - public User deleteUser(@PathVariable Long user) { - // ... - } -} -``` -Spring MVC是Spring框架的核心部分,详细信息可以参考[reference documentation](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle#mvc),[spring.io/guides](http://spring.io/guides)也有一些可用的指导覆盖Spring MVC。 diff --git "a/IV. Spring Boot features/27.1. The \342\200\234Spring Web MVC Framework\342\200\235.md" "b/IV. Spring Boot features/27.1. The \342\200\234Spring Web MVC Framework\342\200\235.md" new file mode 100644 index 00000000..cf883845 --- /dev/null +++ "b/IV. Spring Boot features/27.1. The \342\200\234Spring Web MVC Framework\342\200\235.md" @@ -0,0 +1,28 @@ +### 27.1. Spring Web MVC框架 + +Spring Web MVC框架(通常简称为"Spring MVC")是一个富“模型,视图,控制器”web框架, +允许用户创建特定的`@Controller`或`@RestController` beans来处理传入的HTTP请求,通过`@RequestMapping`注解可以将控制器中的方法映射到相应的HTTP请求。 + +示例: +```java +@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 getUserCustomers(@PathVariable Long user) { + // ... + } + + @RequestMapping(value="/{user}", method=RequestMethod.DELETE) + public User deleteUser(@PathVariable Long user) { + // ... + } +} +``` +Spring MVC是Spring框架的核心部分,详细信息可以参考[reference documentation](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/htmlsingle#mvc),[spring.io/guides](http://spring.io/guides)也有一些可用的指导覆盖Spring MVC。 diff --git a/IV. Spring Boot features/27.1.1. Spring MVC Auto-configuration.md b/IV. Spring Boot features/27.1.1. Spring MVC Auto-configuration.md new file mode 100644 index 00000000..ef7d1b8b --- /dev/null +++ b/IV. Spring Boot features/27.1.1. Spring MVC Auto-configuration.md @@ -0,0 +1,16 @@ +### 27.1.1. Spring MVC自动配置 + +Spring Boot为Spring MVC提供的auto-configuration适用于大多数应用,并在Spring默认功能上添加了以下特性: + +1. 引入`ContentNegotiatingViewResolver`和`BeanNameViewResolver` beans。 +2. 对静态资源的支持,包括对WebJars的支持。 +3. 自动注册`Converter`,`GenericConverter`,`Formatter` beans。 +4. 对`HttpMessageConverters`的支持。 +5. 自动注册`MessageCodeResolver`。 +6. 对静态`index.html`的支持。 +7. 对自定义`Favicon`的支持。 +8. 自动使用`ConfigurableWebBindingInitializer` bean。 + +如果保留Spring Boot MVC特性,你只需添加其他的[MVC配置](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#mvc)(拦截器,格式化处理器,视图控制器等)。你可以添加自己的`WebMvcConfigurer`类型的`@Configuration`类,而不需要注解`@EnableWebMvc`。如果希望使用自定义的`RequestMappingHandlerMapping`,`RequestMappingHandlerAdapter`,或`ExceptionHandlerExceptionResolver`,你可以声明一个`WebMvcRegistrationsAdapter`实例提供这些组件。 + +如果想全面控制Spring MVC,你可以添加自己的`@Configuration`,并使用`@EnableWebMvc`注解。 diff --git a/IV. Spring Boot features/27.1.1. Spring MVC auto-configuration.md b/IV. Spring Boot features/27.1.1. Spring MVC auto-configuration.md deleted file mode 100644 index cdb2c8d5..00000000 --- a/IV. Spring Boot features/27.1.1. Spring MVC auto-configuration.md +++ /dev/null @@ -1,17 +0,0 @@ -### 27.1.1. Spring MVC自动配置 - -Spring Boot为Spring MVC提供的auto-configuration适用于大多数应用,并在Spring默认功能上添加了以下特性: - -1. 引入`ContentNegotiatingViewResolver`和`BeanNameViewResolver` beans。 -2. 对静态资源的支持,包括对WebJars的支持。 -3. 自动注册`Converter`,`GenericConverter`,`Formatter` beans。 -4. 对`HttpMessageConverters`的支持。 -5. 自动注册`MessageCodeResolver`。 -6. 对静态`index.html`的支持。 -7. 对自定义`Favicon`的支持。 -8. 自动使用`ConfigurableWebBindingInitializer` bean。 - -如果保留Spring Boot MVC特性,你只需添加其他的[MVC配置](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc)(拦截器,格式化处理器,视图控制器等)。你可以添加自己的`WebMvcConfigurer`类型的`@Configuration`类,而不需要注解`@EnableWebMvc`。如果希望使用自定义的`RequestMappingHandlerMapping`,`RequestMappingHandlerAdapter`,或`ExceptionHandlerExceptionResolver`,你可以声明一个`WebMvcRegistrationsAdapter`实例提供这些组件。 - - -如果想全面控制Spring MVC,你可以添加自己的`@Configuration`,并使用`@EnableWebMvc`注解。 diff --git a/IV. Spring Boot features/27.1.10. Spring HATEOAS.md b/IV. Spring Boot features/27.1.10. Spring HATEOAS.md deleted file mode 100644 index b190bef8..00000000 --- a/IV. Spring Boot features/27.1.10. Spring HATEOAS.md +++ /dev/null @@ -1,6 +0,0 @@ -### 27.1.10 Spring HATEOAS - -如果正在开发基于超媒体的RESTful API,你可能需要Spring HATEOAS,而Spring Boot会为其提供自动配置,这在大多数应用中都运作良好。 -自动配置取代了`@EnableHypermediaSupport`,只需注册一定数量的beans就能轻松构建基于超媒体的应用,这些beans包括`LinkDiscoverers`(客户端支持),`ObjectMapper`(用于将响应编排为想要的形式)。`ObjectMapper`可以根据`spring.jackson.*`属性或`Jackson2ObjectMapperBuilder` bean进行自定义。 - -通过注解`@EnableHypermediaSupport`,你可以控制Spring HATEOAS的配置,但这会禁用上述`ObjectMapper`的自定义功能。 diff --git a/IV. Spring Boot features/27.1.10. Template Engines.md b/IV. Spring Boot features/27.1.10. Template Engines.md new file mode 100644 index 00000000..c3c4c113 --- /dev/null +++ b/IV. Spring Boot features/27.1.10. Template Engines.md @@ -0,0 +1,16 @@ +### 27.1.10 模板引擎 + +正如REST web服务,你也可以使用Spring MVC提供动态HTML内容。Spring MVC支持各种各样的模板技术,包括Thymeleaf, FreeMarker和JSPs,很多其他的模板引擎也提供它们自己的Spring MVC集成。 + +Spring Boot为以下的模板引擎提供自动配置支持: + +* [FreeMarker](http://freemarker.org/docs/) +* [Groovy](http://beta.groovy-lang.org/docs/groovy-2.3.0/html/documentation/markup-template-engine.html) +* [Thymeleaf](http://www.thymeleaf.org/) +* [Mustache](http://mustache.github.io/) + +**注**:由于在内嵌servlet容器中使用JSPs存在一些[已知的限制](27.4.5. JSP limitations.md),所以建议尽量不使用它们。 + +使用以上引擎中的任何一种,并采用默认配置,则模块会从`src/main/resources/templates`自动加载。 + +**注**:IntelliJ IDEA根据你运行应用的方式会对classpath进行不同的排序。在IDE里通过main方法运行应用,跟从Maven,或Gradle,或打包好的jar中运行相比会导致不同的顺序,这可能导致Spring Boot不能从classpath下成功地找到模板。如果遇到这个问题,你可以在IDE里重新对classpath进行排序,将模块的类和资源放到第一位。或者,你可以配置模块的前缀为`classpath*:/templates/`,这样会查找classpath下的所有模板目录。 diff --git a/IV. Spring Boot features/27.1.11. CORS support.md b/IV. Spring Boot features/27.1.11. CORS support.md deleted file mode 100644 index d4cfe3bc..00000000 --- a/IV. Spring Boot features/27.1.11. CORS support.md +++ /dev/null @@ -1,20 +0,0 @@ -### 27.1.11 CORS支持 - -[跨域资源共享](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)(CORS)是一个[大多数浏览器](http://caniuse.com/#feat=cors)都实现了的[W3C标准](http://www.w3.org/TR/cors/),它允许你以灵活的方式指定跨域请求如何被授权,而不是采用那些不安全,性能低的方式,比如IFRAME或JSONP。 - -从4.2版本开始,Spring MVC对[CORS](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#cors)提供开箱即用的支持。不用添加任何特殊配置,只需要在Spring Boot应用的controller方法上注解[`@CrossOrigin`](https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html),并添加[CORS配置](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#_controller_method_cors_configuration)。通过注册一个自定义`addCorsMappings(CorsRegistry)`方法的`WebMvcConfigurer` bean可以指定[全局CORS配置](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#_global_cors_configuration): -```java -@Configuration -public class MyConfiguration { - - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/api/**"); - } - }; - } -} -``` diff --git a/IV. Spring Boot features/27.1.11. Error Handling.md b/IV. Spring Boot features/27.1.11. Error Handling.md new file mode 100644 index 00000000..6e510d6a --- /dev/null +++ b/IV. Spring Boot features/27.1.11. Error Handling.md @@ -0,0 +1,108 @@ +### 27.1.11 错误处理 + +Spring Boot默认提供一个`/error`映射用来以合适的方式处理所有的错误,并将它注册为servlet容器中全局的 +错误页面。对于机器客户端(相对于浏览器而言,浏览器偏重于人的行为),它会产生一个具有详细错误,HTTP状态,异常信息的JSON响应。对于浏览器客户端,它会产生一个白色标签样式(whitelabel)的错误视图,该视图将以HTML格式显示同样的数据(可以添加一个解析为'error'的View来自定义它)。为了完全替换默认的行为,你可以实现`ErrorController`,并注册一个该类型的bean定义,或简单地添加一个`ErrorAttributes`类型的bean以使用现存的机制,只是替换显示的内容。 + +**注** `BasicErrorController`可以作为自定义`ErrorController`的基类,如果你想添加对新context type的处理(默认处理`text/html`),这会很有帮助。你只需要继承`BasicErrorController`,添加一个public方法,并注解带有`produces`属性的`@RequestMapping`,然后创建该新类型的bean。 + +你也可以定义一个注解为`@ControllerAdvice`的类去自定义某个特殊controller或exception类型的JSON文档。如下所示: +```java +@ControllerAdvice(basePackageClasses = AcmeController.class) +public class AcmeControllerAdvice extends ResponseEntityExceptionHandler { + + @ExceptionHandler(YourException.class) + @ResponseBody + ResponseEntity handleControllerException(HttpServletRequest request, Throwable ex) { + HttpStatus status = getStatus(request); + return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status); + } + + private HttpStatus getStatus(HttpServletRequest request) { + Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); + if (statusCode == null) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } + return HttpStatus.valueOf(statusCode); + } + +} +``` +在以上示例中,如果跟`AcmeController`相同package的某个controller抛出`YourException`,一个`CustomErrorType`类型的POJO的JSON展示将代替`ErrorAttributes`展示。 + +**自定义错误页面** + +如果想为某个给定的状态码展示一个自定义的HTML错误页面,你需要将文件添加到`/error`文件夹下。错误页面既可以是静态HTML(比如,任何静态资源文件夹下添加的),也可以是使用模板构建的,文件名必须是明确的状态码或一系列标签。 + +例如,映射`404`到一个静态HTML文件,你的目录结构可能如下: +```properties +src/ + +- main/ + +- java/ + | + + +- resources/ + +- public/ + +- error/ + | +- 404.html + +- +``` +使用FreeMarker模板映射所有`5xx`错误,你需要如下的目录结构: +```properties +src/ + +- main/ + +- java/ + | + + +- resources/ + +- templates/ + +- error/ + | +- 5xx.ftl + +- +``` +对于更复杂的映射,你可以添加实现`ErrorViewResolver`接口的beans: +```java +public class MyErrorViewResolver implements ErrorViewResolver { + + @Override + public ModelAndView resolveErrorView(HttpServletRequest request, + HttpStatus status, Map model) { + // Use the request or status to optionally return a ModelAndView + return ... + } + +} +``` +你也可以使用Spring MVC特性,比如[@ExceptionHandler方法](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers)和[@ControllerAdvice](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-controller-advice),`ErrorController`将处理所有未处理的异常。 + +**映射Spring MVC以外的错误页面** + +对于不使用Spring MVC的应用,你可以通过`ErrorPageRegistrar`接口直接注册`ErrorPages`。该抽象直接工作于底层内嵌servlet容器,即使你没有Spring MVC的`DispatcherServlet`,它们仍旧可以工作。 +```java +@Bean +public ErrorPageRegistrar errorPageRegistrar(){ + return new MyErrorPageRegistrar(); +} + +// ... + +private static class MyErrorPageRegistrar implements ErrorPageRegistrar { + + @Override + public void registerErrorPages(ErrorPageRegistry registry) { + registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); + } + +} +``` +**注** 如果你注册一个`ErrorPage`,该页面需要被一个`Filter`处理(在一些非Spring web框架中很常见,比如Jersey,Wicket),那么该`Filter`需要明确注册为一个`ERROR`分发器(dispatcher),例如: +```java +@Bean +public FilterRegistrationBean myFilter() { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setFilter(new MyFilter()); + ... + registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); + return registration; +} +``` +默认的`FilterRegistrationBean`不包含`ERROR` dispatcher类型。 + +注意:当部署到一个servlet容器时,Spring Boot通过它的错误页面过滤器将带有错误状态的请求转发到恰当的错误页面。request只有在response还没提交时才能转发(forwarded)到正确的错误页面,而WebSphere应用服务器8.0及后续版本默认情况会在servlet方法成功执行后提交response,你需要设置`com.ibm.ws.webcontainer.invokeFlushAfterService`属性为`false`来关闭该行为。 diff --git a/IV. Spring Boot features/27.1.12. Spring HATEOAS.md b/IV. Spring Boot features/27.1.12. Spring HATEOAS.md new file mode 100644 index 00000000..c4cd6613 --- /dev/null +++ b/IV. Spring Boot features/27.1.12. Spring HATEOAS.md @@ -0,0 +1,6 @@ +### 27.1.12 Spring HATEOAS + +如果正在开发基于超媒体的RESTful API,你可能需要Spring HATEOAS,而Spring Boot会为其提供自动配置,这在大多数应用中都运作良好。 +自动配置取代了`@EnableHypermediaSupport`,只需注册一定数量的beans就能轻松构建基于超媒体的应用,这些beans包括`LinkDiscoverers`(客户端支持),`ObjectMapper`(用于将响应编排为想要的形式)。`ObjectMapper`可以根据`spring.jackson.*`属性或`Jackson2ObjectMapperBuilder` bean进行自定义。 + +通过注解`@EnableHypermediaSupport`,你可以控制Spring HATEOAS的配置,但这会禁用上述`ObjectMapper`的自定义功能。 \ No newline at end of file diff --git a/IV. Spring Boot features/27.1.13. CORS support.md b/IV. Spring Boot features/27.1.13. CORS support.md new file mode 100644 index 00000000..f4f2e2f6 --- /dev/null +++ b/IV. Spring Boot features/27.1.13. CORS support.md @@ -0,0 +1,20 @@ +### 27.1.13 CORS支持 + +[跨域资源共享](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)(CORS)是一个[大多数浏览器](https://caniuse.com/#feat=cors)都实现了的[W3C标准](https://www.w3.org/TR/cors/),它允许你以灵活的方式指定跨域请求如何被授权,而不是采用那些不安全,性能低的方式,比如IFRAME或JSONP。 + +从4.2版本开始,Spring MVC对[CORS](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#cors)提供开箱即用的支持。不用添加任何特殊配置,只需要在Spring Boot应用的controller方法上注解[`@CrossOrigin`](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html),并添加[CORS配置](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#controller-method-cors-configuration)。通过注册一个自定义`addCorsMappings(CorsRegistry)`方法的`WebMvcConfigurer` bean可以指定[全局CORS配置](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#global-cors-configuration): +```java +@Configuration +public class MyConfiguration { + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/api/**"); + } + }; + } +} +``` diff --git a/IV. Spring Boot features/27.1.2. HttpMessageConverters.md b/IV. Spring Boot features/27.1.2. HttpMessageConverters.md index 478ab543..947ac089 100644 --- a/IV. Spring Boot features/27.1.2. HttpMessageConverters.md +++ b/IV. Spring Boot features/27.1.2. HttpMessageConverters.md @@ -1,8 +1,8 @@ ### 27.1.2. HttpMessageConverters -Spring MVC使用`HttpMessageConverter`接口转换HTTP请求和响应,合适的默认配置可以开箱即用,例如对象自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用,否则使用JAXB),字符串默认使用`UTF-8`编码。 +Spring MVC使用`HttpMessageConverter`接口转换HTTP请求和响应。合适的默认配置可以开箱即用,例如对象自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用,否则使用JAXB),字符串默认使用`UTF-8`编码。 -可以使用Spring Boot的`HttpMessageConverters`类添加或自定义转换类: +可以使用Spring Boot的`HttpMessageConverters`类添加或自定义转换类,如下所示: ```java import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.*; @@ -19,4 +19,4 @@ public class MyConfiguration { } } ``` -上下文中出现的所有`HttpMessageConverter` bean都将添加到converters列表,你可以通过这种方式覆盖默认的转换器列表(converters)。 +上下文中出现的所有`HttpMessageConverter` bean都将添加到converters列表。你可以通过这种方式覆盖默认的转换器列表(converters)。 diff --git a/IV. Spring Boot features/27.1.3. Custom JSON Serializers and Deserializers.md b/IV. Spring Boot features/27.1.3. Custom JSON Serializers and Deserializers.md index 3f2bab43..54a7fa7a 100644 --- a/IV. Spring Boot features/27.1.3. Custom JSON Serializers and Deserializers.md +++ b/IV. Spring Boot features/27.1.3. Custom JSON Serializers and Deserializers.md @@ -1,3 +1,29 @@ -###27.1.3 自定义JSON序列化器和反序列化器 +### 27.1.3 自定义JSON序列化器和反序列化器 如果使用Jackson序列化,反序列化JSON数据,你可能想编写自己的`JsonSerializer`和`JsonDeserializer`类。自定义序列化器(serializers)通常[通过Module注册到Jackson](http://wiki.fasterxml.com/JacksonHowToCustomDeserializers),但Spring Boot提供了`@JsonComponent`注解这一替代方式,它能轻松的将序列化器注册为Spring Beans。 + +你可以在`JsonSerializer`或者`JsonDeserializer`的实现上,直接使用`@JsonComponent`注解。你也可以在以内部类的形式包含序列化器/反序列化器的类上使用它,如下所示: + +``` +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 { + // ... + } + + public static class Deserializer extends JsonDeserializer { + // ... + } + +} +``` + +`ApplicationContext`里所有的`@JsonComponent` bean会自动注册到Jackson。因为`@JsonComponent`用`@Component`进行元注解,会应用通常的组件扫描规则。 + +Spring Boot也提供了[`JsonObjectSerializer`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java)和[`JsonObjectDeserializer`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java)基础类。它们为标准的Jackson版本提供了替代选择。详情请查看[`JsonObjectSerializer`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/jackson/JsonObjectSerializer.html)和[`JsonObjectDeserializer`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/jackson/JsonObjectDeserializer.html)的Javadoc。 diff --git a/IV. Spring Boot features/27.1.4. MessageCodesResolver.md b/IV. Spring Boot features/27.1.4. MessageCodesResolver.md index c657cd2d..c5fce621 100644 --- a/IV. Spring Boot features/27.1.4. MessageCodesResolver.md +++ b/IV. Spring Boot features/27.1.4. MessageCodesResolver.md @@ -1,3 +1,3 @@ ### 27.1.4 MessageCodesResolver -Spring MVC有一个实现策略,用于从绑定的errors产生用来渲染错误信息的错误码:`MessageCodesResolver`。Spring Boot会自动为你创建该实现,只要设置`spring.mvc.message-codes-resolver.format`属性为`PREFIX_ERROR_CODE`或`POSTFIX_ERROR_CODE`(具体查看`DefaultMessageCodesResolver.Format`枚举值)。 +Spring MVC有一个实现策略,用于从绑定的errors产生用来渲染错误信息的错误码:`MessageCodesResolver`。只要设置`spring.mvc.message-codes-resolver.format`属性为`PREFIX_ERROR_CODE`或`POSTFIX_ERROR_CODE`,Spring Boot会自动为你创建该实现(具体查看`DefaultMessageCodesResolver.Format`枚举值)。 diff --git a/IV. Spring Boot features/27.1.5. Static Content.md b/IV. Spring Boot features/27.1.5. Static Content.md index 2867a648..5c166ba4 100644 --- a/IV. Spring Boot features/27.1.5. Static Content.md +++ b/IV. Spring Boot features/27.1.5. Static Content.md @@ -4,11 +4,11 @@ 在单机web应用中,容器会启动默认的servlet,并用它加载`ServletContext`根目录下的内容以响应那些Spring不处理的请求。大多数情况下这都不会发生(除非你修改默认的MVC配置),因为Spring总能够通过`DispatcherServlet`处理这些请求。 -默认地,资源放置在`/**`,但是你可以通过`spring.mvc.static-path-pattern`进行调整。例如,迁移所有的资源到`/resources/**`可以按照如下方式实现: +默认地,资源放置在`/**`,但是你可以通过`spring.mvc.static-path-pattern`属性进行调整。例如,迁移所有的资源到`/resources/**`可以按照如下方式实现: ```properties spring.mvc.static-path-pattern=/resources/** ``` -你可以设置`spring.resources.static-locations`属性自定义静态资源的位置(配置一系列目录位置代替默认的值)。根Servlet的上下文路径“/”也会被作为一个位置自动添加。如果你这样做,默认的欢迎页面将从自定义位置加载,所以只要这些路径中的任何地方有一个`index.html`,它都会成为应用的主页。 +你可以设置`spring.resources.static-locations`属性自定义静态资源的位置(配置一系列目录位置代替默认的值)。根Servlet的上下文路径“/”也会被作为一个位置自动添加。 此外,除了上述标准的静态资源位置,有个例外情况是[Webjars内容](http://www.webjars.org/)。任何在`/webjars/**`路径下的资源都将从jar文件中提供,只要它们以Webjars的格式打包。 @@ -18,14 +18,14 @@ Spring Boot也支持Spring MVC提供的高级资源处理特性,可用于清 如果想使用针对WebJars版本无感知的URLs(version agnostic),只需要添加`webjars-locator`依赖,然后声明你的Webjar。以jQuery为例,`"/webjars/jquery/dist/jquery.min.js"`实际为`"/webjars/jquery/x.y.z/dist/jquery.min.js"`,`x.y.z`为Webjar的版本。 -**注** 如果使用JBoss,你需要声明`webjars-locator-jboss-vfs`依赖而不是`webjars-locator`,否则所有的Webjars将解析为`404`。 +**注** 如果使用JBoss,你需要声明`webjars-locator-jboss-vfs`依赖而不是`webjars-locator-core`,否则所有的Webjars将解析为`404`。 以下的配置为所有的静态资源提供一种缓存清除(cache busting)方案,实际上是将内容hash添加到URLs中,比如``: ```properties spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/** ``` -**注** 实现该功能的是`ResourceUrlEncodingFilter`,它在模板运行期会重写资源链接,Thymeleaf和FreeMarker会自动配置该filter,JSP需要手动配置。其他模板引擎还没自动支持,不过你可以使用[ResourceUrlProvider](https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/org/springframework/web/servlet/resource/ResourceUrlProvider.html)自定义模块宏或帮助类。 +**注** 实现该功能的是`ResourceUrlEncodingFilter`,它在模板运行期会重写资源链接,Thymeleaf和FreeMarker会自动配置该filter,JSP需要手动配置。其他模板引擎还没自动支持,不过你可以使用[ResourceUrlProvider](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/web/servlet/resource/ResourceUrlProvider.html)自定义模块宏或帮助类。 当使用比如JavaScript模块加载器动态加载资源时,重命名文件是不行的,这也是提供其他策略并能结合使用的原因。下面是一个"fixed"策略,在URL中添加一个静态version字符串而不需要改变文件名: ```properties @@ -35,6 +35,6 @@ spring.resources.chain.strategy.fixed.enabled=true spring.resources.chain.strategy.fixed.paths=/js/lib/ spring.resources.chain.strategy.fixed.version=v12 ``` -使用以上策略,JavaScript模块加载器加载`"/js/lib/"`下的文件时会使用一个固定的版本策略`"/v12/js/lib/mymodule.js"`,其他资源仍旧使用内容hash的方式``。查看[ResourceProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java)获取更多支持的选项。 +使用以上策略,JavaScript模块加载器加载`"/js/lib/"`下的文件时会使用一个固定的版本策略(`"/v12/js/lib/mymodule.js"`),其他资源仍旧使用内容hash的方式(``)。查看[ResourceProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java)获取更多支持的选项。 -**注** 该特性在一个专门的[博文](https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources)和Spring框架[参考文档](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#mvc-config-static-resources)中有透彻描述。 +**注** 该特性在一个专门的[博文](https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources)和Spring框架[参考文档](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-config-static-resources)中有透彻描述。 diff --git a/IV. Spring Boot features/27.1.6. Custom Favicon.md b/IV. Spring Boot features/27.1.6. Custom Favicon.md deleted file mode 100644 index a33dc90d..00000000 --- a/IV. Spring Boot features/27.1.6. Custom Favicon.md +++ /dev/null @@ -1,3 +0,0 @@ -### 27.1.6 定制网站图标 -Spring Boot会在已配置的静态内容位置和类路径的根目录下依次寻找`favicon.ico`文件。 如果文件存在,它会被自动用作应用的图标。 - diff --git a/IV. Spring Boot features/27.1.6. Welcome Page.md b/IV. Spring Boot features/27.1.6. Welcome Page.md new file mode 100644 index 00000000..4bbb1774 --- /dev/null +++ b/IV. Spring Boot features/27.1.6. Welcome Page.md @@ -0,0 +1,3 @@ +### 27.1.6 欢迎页 + +Spring Boot支持静态的和模板化的欢迎页。它首先会去配置好的静态内容位置寻找`index.html`文件。如果没找到,则会去寻找 `index`模版。如果找到其中之一,Spring Boot会自动把它当做应用的欢迎页。 \ No newline at end of file diff --git a/IV. Spring Boot features/27.1.7. ConfigurableWebBindingInitializer.md b/IV. Spring Boot features/27.1.7. ConfigurableWebBindingInitializer.md deleted file mode 100644 index 8ce28c19..00000000 --- a/IV. Spring Boot features/27.1.7. ConfigurableWebBindingInitializer.md +++ /dev/null @@ -1,3 +0,0 @@ -### 27.1.7 ConfigurableWebBindingInitializer -Spring MVC使用`WebBindingInitializer`为每个特殊的请求初始化相应的`WebDataBinder`,如果你创建自己的`ConfigurableWebBindingInitializer @Bean`,Spring Boot会自动配置Spring MVC使用它。 - diff --git a/IV. Spring Boot features/27.1.7. Custom Favicon.md b/IV. Spring Boot features/27.1.7. Custom Favicon.md new file mode 100644 index 00000000..263939be --- /dev/null +++ b/IV. Spring Boot features/27.1.7. Custom Favicon.md @@ -0,0 +1,3 @@ +### 27.1.7 定制网站图标 + +Spring Boot会在已配置的静态内容位置和类路径的根目录下依次寻找`favicon.ico`文件。 如果文件存在,它会被自动用作应用的图标。 diff --git a/IV. Spring Boot features/27.1.8. Path Matching and Content Negotiation.md b/IV. Spring Boot features/27.1.8. Path Matching and Content Negotiation.md new file mode 100644 index 00000000..fa24f0b1 --- /dev/null +++ b/IV. Spring Boot features/27.1.8. Path Matching and Content Negotiation.md @@ -0,0 +1,29 @@ +### 27.1.8 路径匹配与内容协商 + +Spring MVC能够查看请求路径,将HTTP请求映射到处理程序,并把它匹配到应用里定义的映射关系(比如,Controller方法的`@GetMapping`注解)。 + +Spring Boot默认禁用后缀模式匹配。这意味着类似`"GET /projects/spring-boot.json"`的请求,不会匹配到`@GetMapping("/projects/spring-boot")`。这是[Spring MVC应用的一种最佳实践](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#mvc-ann-requestmapping-suffix-pattern-match)。过去,这个特性主要对HTTP客户端有用。HTTP客户端没有发送适当的"Accept"请求头。我们需要确保给客户端发送了正确的内容类型。现在,内容协商更为可靠。 + +还有其它方式处理HTTP客户端没有发送适当的"Accept"请求头的情况。不使用后缀匹配,但我们可以使用一个查询参数,来确保类似于`"GET /projects/spring-boot?format=json"`的请求会映射到`@GetMapping("/projects/spring-boot")`: + +```properties +spring.mvc.contentnegotiation.favor-parameter=true + +# We can change the parameter name, which is "format" by default: +# spring.mvc.contentnegotiation.parameter-name=myparam + +# We can also register additional file extensions/media types with: +spring.mvc.contentnegotiation.media-types.markdown=text/markdown +``` + +如果你理解上面的警告,但还是想要在你的应用里使用后缀模式匹配,你需要下面的配置: + +```properties +spring.mvc.contentnegotiation.favor-path-extension=true + +# You can also restrict that feature to known extensions only +# spring.mvc.pathmatch.use-registered-suffix-pattern=true + +# We can also register additional file extensions/media types with: +# spring.mvc.contentnegotiation.media-types.adoc=text/asciidoc +``` \ No newline at end of file diff --git a/IV. Spring Boot features/27.1.8. Template engines.md b/IV. Spring Boot features/27.1.8. Template engines.md deleted file mode 100644 index 73685de8..00000000 --- a/IV. Spring Boot features/27.1.8. Template engines.md +++ /dev/null @@ -1,16 +0,0 @@ -### 27.1.8 模板引擎 - -正如REST web服务,你也可以使用Spring MVC提供动态HTML内容。Spring MVC支持各种各样的模板技术,包括Thymeleaf, FreeMarker和JSPs,很多其他的模板引擎也提供它们自己的Spring MVC集成。 - -Spring Boot为以下的模板引擎提供自动配置支持: - -* [FreeMarker](http://freemarker.org/docs/) -* [Groovy](http://beta.groovy-lang.org/docs/groovy-2.3.0/html/documentation/markup-template-engine.html) -* [Thymeleaf](http://www.thymeleaf.org/) -* [Mustache](http://mustache.github.io/) - -**注**:由于在内嵌servlet容器中使用JSPs存在一些[已知的限制](27.3.5. JSP limitations.md),所以建议尽量不使用它们。 - -使用以上引擎中的任何一种,并采用默认配置,则模块会从`src/main/resources/templates`自动加载。 - -**注**:IntelliJ IDEA根据你运行应用的方式会对classpath进行不同的排序。在IDE里通过main方法运行应用,跟从Maven,或Gradle,或打包好的jar中运行相比会导致不同的顺序,这可能导致Spring Boot不能从classpath下成功地找到模板。如果遇到这个问题,你可以在IDE里重新对classpath进行排序,将模块的类和资源放到第一位。或者,你可以配置模块的前缀为`classpath*:/templates/`,这样会查找classpath下的所有模板目录。 diff --git a/IV. Spring Boot features/27.1.9. ConfigurableWebBindingInitializer.md b/IV. Spring Boot features/27.1.9. ConfigurableWebBindingInitializer.md new file mode 100644 index 00000000..2a78d01f --- /dev/null +++ b/IV. Spring Boot features/27.1.9. ConfigurableWebBindingInitializer.md @@ -0,0 +1,3 @@ +### 27.1.9 ConfigurableWebBindingInitializer + +Spring MVC使用`WebBindingInitializer`为每个特殊的请求初始化相应的`WebDataBinder`,如果你创建自己的`ConfigurableWebBindingInitializer @Bean`,Spring Boot会自动配置Spring MVC使用它。 \ No newline at end of file diff --git a/IV. Spring Boot features/27.1.9. Error Handling.md b/IV. Spring Boot features/27.1.9. Error Handling.md deleted file mode 100644 index 8bd635c5..00000000 --- a/IV. Spring Boot features/27.1.9. Error Handling.md +++ /dev/null @@ -1,110 +0,0 @@ -### 27.1.9 错误处理 - -Spring Boot默认提供一个`/error`映射用来以合适的方式处理所有的错误,并将它注册为servlet容器中全局的 -错误页面。对于机器客户端(相对于浏览器而言,浏览器偏重于人的行为),它会产生一个具有详细错误,HTTP状态,异常信息的JSON响应。对于浏览器客户端,它会产生一个白色标签样式(whitelabel)的错误视图,该视图将以HTML格式显示同样的数据(可以添加一个解析为'error'的View来自定义它)。为了完全替换默认的行为,你可以实现`ErrorController`,并注册一个该类型的bean定义,或简单地添加一个`ErrorAttributes`类型的bean以使用现存的机制,只是替换显示的内容。 - -**注** `BasicErrorController`可以作为自定义`ErrorController`的基类,如果你想添加对新context type的处理(默认处理`text/html`),这会很有帮助。你只需要继承`BasicErrorController`,添加一个public方法,并注解带有`produces`属性的`@RequestMapping`,然后创建该新类型的bean。 - -你也可以定义一个`@ControllerAdvice`去自定义某个特殊controller或exception类型的JSON文档: -```java -@ControllerAdvice(basePackageClasses = FooController.class) -public class FooControllerAdvice extends ResponseEntityExceptionHandler { - - @ExceptionHandler(YourException.class) - @ResponseBody - ResponseEntity handleControllerException(HttpServletRequest request, Throwable ex) { - HttpStatus status = getStatus(request); - return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status); - } - - private HttpStatus getStatus(HttpServletRequest request) { - Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); - if (statusCode == null) { - return HttpStatus.INTERNAL_SERVER_ERROR; - } - return HttpStatus.valueOf(statusCode); - } - -} -``` -在以上示例中,如果跟`FooController`相同package的某个controller抛出`YourException`,一个`CustomerErrorType`类型的POJO的json展示将代替`ErrorAttributes`展示。 - -**自定义错误页面** - -如果想为某个给定的状态码展示一个自定义的HTML错误页面,你需要将文件添加到`/error`文件夹下。错误页面既可以是静态HTML(比如,任何静态资源文件夹下添加的),也可以是使用模板构建的,文件名必须是明确的状态码或一系列标签。 - -例如,映射`404`到一个静态HTML文件,你的目录结构可能如下: -```properties -src/ - +- main/ - +- java/ - | + - +- resources/ - +- public/ - +- error/ - | +- 404.html - +- -``` -使用FreeMarker模板映射所有`5xx`错误,你需要如下的目录结构: -```properties -src/ - +- main/ - +- java/ - | + - +- resources/ - +- templates/ - +- error/ - | +- 5xx.ftl - +- -``` -对于更复杂的映射,你可以添加实现`ErrorViewResolver`接口的beans: -```java -public class MyErrorViewResolver implements ErrorViewResolver { - - @Override - public ModelAndView resolveErrorView(HttpServletRequest request, - HttpStatus status, Map model) { - // Use the request or status to optionally return a ModelAndView - return ... - } - -} -``` -你也可以使用Spring MVC特性,比如[@ExceptionHandler方法](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers)和[@ControllerAdvice](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-controller-advice),`ErrorController`将处理所有未处理的异常。 - -**映射Spring MVC以外的错误页面** - -对于不使用Spring MVC的应用,你可以通过`ErrorPageRegistrar`接口直接注册`ErrorPages`。该抽象直接工作于底层内嵌servlet容器,即使你没有Spring MVC的`DispatcherServlet`,它们仍旧可以工作。 -```java -@Bean -public ErrorPageRegistrar errorPageRegistrar(){ - return new MyErrorPageRegistrar(); -} - -// ... - -private static class MyErrorPageRegistrar implements ErrorPageRegistrar { - - @Override - public void registerErrorPages(ErrorPageRegistry registry) { - registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - } - -} -``` -注.如果你注册一个`ErrorPage`,该页面需要被一个`Filter`处理(在一些非Spring web框架中很常见,比如Jersey,Wicket),那么该`Filter`需要明确注册为一个`ERROR`分发器(dispatcher),例如: -```java -@Bean -public FilterRegistrationBean myFilter() { - FilterRegistrationBean registration = new FilterRegistrationBean(); - registration.setFilter(new MyFilter()); - ... - registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); - return registration; -} -``` -(默认的`FilterRegistrationBean`不包含`ERROR` dispatcher类型)。 - -**WebSphere应用服务器的错误处理** - -当部署到一个servlet容器时,Spring Boot通过它的错误页面过滤器将带有错误状态的请求转发到恰当的错误页面。request只有在response还没提交时才能转发(forwarded)到正确的错误页面,而WebSphere应用服务器8.0及后续版本默认情况会在servlet方法成功执行后提交response,你需要设置`com.ibm.ws.webcontainer.invokeFlushAfterService`属性为`false`来关闭该行为。 diff --git "a/IV. Spring Boot features/27.2 The \342\200\230Spring WebFlux framework\342\200\231.md" "b/IV. Spring Boot features/27.2 The \342\200\230Spring WebFlux framework\342\200\231.md" deleted file mode 100644 index f6a672ee..00000000 --- "a/IV. Spring Boot features/27.2 The \342\200\230Spring WebFlux framework\342\200\231.md" +++ /dev/null @@ -1,62 +0,0 @@ -### 27.2 The ‘Spring WebFlux framework’ - -Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. Unlike Spring MVC, it does not require the Servlet API, is fully asynchronous and non-blocking, and implements the Reactive Streams specification through the Reactor project. - -Spring WebFlux comes in two flavors; the annotation-based one is quite close to the Spring MVC model we know: - -@RestController -@RequestMapping("/users") -public class MyRestController { - - @GetMapping("/{user}") - public Mono getUser(@PathVariable Long user) { - // ... - } - - @GetMapping("/{user}/customers") - Flux getUserCustomers(@PathVariable Long user) { - // ... - } - - @DeleteMapping("/{user}") - public Mono deleteUser(@PathVariable Long user) { - // ... - } - -} -‘WebFlux.fn’, the functional variant, separates the routing configuration from the actual handling of the requests: - -@Configuration -public class RoutingConfiguration { - - @Bean - public RouterFunction 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 getUser(ServerRequest request) { - // ... - } - - public Mono getUserCustomers(ServerRequest request) { - // ... - } - - public Mono 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. - -[Note] -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 like SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE). - diff --git "a/IV. Spring Boot features/27.2 The \342\200\234Spring WebFlux Framework\342\200\235.md" "b/IV. Spring Boot features/27.2 The \342\200\234Spring WebFlux Framework\342\200\235.md" new file mode 100644 index 00000000..faf29c8e --- /dev/null +++ "b/IV. Spring Boot features/27.2 The \342\200\234Spring WebFlux Framework\342\200\235.md" @@ -0,0 +1,64 @@ +### 27.2 Spring WebFlux框架 + +Spring WebFlux是Spring Framework 5.0中引入的新的响应式网络框架。不同与Spring MVC,它不需要Servlet API,是完全异步、非阻塞的,通过[Reactor项目](https://projectreactor.io/)实现了[Reactive Streams](http://www.reactive-streams.org/) 规范。 + +Spring WebFlux有两种风格:函数式和基于注解。基于注解的风格相当接近于Spring MVC模型,如下所示: +```java +@RestController +@RequestMapping("/users") +public class MyRestController { + + @GetMapping("/{user}") + public Mono getUser(@PathVariable Long user) { + // ... + } + + @GetMapping("/{user}/customers") + public Flux getUserCustomers(@PathVariable Long user) { + // ... + } + + @DeleteMapping("/{user}") + public Mono deleteUser(@PathVariable Long user) { + // ... + } + +} +``` +“WebFlux.fn”——函数式变体,从请求的实际处理中分离了路由配置,如下所示: +```java +@Configuration +public class RoutingConfiguration { + + @Bean + public RouterFunction 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 getUser(ServerRequest request) { + // ... + } + + public Mono getUserCustomers(ServerRequest request) { + // ... + } + + public Mono deleteUser(ServerRequest request) { + // ... + } +} +``` +WebFlux是Spring框架的一部分。详细信息请查看它的[参考文档](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web-reactive.html#webflux-fn)。 + +**注** 你可以定义多个`RouterFunction` bean来模块化路由的定义。如果你需要应用优先级,可以给bean排序。 + +给你的应用添加`spring-boot-starter-webflux`模块,开始使用。 + +**注** 在你的应用里同时添加`spring-boot-starter-web`和`spring-boot-starter-webflux`模块,会使Spring Boot自动配置Spring MVC,而不是WebFlux。这种行为是因为许多Spring开发者为了使用响应式的`WebClient`,往他们的Spring MVC应用里添加`spring-boot-starter-webflux`。你可以设置应用类型为`SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`,强制Spring Boot自动配置WebFlux。 \ No newline at end of file diff --git a/IV. Spring Boot features/27.2.1 Spring WebFlux Auto-configuration.md b/IV. Spring Boot features/27.2.1 Spring WebFlux Auto-configuration.md new file mode 100644 index 00000000..6522e9ab --- /dev/null +++ b/IV. Spring Boot features/27.2.1 Spring WebFlux Auto-configuration.md @@ -0,0 +1,11 @@ +### 27.2.1 Spring WebFlux自动配置 + +Spring Boot为Spring WebFlux提供了自动配置。这些配置在大多数应用里能够很好地工作。 + +自动配置会添加以下特性: +- 为`HttpMessageReader`和`HttpMessageWriter`实例配置编解码器([在此文档的后面章节](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-webflux-httpcodecs)有描述)。 +- 支持服务静态内容,包括对WebJars的支持 ([在此文档的后面章节](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-static-content)有描述)。 + +如果你想保持Spring Boot WebFlux特性,并添加额外的[WebFlux配置](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#web-reactive),你可以添加你自己的`WebFluxConfigurer`类型的`@Configuration`类,但是不加`@EnableWebFlux`。 + +如果你想完全控制Spring WebFlux,你可以添加你自己的`@Configuration`,并用`@EnableWebFlux`标注。 diff --git a/IV. Spring Boot features/27.2.1 Spring WebFlux auto-configuration.md b/IV. Spring Boot features/27.2.1 Spring WebFlux auto-configuration.md deleted file mode 100644 index 95c0ab89..00000000 --- a/IV. Spring Boot features/27.2.1 Spring WebFlux auto-configuration.md +++ /dev/null @@ -1,11 +0,0 @@ -### 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. \ No newline at end of file diff --git a/IV. Spring Boot features/27.2.2 HTTP Codecs with HttpMessageReaders and HttpMessageWriters.md b/IV. Spring Boot features/27.2.2 HTTP Codecs with HttpMessageReaders and HttpMessageWriters.md new file mode 100644 index 00000000..eda3b239 --- /dev/null +++ b/IV. Spring Boot features/27.2.2 HTTP Codecs with HttpMessageReaders and HttpMessageWriters.md @@ -0,0 +1,23 @@ +### 27.2.2 HTTP编解码器——HttpMessageReaders与HttpMessageWriters + +Spring WebFlux使用`HttpMessageReader`和`HttpMessageWriter`接口转换HTTP请求与回应。它们由`CodecConfigurer`配置——通过查看类路径里可用的库配置默认值。 + +Spring Boot通过使用`CodecCustomizer`实例,更进一步地实现自定义。比如,`spring.jackson.*`配置键被应用于Jackson编解码器。 + +如果你需要添加或自定义编解码器,你可以创建一个自定义的`CodecCustomizer`组件,如下所示: +```java +import org.springframework.boot.web.codec.CodecCustomizer; + +@Configuration +public class MyConfiguration { + + @Bean + public CodecCustomizer myCodecCustomizer() { + return codecConfigurer -> { + // ... + } + } + +} +``` +你也可以利用[Spring Boot的自定义JSON序列化器和反序列化器](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-json-components)。 diff --git a/IV. Spring Boot features/27.2.2 HTTP codecs with HttpMessageReaders and HttpMessageWriters.md b/IV. Spring Boot features/27.2.2 HTTP codecs with HttpMessageReaders and HttpMessageWriters.md deleted file mode 100644 index 56f5f96b..00000000 --- a/IV. Spring Boot features/27.2.2 HTTP codecs with HttpMessageReaders and HttpMessageWriters.md +++ /dev/null @@ -1,22 +0,0 @@ -### 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. - -If you need to add or customize codecs you can create a custom CodecCustomizer component: - -import org.springframework.boot.web.codec.CodecCustomizer; - -@Configuration -public class MyConfiguration { - - @Bean - public CodecCustomizer myCodecCustomizer() { - return codecConfigurer -> { - // ... - } - } - -} -You can also leverage Boot’s custom JSON serializers and deserializers. \ No newline at end of file diff --git a/IV. Spring Boot features/27.2.3 Static Content.md b/IV. Spring Boot features/27.2.3 Static Content.md index 8fcb2966..bc8c64d0 100644 --- a/IV. Spring Boot features/27.2.3 Static Content.md +++ b/IV. Spring Boot features/27.2.3 Static Content.md @@ -1,13 +1,13 @@ -### 27.2.3 Static Content +### 27.2.3 静态内容 -By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath. It uses the ResourceWebHandler from Spring WebFlux so you can modify that behavior by adding your own WebFluxConfigurer and overriding the addResourceHandlers method. +默认情况下,Spring Boot从类路径下的`/static`(或者是`/public`、`/resources`、`/META-INF/resources`)文件夹提供静态内容。这是通过Spring WebFlux的`ResourceWebHandler`实现的。你可以添加你自己的`WebFluxConfigurer`并覆写`addResourceHandlers`方法来改变该行为(加载静态文件)。 -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.webflux.static-path-pattern`属性进行调整。例如,迁移所有的资源到`/resources/**`可以按照如下方式实现: +```properties +spring.webflux.static-path-pattern=/resources/** +``` +你可以设置`spring.resources.static-locations`属性自定义静态资源的位置(配置一系列目录位置代替默认的值)。这样,Spring Boot会在你自定义的位置查找欢迎页。所以,要是在哪个位置有`index.html`,它就会是应用的主页。 -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. +此外,除了上述标准的静态资源位置,有个例外情况是[Webjars内容](http://www.webjars.org/)。任何在`/webjars/**`路径下的资源都将从jar文件中提供,只要它们以Webjars的格式打包。 -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. - -[Tip] -Spring WebFlux applications don’t strictly depend on the Servlet API, so they can’t be deployed as war and have no use of the src/main/webapp directory. +**注** Spring WebFlux应用并不完全依赖Servlet API,所以它们不能用war文件部署,也不使用`src/main/webapp`目录。 diff --git a/IV. Spring Boot features/27.2.4 Template Engines.md b/IV. Spring Boot features/27.2.4 Template Engines.md new file mode 100644 index 00000000..bb7d4dd0 --- /dev/null +++ b/IV. Spring Boot features/27.2.4 Template Engines.md @@ -0,0 +1,11 @@ +### 27.2.4 模板引擎 + +除了REST网络服务,你也可以将Spring WebFlux用于动态HTML内容。Spring WebFlux支持许多的模板技术,包括Thymeleaf、FreeMarker与Mustache。 + +Spring Boot支持以下模板引擎的自动配置: + +- [FreeMarker](http://freemarker.org/docs/) +- [Thymeleaf](http://www.thymeleaf.org/) +- [Mustache](https://mustache.github.io/) + +当你用默认配置使用这些模板引擎时,你的模板会自动从`src/main/resources/templates`获取。 diff --git a/IV. Spring Boot features/27.2.4 Template engines.md b/IV. Spring Boot features/27.2.4 Template engines.md deleted file mode 100644 index 16db8acc..00000000 --- a/IV. Spring Boot features/27.2.4 Template engines.md +++ /dev/null @@ -1,10 +0,0 @@ -### 27.2.4 Template engines - -As well as REST web services, you can also use Spring WebFlux to serve dynamic HTML content. Spring WebFlux supports a variety of templating technologies including Thymeleaf, FreeMarker and Mustache. - -Spring Boot includes auto-configuration support for the following templating engines: - -FreeMarker -Thymeleaf -Mustache -When you’re using one of these templating engines with the default configuration, your templates will be picked up automatically from src/main/resources/templates. diff --git a/IV. Spring Boot features/27.2.5 Error Handling.md b/IV. Spring Boot features/27.2.5 Error Handling.md new file mode 100644 index 00000000..7196c286 --- /dev/null +++ b/IV. Spring Boot features/27.2.5 Error Handling.md @@ -0,0 +1,55 @@ +### 27.2.5 错误处理 + +Spring Boot提供了`WebExceptionHandler`,用一种明智的方式处理所有的错误。在处理顺序上,它的位置在WebFlux提供处理器之前。对于机器客户端,它会产生带有错误的详细描述(HTTP状态与异常信息)的JSON响应。对于浏览器客户端,“whitelabel”错误处理器会以HTML格式渲染相同的数据。你也可以提供你自己的HTML模版来显示错误(查看[下一章节](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-webflux-error-handling-custom-error-pages))。 + +自定义这个特性的第一步时常需要使用现存的机制,但是替换或者添加错误的内容。为此,你可以添加`ErrorAttributes`类型的bean。 + +为了改变错误处理的行为,你可以实现`ErrorWebExceptionHandler`,并注册一个那种类型的bean定义。因为 `WebExceptionHandler`的级别相当低,Spring Boot提供了方便的`AbstractErrorWebExceptionHandler`,让你以WebFlux函数式方法处理错误,如下所示: +```java +public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { + + // Define constructor here + + @Override + protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) { + + return RouterFunctions + .route(aPredicate, aHandler) + .andRoute(anotherPredicate, anotherHandler); + } + +} +``` +你也可以直接继承`DefauLambdatErrorWebExceptionHandler`,并重写特定的方法。 + +**自定义错误页** + +如果你想要给某个给定的状态码显示自定义的HTML错误页,你可以在`/error`文件夹下添加一个文件。错误页可以是静态的HTML(也就是,添加在任何的静态资源文件夹下面),或者使用模版构建。文件名应当是状态码,或者是一系列掩码。 + +比如,为了将`404`映射到一个静态HTML文件,你的文件夹结构将会如下: + +``` +src/ + +- main/ + +- java/ + | + + +- resources/ + +- public/ + +- error/ + | +- 404.html + +- +``` + +使用Mustache模版映射所有的`5xx`错误,你的文件夹结构将会如下: + +``` +src/ + +- main/ + +- java/ + | + + +- resources/ + +- templates/ + +- error/ + | +- 5xx.mustache + +- +``` \ No newline at end of file diff --git a/IV. Spring Boot features/27.2.6 Web Filters.md b/IV. Spring Boot features/27.2.6 Web Filters.md new file mode 100644 index 00000000..5daad3e5 --- /dev/null +++ b/IV. Spring Boot features/27.2.6 Web Filters.md @@ -0,0 +1,11 @@ +### 27.2.6 网络过滤器 + +Spring WebFlux提供了`WebFilter`接口。它可以用来过滤HTTP请求-响应交换。在应用上下文里的`WebFilter`将会自动用于过滤每一个交换。 + +过滤器的顺序很重要。它们可以实现`Ordered`,或者标注`@Order`。Spring Boot会为你自动配置网络过滤器,顺序如下: + +|Web Filter|Order| +|--|--| +|`MetricsWebFilter`|`Ordered.HIGHEST_PRECEDENCE + 1`| +|`WebFilterChainProxy `(Spring Security)|`-100`| +|`HttpTraceWebFilter`|`Ordered.LOWEST_PRECEDENCE - 10`| \ No newline at end of file diff --git a/IV. Spring Boot features/27.3. JAX-RS and Jersey.md b/IV. Spring Boot features/27.3. JAX-RS and Jersey.md index e3582a67..c9c39df5 100644 --- a/IV. Spring Boot features/27.3. JAX-RS and Jersey.md +++ b/IV. Spring Boot features/27.3. JAX-RS and Jersey.md @@ -2,7 +2,7 @@ 如果你更喜欢JAX-RS为REST端点提供的编程模型,可以使用相应的实现代替Spring MVC。如果将Jersey 1.x和Apache CXF的`Servlet`或`Filter`注册到应用上下文中,那它们可以很好的工作。Spring对Jersey 2.x有一些原生支持,所以在Spring Boot中也为它提供了自动配置及一个starter。 -想要使用Jersey 2.x,只需添加`spring-boot-starter-jersey`依赖,然后创建一个`ResourceConfig`类型的`@Bean`,用于注册所有的端点(endpoints): +想要使用Jersey 2.x,需要添加`spring-boot-starter-jersey`依赖,然后创建一个`ResourceConfig`类型的`@Bean`,用于注册所有的端点(endpoints),如下所示: ```java @Component public class JerseyConfig extends ResourceConfig { @@ -15,7 +15,7 @@ public class JerseyConfig extends ResourceConfig { 你也可以注册任意数量的,实现`ResourceConfigCustomizer`的beans来进一步自定义。 -所有注册的端点都需注解`@Components`和HTTP资源annotations(比如`@GET`): +所有注册的端点都需注解`@Components`和HTTP资源annotations(比如`@GET`),如下所示: ```java @Component @Path("/hello") @@ -26,8 +26,8 @@ public class Endpoint { } } ``` -由于`Endpoint`是一个Spring组件(`@Component`),所以它的生命周期受Spring管理,你可以使用`@Autowired`添加依赖,也可以使用`@Value`注入外部配置。Jersey的servlet会被注册,并默认映射到`/*`,你可以将`@ApplicationPath`添加到`ResourceConfig`来改变该映射。 +由于`Endpoint`是一个Spring组件(`@Component`),所以它的生命周期受Spring管理,你可以使用`@Autowired`注解注入依赖,也可以使用`@Value`注解注入外部配置。Jersey的servlet会被注册,并默认映射到`/*`,你可以将`@ApplicationPath`添加到`ResourceConfig`来改变该映射。 -默认情况下,Jersey将以Servlet的形式注册为一个`ServletRegistrationBean`类型的`@Bean`,name为`jerseyServletRegistration`,该servlet默认会延迟初始化,不过可以通过`spring.jersey.servlet.load-on-startup`自定义。通过创建相同name的bean,你可以禁用或覆盖框架默认产生的bean。设置`spring.jersey.type=filter`可以使用Filter的形式代替Servlet,相应的`@Bean`类型变为`jerseyFilterRegistration`,该filter有一个`@Order`属性,你可以通过`spring.jersey.filter.order`设置。Servlet和Filter注册时都可以使用`spring.jersey.init.*`定义一个属性集合传递给init参数。 +默认情况下,Jersey将以Servlet的形式注册为一个`ServletRegistrationBean`类型的`@Bean`,name为`jerseyServletRegistration`,该servlet默认会延迟初始化,不过可以通过`spring.jersey.servlet.load-on-startup`自定义。通过创建相同name的bean,你可以禁用或覆盖框架默认产生的bean。设置`spring.jersey.type=filter`可以使用filter的形式代替servlet,相应的`@Bean`类型变为`jerseyFilterRegistration`,该filter有一个`@Order`属性,你可以通过`spring.jersey.filter.order`设置。servlet和filter注册时都可以使用`spring.jersey.init.*`定义一个属性集合传递给init参数。 -这里有一个[Jersey示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples/spring-boot-sample-jersey),你可以查看如何设置相关事项。 +这里有一个[Jersey示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-jersey),你可以查看如何设置相关事项。还有一个[Jersey 1.x示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-jersey1)。注意,在Jersey 1.x示例里,spring-boot maven plugin被配置为拆开某些Jersey jars。这样,它们就会被JAX-RS实现扫描(因为示例要求它们在`Filter`注册里接受扫描)。如果你的JAX-RS资源以内部jars的方法打包,你可能需要做同样的事情。 diff --git a/IV. Spring Boot features/27.4 Embedded Servlet Container Support.md b/IV. Spring Boot features/27.4 Embedded Servlet Container Support.md new file mode 100644 index 00000000..065c71cd --- /dev/null +++ b/IV. Spring Boot features/27.4 Embedded Servlet Container Support.md @@ -0,0 +1,5 @@ +### 27.4 内嵌servlet容器支持 + +Spring Boot支持内嵌的Tomcat、Jetty和Undertow服务器。多数开发者使用合适的"Starter"来获取一个完全配置好的实例即可。内嵌服务器默认监听8080端口的HTTP请求。 + +**警告⚠️** 如果你在CentOS上使用Tomcat,需要注意:默认情况下,一个临时的目录会被用于存储编译完成的JSPs和上传的文件等。当你的应用运行时出错,这个目录可能会被`tmpwatch`删除。为了避免这种情况,你需要自定义`tmpwatch`。这样`tomcat.*`目录才不会被删除。或者,配置`server.tomcat.basedir`。这样内嵌的Tomcat会使用一个不同的位置。 diff --git a/IV. Spring Boot features/27.4 Embedded servlet container support.md b/IV. Spring Boot features/27.4 Embedded servlet container support.md deleted file mode 100644 index 856d740a..00000000 --- a/IV. Spring Boot features/27.4 Embedded servlet container support.md +++ /dev/null @@ -1,5 +0,0 @@ -### 27.4 内嵌servlet容器支持 - -Spring Boot支持内嵌的Tomcat, Jetty和Undertow服务器,多数开发者只需要使用合适的'Starter'来获取一个完全配置好的实例即可,内嵌服务器默认监听8080端口的HTTP请求。 - -**警告⚠️** 如果你在CentOS上使用Tomcat,需要注意:默认情况下,一个临时的目录会被用于存储编译完成的JSPs和上传的文件等。当你的应用运行时出错,这个目录可能会被`tmpwatch`删除。为了避免这种情况,你需要自定义`tmpwatch`。这样`tomcat.*`目录才不会被删除。或者,配置`server.tomcat.basedir`。这样内嵌的Tomcat会使用一个不同的位置。 diff --git a/IV. Spring Boot features/27.4.1 Servlets, Filters, and listeners.md b/IV. Spring Boot features/27.4.1 Servlets, Filters, and listeners.md index 9fa91a51..310ffb5a 100644 --- a/IV. Spring Boot features/27.4.1 Servlets, Filters, and listeners.md +++ b/IV. Spring Boot features/27.4.1 Servlets, Filters, and listeners.md @@ -1,9 +1,22 @@ -### 27.4.1 Servlets, Filters和listeners +### 27.4.1 Servlets、Filters和listeners -使用内嵌servlet容器时,你可以通过使用Spring beans或扫描Servlet组件的方式注册Servlets,Filters及特定Servlet相关的所有listeners(比如`HttpSessionListener`)。 +使用内嵌servlet容器时,你可以通过使用Spring beans或扫描Servlet组件的方式注册servlets,filters及特定Servlet相关的所有listeners(比如`HttpSessionListener`)。 -**将Servlets,Filters和listeners注册为Spring beans** +**将Servlet、Filter和listener注册为Spring bean** -所有`Servlet`,`Filter`或Servlet `*Listener`实例,只要是Spring bean,都会注册到内嵌容器中。如果想在配置期间引用`application.properties`的属性,这是非常方便的。默认情况下,如果上下文只包含单个Servlet,那它将被映射到`/`。如果存在多个Servlet beans,那么bean的名称将被用作路径的前缀,过滤器将映射到`/*`。 +所有`Servlet`,`Filter`或servlet `*Listener`实例,只要是Spring bean,都会注册到内嵌容器中。如果想在配置期间引用`application.properties`的属性,这是非常方便的。默认情况下,如果上下文只包含单个Servlet,那它将被映射到`/`。如果存在多个servlet beans,那么bean的名称将被用作路径的前缀,过滤器将映射到`/*`。 如果基于约定(convention-based)的映射不够灵活,你可以使用`ServletRegistrationBean`,`FilterRegistrationBean`,`ServletListenerRegistrationBean`实现完全的控制。 + +Spring Boot带有许多的自动配置。它们可能定义Filter bean。这里有一些Filter以及它们的顺序的例子(低位意味着更高的优先级)。 + +| Servlet Filter | Order | +|----------|-------------| +| `OrderedCharacterEncodingFilter` | `Ordered.HIGHEST_PRECEDENCE` | +| `WebMvcMetricsFilter` | `Ordered.HIGHEST_PRECEDENCE + 1` | +| `ErrorPageFilter` | `Ordered.HIGHEST_PRECEDENCE + 1` | +| `HttpTraceFilter` | `Ordered.LOWEST_PRECEDENCE - 10` | + +无序的Filter bean通常是安全的。 + +如果需要一个特定的顺序,你应当避免配置一个在`Ordered.HIGHEST_PRECEDENCE`上读取请求体的Filter。因为它可能违反你的应用的字符编码配置。如果一个Servlet filter包裹请求,它应当被配置一个顺序。此顺序不高于`FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER`。 diff --git a/IV. Spring Boot features/27.4.2 Servlet Context Initialization.md b/IV. Spring Boot features/27.4.2 Servlet Context Initialization.md index 77536d3a..9ad6372c 100644 --- a/IV. Spring Boot features/27.4.2 Servlet Context Initialization.md +++ b/IV. Spring Boot features/27.4.2 Servlet Context Initialization.md @@ -1,4 +1,5 @@ ### 27.4.2 Servlet上下文初始化 + 内嵌servlet容器不会直接执行Servlet 3.0+的`javax.servlet.ServletContainerInitializer`接口,或Spring的`org.springframework.web.WebApplicationInitializer`接口,这样设计的目的是降低war包内运行的第三方库破坏Spring Boot应用的风险。 如果需要在Spring Boot应用中执行servlet上下文初始化,你需要注册一个实现`org.springframework.boot.web.servlet.ServletContextInitializer`接口的bean。`onStartup`方法可以获取`ServletContext`,如果需要的话可以轻松用来适配一个已存在的`WebApplicationInitializer`。 diff --git a/IV. Spring Boot features/27.4.3 The ServletWebServerApplicationContext.md b/IV. Spring Boot features/27.4.3 The ServletWebServerApplicationContext.md index 3a499574..fe9a1afc 100644 --- a/IV. Spring Boot features/27.4.3 The ServletWebServerApplicationContext.md +++ b/IV. Spring Boot features/27.4.3 The ServletWebServerApplicationContext.md @@ -1,5 +1,5 @@ ### 27.4.3 The ServletWebServerApplicationContext -Spring Boot底层使用一种新的`ApplicationContext`类型,用于对内嵌servlet容器的支持。`ServletWebServerApplicationContext`是一种特殊类型的`WebApplicationContext`,它通过搜索到的单个`ServletWebServerFactory` bean来启动自己,通常`TomcatServletWebServerFactory`,`JettyServletWebServerFactory`或`UndertowServletWebServerFactory`将被自动配置。 +Spring Boot底层使用一种不同的`ApplicationContext`类型,用于对内嵌servlet容器的支持。`ServletWebServerApplicationContext`是一种特殊类型的`WebApplicationContext`,它通过搜索到的单个`ServletWebServerFactory` bean来启动自己,通常`TomcatServletWebServerFactory`,`JettyServletWebServerFactory`或`UndertowServletWebServerFactory`将被自动配置。 -**注** 你不需要关心这些实现类,大部分应用都能被自动配置,并根据你的行为创建合适的`ApplicationContext`和`ServletWebServerFactory`。 +**注** 你通常不需要关心这些实现类,大部分应用都能被自动配置,并根据你的行为创建合适的`ApplicationContext`和`ServletWebServerFactory`。 diff --git a/IV. Spring Boot features/27.4.4 Customizing Embedded Servlet Containers.md b/IV. Spring Boot features/27.4.4 Customizing Embedded Servlet Containers.md new file mode 100644 index 00000000..a94b2c43 --- /dev/null +++ b/IV. Spring Boot features/27.4.4 Customizing Embedded Servlet Containers.md @@ -0,0 +1,47 @@ +### 27.4.4 自定义内嵌servlet容器 + +常见的Servlet容器配置可以通过Spring `Environment`进行设置,通常将这些属性定义到`application.properties`文件中。 + +常见的服务器配置包括: + +1. 网络设置:监听进入Http请求的端口(`server.port`),接口绑定地址`server.address`等。 +2. Session设置:session是否持久化(`server.servlet.session.persistence`),session超时时间(`server.servlet.session.timeout`),数据存放位置(`server.servlet.session.store-dir`),session-cookie配置(`server.servlet.session.cookie.*`)。 +3. Error管理:错误页面的位置(`server.error.path`)等。 +4. [SSL](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-configure-ssl)。 +5. [HTTP压缩](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#how-to-enable-http-response-compression) + +Spring Boot会尽量暴露常用设置,但这并不总是可能的。对于不可能的情况,可以使用专用的命名空间提供server-specific配置(查看`server.tomcat`,`server.undertow`)。例如,可以根据内嵌servlet容器的特性对[access logs](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-configure-accesslogs)进行不同的设置。 + +**注** 具体参考[ServerProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)。 + +**编程方式的自定义** + +如果需要以编程方式配置内嵌servlet容器,你可以注册一个实现`WebServerFactoryCustomizer`接口的Spring bean。`WebServerFactoryCustomizer`能够获取到包含很多自定义setter方法的`ConfigurableServletWebServerFactory`,你可以通过这些setter方法对内嵌容器自定义。Tomcat,Jetty和Undertow有独立的变体。下面的例子展示了以编程的方式设置端口: +```java +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.stereotype.Component; + +@Component +public class CustomizationBean implements WebServerFactoryCustomizer { + @Override + public void customize(ConfigurableServletWebServerFactory server) { + server.setPort(9000); + } +} +``` + +**直接自定义ConfigurableServletWebServerFactory** + +如果以上自定义手法过于受限,你可以自己注册`TomcatServletWebServerFactory`,`JettyServletWebServerFactory`或`UndertowServletWebServerFactory`。 +```java +@Bean +public ConfigurableServletWebServerFactory webServerFactory() { + TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); + factory.setPort(9000); + factory.setSessionTimeout(10, TimeUnit.MINUTES); + factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"); + return factory; +} +``` +很多配置选项提供setter方法,有的甚至提供一些受保护的钩子方法以满足你的某些特殊需求,具体参考源码或相关文档。 diff --git a/IV. Spring Boot features/27.4.4 Customizing embedded servlet containers.md b/IV. Spring Boot features/27.4.4 Customizing embedded servlet containers.md deleted file mode 100644 index 98b638b0..00000000 --- a/IV. Spring Boot features/27.4.4 Customizing embedded servlet containers.md +++ /dev/null @@ -1,47 +0,0 @@ -### 27.4.4 自定义内嵌servlet容器 - -常见的Servlet容器配置可以通过Spring `Environment`进行设置,通常将这些属性定义到`application.properties`文件中。 - -常见的服务器配置包括: - -1. 网络设置:监听进入Http请求的端口(`server.port`),接口绑定地址`server.address`等。 -2. Session设置:session是否持久化(`server.session.persistence`),session超时时间(`server.session.timeout`),session数据存放位置(`server.session.store-dir`),session-cookie配置(`server.session.cookie.*`)。 -3. Error管理:错误页面的位置(`server.error.path`)等。 -4. [SSL](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-configure-ssl)。 -5. [HTTP压缩](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#how-to-enable-http-response-compression) - -Spring Boot会尽量暴露常用设置,但这并不总是可能的。对于不可能的情况,可以使用专用的命名空间提供server-specific配置(查看`server.tomcat`,`server.undertow`)。例如,可以根据内嵌servlet容器的特性对[access logs](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-configure-accesslogs)进行不同的设置。 - -**注** 具体参考[ServerProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)。 - -**编程方式的自定义** - -如果需要以编程方式配置内嵌servlet容器,你可以注册一个实现`WebServerFactoryCustomizer`接口的Spring bean。`WebServerFactoryCustomizer`能够获取到包含很多自定义setter方法的`ConfigurableServletWebServerFactory`,你可以通过这些setter方法对内嵌容器自定义。 -```java -import org.springframework.boot.web.server.WebServerFactoryCustomizer; -import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; -import org.springframework.stereotype.Component; - -@Component -public class CustomizationBean implements WebServerFactoryCustomizer { - @Override - public void customize(ConfigurableServletWebServerFactory server) { - server.setPort(9000); - } -} -``` - -**直接自定义ConfigurableServletWebServerFactory** - -如果以上自定义手法过于受限,你可以自己注册`TomcatServletWebServerFactory`,`JettyServletWebServerFactory`或`UndertowServletWebServerFactory`。 -```java -@Bean -public ConfigurableServletWebServerFactory webServerFactory() { - TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); - factory.setPort(9000); - factory.setSessionTimeout(10, TimeUnit.MINUTES); - factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"); - return factory; -} -``` -很多配置选项提供setter方法,有的甚至提供一些受保护的钩子方法以满足你的某些特殊需求,具体参考源码或相关文档。 diff --git a/IV. Spring Boot features/27.4.5 JSP Limitations.md b/IV. Spring Boot features/27.4.5 JSP Limitations.md new file mode 100644 index 00000000..7b19d07d --- /dev/null +++ b/IV. Spring Boot features/27.4.5 JSP Limitations.md @@ -0,0 +1,10 @@ +### 27.4.5 JSP的限制 + +当使用内嵌servlet容器运行Spring Boot应用时(并打包成一个可执行的存档archive),容器对JSP的支持有一些限制: + +1. Tomcat只支持war的打包方式,不支持可执行jar。 +2. Jetty只支持war的打包方式。 +3. Undertow不支持JSPs。 +4. 创建的自定义`error.jsp`页面不会覆盖默认的[error handling](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-error-handling)视图。 + +这里有个[JSP示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp),你可以查看如何设置相关事项。 diff --git a/IV. Spring Boot features/27.4.5 JSP limitations.md b/IV. Spring Boot features/27.4.5 JSP limitations.md deleted file mode 100644 index 927de6b5..00000000 --- a/IV. Spring Boot features/27.4.5 JSP limitations.md +++ /dev/null @@ -1,10 +0,0 @@ -### 27.4.5 JSP的限制 - -当使用内嵌servlet容器运行Spring Boot应用时(并打包成一个可执行的存档archive),容器对JSP的支持有一些限制: - -1. Tomcat只支持war的打包方式,不支持可执行jar。 -2. Jetty只支持war的打包方式。 -3. Undertow不支持JSPs。 -4. 创建的自定义`error.jsp`页面不会覆盖默认的[error handling](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-error-handling)视图。 - -这里有个[JSP示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp),你可以查看如何设置相关事项。 diff --git a/IV. Spring Boot features/28. Security.md b/IV. Spring Boot features/28. Security.md index 21374080..ec2acace 100644 --- a/IV. Spring Boot features/28. Security.md +++ b/IV. Spring Boot features/28. Security.md @@ -1,29 +1,19 @@ ### 28. 安全 -如果添加了Spring Security的依赖,那么web应用默认对所有的HTTP路径(也称为终点,端点,表示API的具体网址)使用'basic'认证。为了给web应用添加方法级别(method-level)的保护,你可以添加`@EnableGlobalMethodSecurity`并使用想要的设置,其他信息参考[Spring Security Reference](http://docs.spring.io/spring-security/site/docs/4.1.3.RELEASE/reference/htmlsingle#jc-method)。 +如果Spring Security在类路径上,那么web应用默认是安全的。Spring Boot依靠Spring Security的内容协商策略,决定是使用httpBasic,还是formLogin。为了给web应用添加方法级别(method-level)的保护,你可以添加`@EnableGlobalMethodSecurity`并使用想要的设置。其它信息参考[Spring Security参考指南](https://docs.spring.io/spring-security/site/docs/5.0.3.RELEASE/reference/htmlsingle#jc-method)。 -默认的`AuthenticationManager`只有一个用户('user'的用户名和随机密码会在应用启动时以INFO日志级别打印出来),如下: +默认的`AuthenticationManager`只有一个用户。用户名是user,密码随机,会在应用启动时以INFO日志级别打印出来。如下: ```java -Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 +Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 ``` **注** 如果你对日志配置进行微调,确保`org.springframework.boot.autoconfigure.security`类别记录日志级别为`INFO`,否则默认的密码不会打印出来。 -你可以通过设置`security.user.password`改变默认密码,这些和其他有用的属性通过[SecurityProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java)(以"security"为前缀的属性)被外部化了。 +你可以通过提供`spring.security.user.name`和`spring.security.user.password`,改变用户名和密码。 -默认的安全配置是通过`SecurityAutoConfiguration`,`SpringBootWebSecurityConfiguration`(用于web安全),`AuthenticationManagerConfiguration`(可用于非web应用的认证配置)进行管理的。你可以添加一个`@EnableWebSecurity` bean来彻底关掉Spring Boot的默认配置。为了对它进行自定义,你需要使用外部的属性配置和`WebSecurityConfigurerAdapter`类型的beans(比如,添加基于表单的登陆)。 +在web应用中,你默认能得到如下的基本特性: -**注** 如果你添加`@EnableWebSecurity`,同时也禁用了执行器安全,你将在整个应用里得到默认的基于表单的登录,除非你添加了一个自定义的`WebSecurityConfigurerAdapter`。 +- 一个`UserDetailsService`(如果是WebFlux应用的话,则是`ReactiveUserDetailsService`)bean,存储在内存中。还有一个用户,用户的密码是生成的(关于这个用户的属性,请查看[`SecurityProperties.User`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/SecurityProperties.User.html))。 +- 应用在整个应用上的基于表单的登录或是HTTP Basic security(取决于Content-Type)。如果执行器在类路径上,则包含执行器端点。 +- 一个`DefaultAuthenticationEventPublisher`,用来发布认证事件。 -想要关闭认证管理的配置,你可以添加一个`AuthenticationManager`类型的bean,或在`@Configuration`类的某个方法里注入`AuthenticationManagerBuilder`来配置全局的`AuthenticationManager`。这里有一些安全相关的[Spring Boot应用示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples/)可以拿来参考。 - -在web应用中你能得到的开箱即用的基本特性如下: - -1. 一个使用内存存储的`AuthenticationManager` bean和一个用户(查看`SecurityProperties.User`获取user的属性)。 -2. 忽略(不保护)常见的静态资源路径(`/css/**, /js/**, /images/**`,`/webjars/**`和 `**/favicon.ico`)。 -3. 对其他所有路径实施HTTP Basic安全保护。 -4. 安全相关的事件会发布到Spring的`ApplicationEventPublisher`(成功和失败的认证,拒绝访问)。 -5. Spring Security提供的常见底层特性(HSTS, XSS, CSRF, 缓存)默认都被开启。 - -上述所有特性都能通过外部配置(`security.*`)打开,关闭,或修改。想要覆盖访问规则而不改变其他自动配置的特性,你可以添加一个注解`@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)`的`WebSecurityConfigurerAdapter`类型的`@Bean`。 - -**注** `WebSecurityConfigurerAdapter`默认会匹配所有路径,如果不想完全覆盖Spring Boot自动配置的访问规则,你可以精确的配置想要覆盖的路径。 +你可以通过添加一个bean,为它提供一个不同的`AuthenticationEventPublisher`。 diff --git a/IV. Spring Boot features/28.1 MVC Security.md b/IV. Spring Boot features/28.1 MVC Security.md new file mode 100644 index 00000000..a75f03e1 --- /dev/null +++ b/IV. Spring Boot features/28.1 MVC Security.md @@ -0,0 +1,7 @@ +### 28.1 MVC安全 + +默认的安全配置由`SecurityAutoConfiguration`以及从其它地方导入的类(`SpringBootWebSecurityConfiguration`用于web安全,`AuthenticationManagerConfiguration`用于认证配置,也与非web应用相关)实现的。你可以添加一个`WebSecurityConfigurerAdapter`类型的bean,来彻底关掉默认的web应用安全配置(这样做不会禁用认证管理者配置或者Actuator的安全)。 + +为了关闭认证管理者配置,你可以添加`UserDetailsService`、`AuthenticationProvider`、或是`AuthenticationManager`类型的bean。在[Spring Boot示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/)里有几个安全的应用,里面包含了一些常见用例。 + +访问规则可以通过添加自定义的`WebSecurityConfigurerAdapter`覆盖。Spring Boot提供了便捷的方法。它们可以用来覆盖执行器端点和静态资源的访问规则。`EndpointRequest`可以用来创建基于`management.endpoints.web.base-path`属性的`RequestMatcher`。`PathRequest`可以用来创建常用位置上的资源的`RequestMatcher`。 diff --git a/IV. Spring Boot features/28.1 OAuth2.md b/IV. Spring Boot features/28.1 OAuth2.md deleted file mode 100644 index 80792651..00000000 --- a/IV. Spring Boot features/28.1 OAuth2.md +++ /dev/null @@ -1,3 +0,0 @@ -###28.1 OAuth2 -如果添加了`spring-security-oauth2`依赖,你可以利用自动配置简化认证(Authorization)或资源服务器(Resource Server)的设置,详情参考[Spring Security OAuth 2 Developers Guide](http://projects.spring.io/spring-security-oauth/docs/oauth2.html)。 - diff --git a/IV. Spring Boot features/28.1.1 Authorization Server.md b/IV. Spring Boot features/28.1.1 Authorization Server.md deleted file mode 100644 index d864b965..00000000 --- a/IV. Spring Boot features/28.1.1 Authorization Server.md +++ /dev/null @@ -1,11 +0,0 @@ -### 28.1.1 授权服务器 - -想要创建一个授权服务器,并授予access tokens,你需要使用`@EnableAuthorizationServer`,并提供`security.oauth2.client.client-id`和`security.oauth2.client.client-secret`配置。 - -按以上操作后,你就能使用客户端证书创建一个access token,例如: -```shell -$ curl client:secret@localhost:8080/oauth/token -d grant_type=password -d username=user -d password=pwd -``` -`/token`端点basic形式的认证证书是`client-id`和`client-secret`,用户证书通常是Spring Security的user详情(Spring Boot中默认是"user"和一个随机的密码)。 - -想要关闭自动配置,自己配置授权服务器特性,你只需添加一个`AuthorizationServerConfigurer`类型的`@Bean`。 diff --git a/IV. Spring Boot features/28.1.2 Resource Server.md b/IV. Spring Boot features/28.1.2 Resource Server.md deleted file mode 100644 index b0ca0ec3..00000000 --- a/IV. Spring Boot features/28.1.2 Resource Server.md +++ /dev/null @@ -1,16 +0,0 @@ -### 28.1.2 资源服务器 -为了使用access token,你需要一个资源服务器(可以跟授权服务器是同一个)。创建资源服务器很简单,只需要添加`@EnableResourceServer`,提供一些配置以允许服务器解码access token。如果应用也是授权服务器,由于它知道如何去解码tokens,所以也就不需要做其他事情。如果你的app是独立的服务,那你就需要给它添加以下可选配置中的某一项: - -* `security.oauth2.resource.user-info-uri`用于`/me`资源(例如,PWS的`https://uaa.run.pivotal.io/userinfo`)。 -* `security.oauth2.resource.token-info-uri`用于token解码端点(例如,PWS的`https://uaa.run.pivotal.io/check_token`)。 - -如果`user-info-uri`和`token-info-uri`都指定了,你可以设置flag筛选出最想要的那个(默认`prefer-token-info=true`)。 - -另外,如果token是JWTs,你可以配置`security.oauth2.resource.jwt.key-value`解码它们(key是验签的key)。验签的键值可以是一个对称密钥,也可以是PEM编码的RSA公钥。如果你没有key,并且它是公开的,你可以通过`security.oauth2.resource.jwt.key-uri`提供一个下载URI(有一个"value"字段的JSON对象),例如,在PWS平台上: -``` -$ curl https://uaa.run.pivotal.io/token_key -{"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"} -``` -**注** 如果你使用`security.oauth2.resource.jwt.key-uri`,授权服务器需要在应用启动时也运行起来,如果找不到key,它将输出warning,并告诉你如何解决。 - -OAuth2资源被过滤器链按`security.oauth2.resource.filter-order`指明的顺序保护着。默认地,在过滤器的保护结束之后才会到执行器端点(这样,执行器端点将会继续停留在HTTP Basic,除非你改变了顺序)。 diff --git a/IV. Spring Boot features/28.2 Token Type in User Info.md b/IV. Spring Boot features/28.2 Token Type in User Info.md deleted file mode 100644 index df8aded9..00000000 --- a/IV. Spring Boot features/28.2 Token Type in User Info.md +++ /dev/null @@ -1,3 +0,0 @@ -###28.2 User Info中的Token类型 - -Google和其他一些第三方身份(identity)提供商对发送给user info端点的请求头中设置的token类型名有严格要求。默认的`Bearer`满足大多数提供商要求,如果需要你可以设置`security.oauth2.resource.token-type`来改变它。 diff --git a/IV. Spring Boot features/28.2 WebFlux Security.md b/IV. Spring Boot features/28.2 WebFlux Security.md new file mode 100644 index 00000000..1422d3dc --- /dev/null +++ b/IV. Spring Boot features/28.2 WebFlux Security.md @@ -0,0 +1,23 @@ +### 28.2 WebFlux安全 + +类似于Spring MVC应用,你可以通过添加`spring-boot-starter-security`依赖,保护你的WebFlux应用。默认的安全配置由`ReactiveSecurityAutoConfiguration`以及从其它地方导入的类(`WebFluxSecurityConfiguration`用于web安全,`ReactiveAuthenticationManagerConfiguration`用于认证配置,也与非web应用相关)实现的。你可以添加一个`WebFilterChainProxy`类型的bean,来彻底关掉默认的web应用安全配置(这样做不会禁用认证管理者配置或者Actuator的安全)。 + +为了关闭认证管理者配置,你可以添加`ReactiveUserDetailsService`或是`ReactiveAuthenticationManager`类型的bean。 + +访问规则可以通过添加自定义的`SecurityWebFilterChain`配置。Spring Boot提供了便捷的方法。它们可以用来覆盖执行器端点和静态资源的访问规则。`EndpointRequest`可以用来创建基于`management.endpoints.web.base-path`属性的`ServerWebExchangeMatcher`。 + +`PathRequest`可以用来创建常用位置上的资源的`ServerWebExchangeMatcher`。 + +例如,你可以添加如下代码,自定义你的安全配置: +```java +@Bean +public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange() + .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() + .pathMatchers("/foo", "/bar") + .authenticated().and() + .formLogin(); + return http.build(); +} +``` \ No newline at end of file diff --git a/IV. Spring Boot features/28.3 Customizing the User Info RestTemplate.md b/IV. Spring Boot features/28.3 Customizing the User Info RestTemplate.md deleted file mode 100644 index 59d49b13..00000000 --- a/IV. Spring Boot features/28.3 Customizing the User Info RestTemplate.md +++ /dev/null @@ -1,14 +0,0 @@ -### 28.3 自定义User Info RestTemplate -如果设置了`user-info-uri`,资源服务器在内部将使用一个`OAuth2RestTemplate`抓取用于认证的用户信息,这是一个类型为`UserInfoRestTemplateFactory`的`@Bean`提供的。默认适用于大多数提供商,但偶尔你可能需要添加其他interceptors,或改变request的验证器(authenticator)。想要添加自定义,只需创建一个`UserInfoRestTemplateCustomizer`类型的bean —— 它只有单个方法,在bean创建后,初始化前会调用该方法。此处自定义的rest template仅用于内部执行认证。或者,你可以定义你自己的`UserInfoRestTemplateFactory``@Bean`来掌握完全的控制。 - -**注** 在YAML中设置RSA key时,需要使用管道符分割多行(“|”),记得缩进key value,例如: -```yaml -security: - oauth2: - resource: - jwt: - keyValue: | - -----BEGIN PUBLIC KEY----- - MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC... - -----END PUBLIC KEY----- -``` diff --git a/IV. Spring Boot features/28.3 OAuth2.md b/IV. Spring Boot features/28.3 OAuth2.md new file mode 100644 index 00000000..bde053d0 --- /dev/null +++ b/IV. Spring Boot features/28.3 OAuth2.md @@ -0,0 +1,3 @@ +### 28.3 OAuth2 + +[OAuth2](https://oauth.net/2/)是一个Spring支持的被广泛使用的认证框架。 diff --git a/IV. Spring Boot features/28.3.1 Client.md b/IV. Spring Boot features/28.3.1 Client.md index 2a5a6380..dd61ce2d 100644 --- a/IV. Spring Boot features/28.3.1 Client.md +++ b/IV. Spring Boot features/28.3.1 Client.md @@ -1,30 +1,60 @@ ### 28.3.1 客户端 -为了将web-app放入一个OAuth2客户端,你只需注解`@EnableOAuth2Client`,Spring Boot会创建`OAuth2ClientContext`和`OAuth2ProtectedResourceDetails`,这些是创建`OAuth2RestOperations`必需的。Spring Boot不会自动创建该bean,但你自己创建也不费力: +如果你的类路径上有`spring-security-oauth2-client`,你可以利用某些自动配置更容易地设置OAuth2客户端。 这个配置使用`OAuth2ClientProperties`里的属性。 + +你可以在`spring.security.oauth2.client`前缀下,注册多个OAuth2客户端和提供商,如下所示: + +```properties +spring.security.oauth2.client.registration.my-client-1.client-id=abcd +spring.security.oauth2.client.registration.my-client-1.client-secret=password +spring.security.oauth2.client.registration.my-client-1.client-name=Client for user scope +spring.security.oauth2.client.registration.my-client-1.provider=my-oauth-provider +spring.security.oauth2.client.registration.my-client-1.scope=user +spring.security.oauth2.client.registration.my-client-1.redirect-uri-template=http://my-redirect-uri.com +spring.security.oauth2.client.registration.my-client-1.client-authentication-method=basic +spring.security.oauth2.client.registration.my-client-1.authorization-grant-type=authorization_code + +spring.security.oauth2.client.registration.my-client-2.client-id=abcd +spring.security.oauth2.client.registration.my-client-2.client-secret=password +spring.security.oauth2.client.registration.my-client-2.client-name=Client for email scope +spring.security.oauth2.client.registration.my-client-2.provider=my-oauth-provider +spring.security.oauth2.client.registration.my-client-2.scope=email +spring.security.oauth2.client.registration.my-client-2.redirect-uri-template=http://my-redirect-uri.com +spring.security.oauth2.client.registration.my-client-2.client-authentication-method=basic +spring.security.oauth2.client.registration.my-client-2.authorization-grant-type=authorization_code + +spring.security.oauth2.client.provider.my-oauth-provider.authorization-uri=http://my-auth-server/oauth/authorize +spring.security.oauth2.client.provider.my-oauth-provider.token-uri=http://my-auth-server/oauth/token +spring.security.oauth2.client.provider.my-oauth-provider.user-info-uri=http://my-auth-server/userinfo +spring.security.oauth2.client.provider.my-oauth-provider.jwk-set-uri=http://my-auth-server/token_keys +spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=name +``` +默认的,Spring Security的`OAuth2LoginAuthenticationFilter`只处理匹配`/login/oauth2/code/*`的URL。如果你想要自定义`redirect-uri-template`来使用不同的模式,你需要提供处理那个自定义模式的配置。比如,你可以添加类似于下面示例的你自己的`WebSecurityConfigurerAdapter`: ```java -@Bean -public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, - OAuth2ProtectedResourceDetails details) { - return new OAuth2RestTemplate(details, oauth2ClientContext); +public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest().authenticated() + .and() + .oauth2Login() + .redirectionEndpoint() + .baseUri("/custom-callback"); + } } ``` -**注** 你可能想添加一个限定名(qualifier),因为应用中可能定义多个`RestTemplate`。 - -该配置使用`security.oauth2.client.*`作为证书(跟授权服务器使用的相同),此外,它也需要知道授权服务器中认证和token的URIs,例如: -```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 -``` -具有该配置的应用在使用`OAuth2RestTemplate`时会重定向到GitHub以完成授权,如果已经登陆GitHub,你甚至不会注意到它已经授权过了。那些特殊的凭证(credentials)只在应用运行于8080端口时有效(为了更灵活,在GitHub或其他提供商上注册自己的客户端app)。 +对于通常的OAuth2和OpenID提供商,包括Google、Github、Facebook、和Okta,我们提供了一系列默认的提供商(`google`、`github`、`facebook`、`okta`)。 -在客户端获取access token时,你可以设置`security.oauth2.client.scope`(逗号分隔或一个YAML数组)来限制它请求的作用域(scope)。作用域默认是空的,默认值取决于授权服务器,通常依赖于它拥有的客户端在注册时的设置。 +如果你不需要自定义这些提供商,你可以把`provider`属性设置为其中的一个。同样的,如果你客户端的ID匹配默认支持的提供商,Spring Boot也会推断你要使用它。 -**注** 对`security.oauth2.client.client-authentication-scheme`也有设置,默认为"header"(如果你的OAuth2提供商不喜欢header认证,例如Github,你可能需要将它设置为“form”)。实际上,`security.oauth2.client.*`属性绑定到一个`AuthorizationCodeResourceDetails`实例,所以它的所有属性都可以指定。 +也就是说,下面例子中的两个配置使用Google提供商: +```properties +spring.security.oauth2.client.registration.my-client.client-id=abcd +spring.security.oauth2.client.registration.my-client.client-secret=password +spring.security.oauth2.client.registration.my-client.provider=google -**注** 在一个非web应用中,你仍旧可以创建一个`OAuth2RestOperations`,并且跟`security.oauth2.client.*`配置关联。在这种情况下,它是一个“client credentials token grant”,如果你使用它的话就需要获取(此处不需要注解`@EnableOAuth2Client`或`@EnableOAuth2Sso`)。为了防止基础设施定义,只需要将`security.oauth2.client.client-id`从配置中移除(或将它设为空字符串)。 +spring.security.oauth2.client.registration.google.client-id=abcd +spring.security.oauth2.client.registration.google.client-secret=password +``` diff --git a/IV. Spring Boot features/28.3.2 Single Sign On.md b/IV. Spring Boot features/28.3.2 Single Sign On.md deleted file mode 100644 index d327309c..00000000 --- a/IV. Spring Boot features/28.3.2 Single Sign On.md +++ /dev/null @@ -1,29 +0,0 @@ -### 28.3.2 单点登陆 -OAuth2客户端可用于从提供商抓取用户详情,然后转换为Spring Security需要的`Authentication` token。上述提到的资源服务器通过`user-info-uri`属性来支持该功能,这是基于OAuth2的单点登陆(SSO)协议最基本的,Spring Boot提供的`@EnableOAuth2Sso`注解让它更容易实践。通过添加该注解及端点配置(`security.oauth2.client.*`),Github客户端就可以使用`/user/`端点保护它的所有资源了: -```yaml -security: - oauth2: -... - resource: - userInfoUri: https://api.github.com/user - preferTokenInfo: false -``` -由于所有路径默认都处于保护下,也就没有主页展示那些未授权的用户,进而邀请他们去登陆(通过访问`/login`路径,或`security.oauth2.sso.login-path`指定的路径)。 - -为了自定义访问规则或保护的路径(这样你就可以添加主页),你可以将`@EnableOAuth2Sso`添加到一个`WebSecurityConfigurerAdapter`,该注解会包装它,增强需要的地方以使`/login`路径工作。例如,这里我们允许未授权的用户访问主页`/`,其他的依旧保持默认: -```java -@Configuration -static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { - - @Override - public void init(WebSecurity web) { - web.ignore.antMatchers("/"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**").authorizeRequests().anyRequest().authenticated(); - } - -} -``` diff --git a/IV. Spring Boot features/28.4 Actuator Security.md b/IV. Spring Boot features/28.4 Actuator Security.md index 790592be..343caa12 100644 --- a/IV. Spring Boot features/28.4 Actuator Security.md +++ b/IV. Spring Boot features/28.4 Actuator Security.md @@ -1,10 +1,7 @@ -### 28.4 Actuator安全 -如果Actuator处于使用中,你会发现: +### 28.4 执行器安全 -* 管理的端点是安全的,即使应用端点不安全。 -* Security事件转换为`AuditEvent`实例,并发布到`AuditEventRepository`。 -* 默认用户拥有`ACTUATOR`和`USER`角色。 - -Actuator的安全特性可以通过外部配置属性(`management.security.*`)进行修改。为了覆盖应用访问规则但不覆盖actuator的访问规则,你可以添加一个`WebSecurityConfigurerAdapter`类型的`@Bean`,并注解`@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)`,如果想覆盖actuator访问规则,则注解`@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)`。 +为了安全,`/health`与`/info`之外的所有执行器都默认禁用。可以使用`management.endpoints.web.exposure.include`属性启用执行器。 +如果Spring Security在类路径上,并且没有其它的`WebSecurityConfigurerAdapter`,执行器会受到Spring Boot自动配置的保护。如果你自定义了一个`WebSecurityConfigurerAdapter`,Spring Boot将不会自动配置,你将完全掌控执行器的访问规则。 +**注** 在设置`management.endpoints.web.exposure.include`之前,确保暴露的执行器不包含敏感信息,并且/或者将它们放在防火墙后面,或是通过Spring Security等进行保护。 \ No newline at end of file diff --git a/IV. Spring Boot features/28.4.1 Cross Site Request Forgery Protection.md b/IV. Spring Boot features/28.4.1 Cross Site Request Forgery Protection.md new file mode 100644 index 00000000..f2dd46b9 --- /dev/null +++ b/IV. Spring Boot features/28.4.1 Cross Site Request Forgery Protection.md @@ -0,0 +1,7 @@ +### 28.4.1 跨站请求伪造保护 + +由于Spring Boot依赖Spring Security的默认配置,CSRF保护默认启用。这意味着:当默认安全配置在使用中时,需要`POST`(关机和记录器端点)、`PUT`或者`DELETE`的执行器端点会得到一个403的禁止错误。 + +**注** 我们推荐只在创建由非浏览器客户端使用的服务时,完全禁用CSRF保护。 + +可以在[Spring Security参考指南](https://docs.spring.io/spring-security/site/docs/5.0.3.RELEASE/reference/htmlsingle#csrf)查看与CSRF保护相关的额外信息。 \ No newline at end of file diff --git a/IV. Spring Boot features/29. Working with SQL Databases.md b/IV. Spring Boot features/29. Working with SQL Databases.md new file mode 100644 index 00000000..e963d3d1 --- /dev/null +++ b/IV. Spring Boot features/29. Working with SQL Databases.md @@ -0,0 +1,3 @@ +### 29. 使用SQL数据库 + +Spring框架为使用SQL数据库提供了广泛支持,从使用`JdbcTemplate`直接访问JDBC到完全的“对象关系映射”技术,比如Hibernate。Spring Data提供了更高级的功能:直接从接口创建`Repository`实现,并根据约定从方法名生成查询。 diff --git a/IV. Spring Boot features/29. Working with SQL databases.md b/IV. Spring Boot features/29. Working with SQL databases.md deleted file mode 100644 index eeaed696..00000000 --- a/IV. Spring Boot features/29. Working with SQL databases.md +++ /dev/null @@ -1,3 +0,0 @@ -### 29. 使用SQL数据库 - -Spring框架为使用SQL数据库提供了广泛支持,从使用`JdbcTemplate`直接访问JDBC到完全的‘对象关系映射’技术,比如Hibernate。Spring Data提供了更高级的功能,直接从接口创建`Repository`实现,并根据约定从方法名生成查询。 diff --git a/IV. Spring Boot features/29.1. Configure a DataSource.md b/IV. Spring Boot features/29.1. Configure a DataSource.md index fd3be78d..0a028706 100644 --- a/IV. Spring Boot features/29.1. Configure a DataSource.md +++ b/IV. Spring Boot features/29.1. Configure a DataSource.md @@ -1,5 +1,5 @@ -### 29.1. 配置DataSource - -Java的`javax.sql.DataSource`接口提供了一个标准的使用数据库连接的方法。通常,DataSource使用`URL`和相应的凭证去初始化数据库连接。 - -**提示** 查看How-to章节,获取更多的高级示例,典型地完全控制DataSource的配置。 +### 29.1. 配置数据源 + +Java的`javax.sql.DataSource`接口提供了一个标准的使用数据库连接的方法。通常,DataSource使用`URL`和相应的凭证去初始化数据库连接。 + +**提示** 查看[How-to章节](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-configure-a-datasource),获取更多的高级示例,典型地完全控制DataSource的配置。 diff --git a/IV. Spring Boot features/29.1.1. Embedded Database Support.md b/IV. Spring Boot features/29.1.1. Embedded Database Support.md index 82fff2f8..7938a5ee 100644 --- a/IV. Spring Boot features/29.1.1. Embedded Database Support.md +++ b/IV. Spring Boot features/29.1.1. Embedded Database Support.md @@ -2,14 +2,14 @@ 开发应用时使用内存数据库是很方便的。显然,内存数据库不提供持久化存储;你只需要在应用启动时填充数据库,在应用结束前预先清除数据。 -**提示** How-to章节包含有一章讲解如何初始化数据库。 +**提示** How-to章节包含有[一章讲解如何初始化数据库](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-database-initialization)。 -Spring Boot可以自动配置的内嵌数据库包括[H2](http://www.h2database.com/), [HSQL](http://hsqldb.org/)和[Derby](http://db.apache.org/derby/)。你不需要提供任何连接URLs,只需要添加你想使用的内嵌数据库依赖。 +Spring Boot可以自动配置的内嵌数据库包括[H2](http://www.h2database.com/), [HSQL](http://hsqldb.org/)和[Derby](https://db.apache.org/derby/)。你不需要提供任何连接URL,只需要添加你想使用的内嵌数据库依赖。 **注** 如果你正在你的测试中使用这个特性,你可能注意到了:不管你使用了多少应用上下文,你的整个测试套件重复使用了同一个数据库。如果你想要确保每个上下文各自有一个内嵌数据库,你应当把 `spring.datasource.generate-unique-name`设置为`true`。 -示例:典型的POM依赖如下: +例如,典型的POM依赖如下所示: ```xml org.springframework.boot diff --git a/IV. Spring Boot features/29.1.2. Connection to a Production Database.md b/IV. Spring Boot features/29.1.2. Connection to a Production Database.md new file mode 100644 index 00000000..2d3038ff --- /dev/null +++ b/IV. Spring Boot features/29.1.2. Connection to a Production Database.md @@ -0,0 +1,40 @@ +### 29.1.2 连接生产环境数据库 + +生产环境的数据库连接可以通过池化的`DataSource`进行自动配置。Spring Boot使用如下的算法,选取特定实现: + +1. 出于[HikariCP](https://github.com/brettwooldridge/HikariCP)的优秀性能和并发,如果可用总会优先使用它。 +2. 如果tomcat数据源连接池可用,我们将使用它。 +3. 如果HikariCP和tomcat数据源连接池都不能用。如果[Commons DBCP2](https://commons.apache.org/proper/commons-dbcp/)可用,我们将使用它。 + +如果使用`spring-boot-starter-jdbc`或`spring-boot-starter-data-jpa`“starters”,你会自动添加`HikariCP`依赖。 + +**注** 通过指定`spring.datasource.type`属性,你可以完全抛弃该算法,然后指定数据库连接池。如果你在tomcat容器中运行应用,由于默认提供`tomcat-jdbc`,这就很重要了。 + +**注** 其他的连接池可以手动配置,如果你定义自己的`DataSource` bean,自动配置是不会发生的。 + +DataSource配置被外部的`spring.datasource.*`属性控制,例如,你可能会在`application.properties`中声明以下片段: +```java +spring.datasource.url=jdbc:mysql://localhost/test +spring.datasource.username=dbuser +spring.datasource.password=dbpass +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +``` +**注** 你应该至少使用`spring.datasource.url`属性指定url,或Spring Boot尝试自动配置内嵌数据库。 + +**注** 你经常不需要指定`driver-class-name`,因为Spring boot可以从`url`推断大部分数据库。 + +**注** 对于将要创建的池化`DataSource`,我们需要验证是否有一个可用的`Driver`,所以在做其他事前会校验它。也就是说,如果你设置`spring.datasource.driver-class-name=com.mysql.jdbc.Driver`,然后该class加载出来,否则就会出错。 + +其他可选配置可以查看[DataSourceProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java),有些标准配置是跟实现无关的,对于实现相关的配置可以通过相应前缀进行设置(`spring.datasource.hikari.*`,`spring.datasource.tomcat.*`和`spring.datasource.dbcp2.*`),具体参考你使用的连接池文档。 + +例如,如果正在使用[Tomcat连接池](https://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html#Common_Attributes),你可以自定义很多其他设置,如下所示: +```properties +# Number of ms to wait before throwing an exception if no connection is available. +spring.datasource.tomcat.max-wait=10000 + +# Maximum number of active connections that can be allocated from this pool at the same time. +spring.datasource.tomcat.max-active=50 + +# Validate the connection before borrowing it from the pool. +spring.datasource.tomcat.test-on-borrow=true +``` diff --git a/IV. Spring Boot features/29.1.2. Connection to a production database.md b/IV. Spring Boot features/29.1.2. Connection to a production database.md deleted file mode 100644 index acd51898..00000000 --- a/IV. Spring Boot features/29.1.2. Connection to a production database.md +++ /dev/null @@ -1,40 +0,0 @@ -### 29.1.2. 连接生产环境数据库 - -生产环境的数据库连接可以通过池化的`DataSource`进行自动配置,下面是选取特定实现的算法: - -- 出于HikariCP的优秀性能和并发,如果可用总会优先使用它。 -- 如果tomcat数据源连接池可用,我们将使用它。 -- 如果HikariCP和tomcat数据源连接池都不能用。如果Commons DBCP2可用,我们将使用它。 - -如果使用`spring-boot-starter-jdbc`或`spring-boot-starter-data-jpa` 'starters',你会自动添加`HikariCP`依赖。 - -**注** 通过指定`spring.datasource.type`属性,你可以完全抛弃该算法,然后指定数据库连接池。如果你在tomcat容器中运行应用,由于默认提供`tomcat-jdbc`,这就很重要了。 - -**注** 其他的连接池可以手动配置,如果你定义自己的`DataSource` bean,自动配置是不会发生的。 - -DataSource配置被外部的`spring.datasource.*`属性控制,例如,你可能会在`application.properties`中声明以下片段: -```java -spring.datasource.url=jdbc:mysql://localhost/test -spring.datasource.username=dbuser -spring.datasource.password=dbpass -spring.datasource.driver-class-name=com.mysql.jdbc.Driver -``` -**注** 你应该至少使用`spring.datasource.url`属性指定url,或Spring Boot尝试自动配置内嵌数据库。 - -**注** 你经常不需要指定`driver-class-name`,因为Spring boot可以从`url`推断大部分数据库。 - -**注** 对于将要创建的池化`DataSource`,我们需要验证是否有一个可用的`Driver`,所以在做其他事前会校验它。比如,如果你设置`spring.datasource.driver-class-name=com.mysql.jdbc.Driver`,然后该class加载出来,否则就会出错。 - -其他可选配置可以查看[DataSourceProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java),有些标准配置是跟实现无关的,对于实现相关的配置可以通过相应前缀进行设置(`spring.datasource.hikari.*`,`spring.datasource.tomcat.*`和`spring.datasource.dbcp2.*`),具体参考你使用的连接池文档。 - -例如,如果正在使用[Tomcat连接池](http://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html#Common_Attributes),你可以自定义很多其他设置: -```properties -# Number of ms to wait before throwing an exception if no connection is available. -spring.datasource.tomcat.max-wait=10000 - -# Maximum number of active connections that can be allocated from this pool at the same time. -spring.datasource.tomcat.max-active=50 - -# Validate the connection before borrowing it from the pool. -spring.datasource.tomcat.test-on-borrow=true -``` diff --git a/IV. Spring Boot features/29.1.3. Connection to a JNDI DataSource.md b/IV. Spring Boot features/29.1.3. Connection to a JNDI DataSource.md index 044fc32a..e1d6a4b2 100644 --- a/IV. Spring Boot features/29.1.3. Connection to a JNDI DataSource.md +++ b/IV. Spring Boot features/29.1.3. Connection to a JNDI DataSource.md @@ -2,7 +2,7 @@ 如果正在将Spring Boot应用部署到一个应用服务器,你可能想要用应用服务器内建的特性来配置和管理你的DataSource,并使用JNDI访问它。 -`spring.datasource.jndi-name`属性可用来替代`spring.datasource.url`,`spring.datasource.username`和`spring.datasource.password`去从一个特定的JNDI路径获取`DataSource`,比如,以下`application.properties`中的片段展示了如何获取JBoss AS定义的`DataSource`: +`spring.datasource.jndi-name`属性可用来替代`spring.datasource.url`、`spring.datasource.username`和`spring.datasource.password`,去从一个特定的JNDI路径获取`DataSource`。比如,以下`application.properties`中的片段展示了如何获取JBoss AS定义的`DataSource`: ```java spring.datasource.jndi-name=java:jboss/datasources/customers ``` diff --git a/IV. Spring Boot features/29.2. Using JdbcTemplate.md b/IV. Spring Boot features/29.2. Using JdbcTemplate.md index 1f3b7b78..3241fecd 100644 --- a/IV. Spring Boot features/29.2. Using JdbcTemplate.md +++ b/IV. Spring Boot features/29.2. Using JdbcTemplate.md @@ -1,6 +1,6 @@ ### 29.2. 使用JdbcTemplate -Spring的`JdbcTemplate`和`NamedParameterJdbcTemplate`类会被自动配置,你可以将它们直接`@Autowire`到自己的beans: +Spring的`JdbcTemplate`和`NamedParameterJdbcTemplate`类会被自动配置,你可以将它们直接`@Autowire`到自己的bean,如下所示: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; @@ -19,9 +19,9 @@ public class MyBean { } ``` -你可以使用`spring.jdbc.template.*`属性自定义模版的一些属性: +你可以使用`spring.jdbc.template.*`属性自定义模版的一些属性,如下所示: ```properties spring.jdbc.template.max-rows=500 ``` -**提示** `NamedParameterJdbcTemplate`在幕后重复使用了同一个`JdbcTemplate`实例。如果定义了不止一个`JdbcTemplate`,而且不存在候选,`NamedParameterJdbcTemplate`就没有被自动配置。 \ No newline at end of file +**提示** `NamedParameterJdbcTemplate`在幕后重复使用了同一个`JdbcTemplate`实例。如果定义了不止一个`JdbcTemplate`,而且不存在候选,`NamedParameterJdbcTemplate`就没有被自动配置。 diff --git a/IV. Spring Boot features/29.3. JPA and Spring Data.md b/IV. Spring Boot features/29.3. JPA and Spring Data.md new file mode 100644 index 00000000..33132666 --- /dev/null +++ b/IV. Spring Boot features/29.3. JPA and Spring Data.md @@ -0,0 +1,9 @@ +### 29.3. JPA和Spring Data + +Java持久化API是一个让你将对象映射为关系数据库的标准技术。`spring-boot-starter-data-jpa` POM提供了一种快速上手的方式,它提供以下关键依赖: + +- Hibernate:一个非常流行的JPA实现。 +- Spring Data JPA:让实现基于JPA的repositories更容易。 +- Spring ORMs:Spring框架支持的核心ORM。 + +**注** 我们不想在这涉及太多关于JPA或[Spring Data](https://projects.spring.io/spring-data/)的细节。你可以参考来自[spring.io](https://spring.io/)的指南[使用JPA获取数据](https://spring.io/guides/gs/accessing-data-jpa/),并阅读[Spring Data JPA](https://projects.spring.io/spring-data-jpa/)和[Hibernate](https://hibernate.org/orm/documentation/)的参考文档。 diff --git "a/IV. Spring Boot features/29.3. JPA and \342\200\230Spring Data\342\200\231.md" "b/IV. Spring Boot features/29.3. JPA and \342\200\230Spring Data\342\200\231.md" deleted file mode 100644 index 9068e841..00000000 --- "a/IV. Spring Boot features/29.3. JPA and \342\200\230Spring Data\342\200\231.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 29.3. JPA和Spring Data - -Java持久化API是一个允许你将对象映射为关系数据库的标准技术,`spring-boot-starter-data-jpa` POM提供了一种快速上手的方式,它提供以下关键依赖: - -- Hibernate - 一个非常流行的JPA实现。 -- Spring Data JPA - 让实现基于JPA的repositories更容易。 -- Spring ORMs - Spring框架支持的核心ORM。 - -**注** 我们不想在这涉及太多关于JPA或Spring Data的细节。你可以参考来自[spring.io](http://spring.io/)的指南[使用JPA获取数据](http://spring.io/guides/gs/accessing-data-jpa/),并阅读[Spring Data JPA](http://projects.spring.io/spring-data-jpa/)和[Hibernate](http://hibernate.org/orm/documentation/)的参考文档。 diff --git a/IV. Spring Boot features/29.3.1. Entity Classes.md b/IV. Spring Boot features/29.3.1. Entity Classes.md index 6b8e6e15..14de5f88 100644 --- a/IV. Spring Boot features/29.3.1. Entity Classes.md +++ b/IV. Spring Boot features/29.3.1. Entity Classes.md @@ -1,8 +1,8 @@ ### 29.3.1. 实体类 -通常,JPA实体类被定义到一个`persistence.xml`文件,在Spring Boot中,这个文件被'实体扫描'取代。默认情况,Spring Boot会查找主配置类(被`@EnableAutoConfiguration`或`@SpringBootApplication`注解的类)下的所有包。 +通常,JPA实体类被定义到一个`persistence.xml`文件。在Spring Boot中,这个文件被“实体扫描”取代。默认的,Spring Boot会查找主配置类(被`@EnableAutoConfiguration`或`@SpringBootApplication`注解的类)下的所有包。 -任何被`@Entity`,`@Embeddable`或`@MappedSuperclass`注解的类都将被考虑,一个普通的实体类看起来像这样: +任何被`@Entity`,`@Embeddable`或`@MappedSuperclass`注解的类都将被考虑。一个普通的实体类看起来像这样: ```java package com.example.myapp.domain; @@ -44,4 +44,4 @@ public class City implements Serializable { // ... etc } ``` -**注** 你可以使用`@EntityScan`注解自定义实体扫描路径,具体参考[章节 78.4,从Spring配置分离`@Entity`定义](../IX. ‘How-to’ guides/78.4. Separate @Entity definitions from Spring configuration.md)。 +**注** 你可以使用`@EntityScan`注解自定义实体扫描路径,具体参考[章节 79.4,从Spring配置分离`@Entity`定义](../IX. ‘How-to’ guides/79.4. Separate @Entity Definitions from Spring Configuration.md)。 diff --git a/IV. Spring Boot features/29.3.2. Spring Data JPA Repositories.md b/IV. Spring Boot features/29.3.2. Spring Data JPA Repositories.md index ca0267d2..f9dbb971 100644 --- a/IV. Spring Boot features/29.3.2. Spring Data JPA Repositories.md +++ b/IV. Spring Boot features/29.3.2. Spring Data JPA Repositories.md @@ -1,12 +1,12 @@ ### 29.3.2. Spring Data JPA仓库 -Spring Data JPA仓库(repositories)是用来定义访问数据的接口。根据你的方法名,JPA查询会被自动创建,比如,一个`CityRepository`接口可能声明一个`findAllByState(String state)`方法,用来查找给定状态的所有城市。 +[Spring Data JPA](http://projects.spring.io/spring-data-jpa/)仓库是用来定义访问数据的接口。根据你的方法名,JPA查询会被自动创建,比如,一个`CityRepository`接口可能声明一个`findAllByState(String state)`方法,用来查找给定状态的所有城市。 -对于比较复杂的查询,你可以使用Spring Data的[`Query`](http://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/Query.html)注解你的方法。 +对于比较复杂的查询,你可以使用Spring Data的[`Query`](https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/Query.html)注解你的方法。 -Spring Data仓库通常继承自[`Repository`](http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/Repository.html)或[`CrudRepository`](http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html)接口。如果你使用自动配置,Spring Boot会搜索主配置类(注解`@EnableAutoConfiguration`或`@SpringBootApplication`的类)所在包下的仓库。 +Spring Data仓库通常继承自[`Repository`](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/Repository.html)或[`CrudRepository`](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html)接口。如果你使用自动配置,Spring Boot会搜索主配置类(注解`@EnableAutoConfiguration`或`@SpringBootApplication`的类)所在包下的仓库。 -下面是典型的Spring Data仓库: +下面是典型的Spring Data仓库接口定义: ```java package com.example.myapp.domain; @@ -20,4 +20,4 @@ public interface CityRepository extends Repository { City findByNameAndCountryAllIgnoringCase(String name, String country); } ``` -**注**:我们仅仅触及了Spring Data JPA的表面,具体查看它的[参考指南](http://projects.spring.io/spring-data-jpa/)。 +**注**:我们仅仅触及了Spring Data JPA的表面,具体查看它的[参考指南](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/)。 diff --git a/IV. Spring Boot features/29.3.3. Creating and Dropping JPA Databases.md b/IV. Spring Boot features/29.3.3. Creating and Dropping JPA Databases.md new file mode 100644 index 00000000..518fa928 --- /dev/null +++ b/IV. Spring Boot features/29.3.3. Creating and Dropping JPA Databases.md @@ -0,0 +1,13 @@ +### 29.3.3. 创建和删除JPA数据库 + +默认情况下,只有在你使用内嵌数据库(H2, HSQL或Derby)时,JPA数据库才会被自动创建。你可以使用`spring.jpa.*`属性显式的设置JPA,比如,将以下配置添加到`application.properties`中可以创建和删除表: +```properties +spring.jpa.hibernate.ddl-auto=create-drop +``` +**注** Hibernate自己内部对创建,删除表支持的属性是`hibernate.hbm2ddl.auto`(如果你记得更好)。你可以使用`spring.jpa.properties.*`设置Hibernate其他的native属性(前缀在被添加到实体管理器之前会被去掉)。下面是给Hibernate设置JPA属性的例子: +```properties +`spring.jpa.properties.hibernate.globally_quoted_identifiers=true` +``` +上面的例子将`true`传递到Hibernate实体管理器里的`hibernate.globally_quoted_identifiers`属性。 + +通常,DDL执行(或验证)被延迟到`ApplicationContext`启动后,这可以通过`spring.jpa.generate-ddl`标签控制,如果Hibernate自动配置被激活,那该标识就不会被使用,因为`ddl-auto`设置粒度更细。 diff --git a/IV. Spring Boot features/29.3.3. Creating and dropping JPA databases.md b/IV. Spring Boot features/29.3.3. Creating and dropping JPA databases.md deleted file mode 100644 index b84c847f..00000000 --- a/IV. Spring Boot features/29.3.3. Creating and dropping JPA databases.md +++ /dev/null @@ -1,9 +0,0 @@ -### 29.3.3. 创建和删除JPA数据库 - -默认情况下,只有在你使用内嵌数据库(H2, HSQL或Derby)时,JPA数据库才会被自动创建。你可以使用`spring.jpa.*`属性显式的设置JPA,比如,将以下配置添加到`application.properties`中可以创建和删除表: -```properties -spring.jpa.hibernate.ddl-auto=create-drop -``` -**注** Hibernate自己内部对创建,删除表支持的属性是`hibernate.hbm2ddl.auto`(如果你记得更好)。你可以使用`spring.jpa.properties.*`(前缀在被添加到实体管理器之前会被去掉)设置Hibernate其他的native属性,比如:`spring.jpa.properties.hibernate.globally_quoted_identifiers=true`将传递`hibernate.globally_quoted_identifiers`到Hibernate实体管理器。 - -通常,DDL执行(或验证)被延迟到`ApplicationContext`启动后,这可以通过`spring.jpa.generate-ddl`标签控制,如果Hibernate自动配置被激活,那该标识就不会被使用,因为`ddl-auto`设置粒度更细。 diff --git "a/IV. Spring Boot features/29.4 Using H2\342\200\231s Web Console.md" "b/IV. Spring Boot features/29.4 Using H2\342\200\231s Web Console.md" new file mode 100644 index 00000000..fa69d98c --- /dev/null +++ "b/IV. Spring Boot features/29.4 Using H2\342\200\231s Web Console.md" @@ -0,0 +1,9 @@ +### 29.4 使用H2的web控制台 + +[H2数据库](http://www.h2database.com/)提供一个[基于浏览器的控制台](http://www.h2database.com/html/quickstart.html#h2_console),Spring Boot可以为你自动配置。如果以下条件满足,则控制台会被自动配置: + +* 你正在开发一个web应用。 +* 添加`com.h2database:h2`依赖。 +* 你正在使用[Spring Boot开发者工具](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-devtools)。 + +**注** 如果你没有使用Spring Boot的开发者工具,仍想利用H2的控制台,可以设置`spring.h2.console.enabled`属性值为`true`。H2控制台应该只用于开发期间,所以确保生产环境没有设置`spring.h2.console.enabled`。 diff --git "a/IV. Spring Boot features/29.4 Using H2\342\200\231s web console.md" "b/IV. Spring Boot features/29.4 Using H2\342\200\231s web console.md" deleted file mode 100644 index bf050249..00000000 --- "a/IV. Spring Boot features/29.4 Using H2\342\200\231s web console.md" +++ /dev/null @@ -1,8 +0,0 @@ -### 29.4 使用H2的web控制台 -[H2数据库](http://www.h2database.com/)提供一个[基于浏览器的控制台](http://www.h2database.com/html/quickstart.html#h2_console),Spring Boot可以为你自动配置。如果以下条件满足,则控制台会被自动配置: - -* 你正在开发一个web应用。 -* 添加`com.h2database:h2`依赖。 -* 你正在使用[Spring Boot开发者工具](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#using-boot-devtools)。 - -**注** 如果你没有使用Spring Boot的开发者工具,仍想利用H2的控制台,可以设置`spring.h2.console.enabled`属性值为`true`。H2控制台应该只用于开发期间,所以确保生产环境没有设置`spring.h2.console.enabled`。 diff --git "a/IV. Spring Boot features/29.4.1 Changing the H2 Console\342\200\231s Path.md" "b/IV. Spring Boot features/29.4.1 Changing the H2 Console\342\200\231s Path.md" new file mode 100644 index 00000000..94b2a350 --- /dev/null +++ "b/IV. Spring Boot features/29.4.1 Changing the H2 Console\342\200\231s Path.md" @@ -0,0 +1,3 @@ +### 29.4.1 改变H2控制台路径 + +H2控制台路径默认为`/h2-console`,你可以通过设置`spring.h2.console.path`属性自定义该路径。 diff --git "a/IV. Spring Boot features/29.4.1 Changing the H2 console\342\200\231s path.md" "b/IV. Spring Boot features/29.4.1 Changing the H2 console\342\200\231s path.md" deleted file mode 100644 index 80a31dc7..00000000 --- "a/IV. Spring Boot features/29.4.1 Changing the H2 console\342\200\231s path.md" +++ /dev/null @@ -1,2 +0,0 @@ -### 29.4.1 改变H2控制台路径 -H2控制台路径默认为`/h2-console`,你可以通过设置`spring.h2.console.path`属性自定义该路径。 diff --git a/IV. Spring Boot features/29.4.2 Securing the H2 console.md b/IV. Spring Boot features/29.4.2 Securing the H2 console.md deleted file mode 100644 index 3a044d41..00000000 --- a/IV. Spring Boot features/29.4.2 Securing the H2 console.md +++ /dev/null @@ -1,6 +0,0 @@ -### 29.4.2 保护H2控制台 -当添加Spring Security依赖,并且启用基本认证时,Spring Boot自动使用基本认证保护H2控制台。以下属性可用于自定义安全配置: - -* `security.user.role` -* `security.basic.authorize-mode` -* `security.basic.enabled` diff --git a/IV. Spring Boot features/29.5.2 Using DSLContext.md b/IV. Spring Boot features/29.5.2 Using DSLContext.md index 48b56696..1fcdb242 100644 --- a/IV. Spring Boot features/29.5.2 Using DSLContext.md +++ b/IV. Spring Boot features/29.5.2 Using DSLContext.md @@ -1,4 +1,5 @@ ### 29.5.2 使用DSLContext + jOOQ提供的流式(fluent)API是通过`org.jooq.DSLContext`接口初始化的,Spring Boot将自动配置一个`DSLContext`为Spring Bean,并将它跟应用的`DataSource`连接起来。想要使用`DSLContext`,只需`@Autowire`注入它: ```java @Component @@ -13,9 +14,9 @@ public class JooqExample implements CommandLineRunner { } ``` -**注** jOOQ手册倾向于使用一个名为`create`的变量持有`DSLContext`,示例中也是这样做的。 +**注** jOOQ手册倾向于使用一个名为`create`的变量持有`DSLContext`。 -然后你就可以使用`DSLContext`构造查询: +然后你就可以使用`DSLContext`构造查询,如下所示: ```java public List authorsBornAfter1980() { return this.create.selectFrom(AUTHOR) diff --git a/IV. Spring Boot features/29.5.3 jOOQ SQL Dialect.md b/IV. Spring Boot features/29.5.3 jOOQ SQL Dialect.md new file mode 100644 index 00000000..f6bb2626 --- /dev/null +++ b/IV. Spring Boot features/29.5.3 jOOQ SQL Dialect.md @@ -0,0 +1,5 @@ +### 29.5.3 jOOQ SQL方言 + +Spring Boot决定了对你的数据库使用何种SQL方言,除非你配置了`spring.jooq.sql-dialect`属性。如果探测不到方言,将使用`默认值`。 + +**注** Spring Boot只能自动配置jOOQ的开源版本支持的方言。 diff --git a/IV. Spring Boot features/29.5.3 jOOQ SQL dialect.md b/IV. Spring Boot features/29.5.3 jOOQ SQL dialect.md deleted file mode 100644 index 132a02d9..00000000 --- a/IV. Spring Boot features/29.5.3 jOOQ SQL dialect.md +++ /dev/null @@ -1,4 +0,0 @@ -### 29.5.3 jOOQ SQL方言 -Spring Boot决定了对你的数据库使用何种SQL方言,除非你配置了`spring.jooq.sql-dialect`属性。如果探测不到方言,将使用`默认值`。 - -**注** Spring Boot只能自动配置jOOQ的开源版本支持的方言。 diff --git a/IV. Spring Boot features/30. Working with NoSQL Technologies.md b/IV. Spring Boot features/30. Working with NoSQL Technologies.md new file mode 100644 index 00000000..59ccbbd3 --- /dev/null +++ b/IV. Spring Boot features/30. Working with NoSQL Technologies.md @@ -0,0 +1,3 @@ +### 30. 使用NoSQL技术 + +Spring Data提供其他项目,用来帮你使用各种各样的NoSQL技术,包括:[MongoDB](https://projects.spring.io/spring-data-mongodb/)、[Neo4J](https://projects.spring.io/spring-data-neo4j/)、[Elasticsearch](https://github.com/spring-projects/spring-data-elasticsearch/)、 [Solr](https://projects.spring.io/spring-data-solr/)、[Redis](https://projects.spring.io/spring-data-redis/)、 [Gemfire](https://projects.spring.io/spring-data-gemfire/)、[Cassandra](https://projects.spring.io/spring-data-cassandra/)、[Couchbase](https://projects.spring.io/spring-data-couchbase/)和[LDAP](https://projects.spring.io/spring-data-ldap/)。Spring Boot为Redis、MongoDB、Elasticsearch、Solr Cassandra、Couchbase和LDAP提供自动配置。你也可以充分利用其他项目,但需要自己配置它们,具体查看[projects.spring.io/spring-data](https://projects.spring.io/spring-data)中相应的参考文档。 diff --git a/IV. Spring Boot features/30. Working with NoSQL technologies.md b/IV. Spring Boot features/30. Working with NoSQL technologies.md deleted file mode 100644 index 66ea61f6..00000000 --- a/IV. Spring Boot features/30. Working with NoSQL technologies.md +++ /dev/null @@ -1,3 +0,0 @@ -### 30. 使用NoSQL技术 - -Spring Data提供其他项目,用来帮你使用各种各样的NoSQL技术,包括[MongoDB](http://projects.spring.io/spring-data-mongodb/), [Neo4J](http://projects.spring.io/spring-data-neo4j/), [Elasticsearch](https://github.com/spring-projects/spring-data-elasticsearch/), [Solr](http://projects.spring.io/spring-data-solr/), [Redis](http://projects.spring.io/spring-data-redis/), [Gemfire](http://projects.spring.io/spring-data-gemfire/), [Cassandra](http://projects.spring.io/spring-data-cassandra/),[Couchbase](http://projects.spring.io/spring-data-couchbase/)和[LDAP](http://projects.spring.io/spring-data-ldap/)。Spring Boot为Redis, MongoDB, Elasticsearch, Solr Cassandra,Couchbase和LDAP提供自动配置。你也可以充分利用其他项目,但需要自己配置它们,具体查看[projects.spring.io/spring-data](http://projects.spring.io/spring-data/)中相应的参考文档。 diff --git a/IV. Spring Boot features/30.1. Redis.md b/IV. Spring Boot features/30.1. Redis.md index a3bee1fb..8e7634c6 100644 --- a/IV. Spring Boot features/30.1. Redis.md +++ b/IV. Spring Boot features/30.1. Redis.md @@ -1,4 +1,6 @@ ### 30.1. Redis -[Redis](http://redis.io/)是一个缓存,消息中间件及具有丰富特性的键值存储系统。Spring Boot为[Jedis](https://github.com/xetorthio/jedis/)和[Lettuce](https://github.com/mp911de/lettuce/)客户端library提供基本的自动配置,[Spring Data Redis](https://github.com/spring-projects/spring-data-redis)提供了在它之上的抽象。 -`spring-boot-starter-redis`'Starter'默认使用[Jedis](https://github.com/xetorthio/jedis/)方便地集合了需要的依赖。如果你正在搭建一个响应式的应用,`spring-boot-starter-data-redis-reactive`'Starter'对你来说非常有用。 +[Redis](http://redis.io/)是一个缓存、消息中间件及具有丰富特性的键值存储系统。Spring Boot为[Lettuce](https://github.com/lettuce-io/lettuce-core/)和[Jedis](https://github.com/xetorthio/jedis/)客户端库提供基本的自动配置。[Spring Data Redis](https://github.com/spring-projects/spring-data-redis)提供了在它们之上的抽象。 +`spring-boot-starter-redis`“Starter”方便地集合了需要的依赖。它默认使用[Lettuce](https://github.com/lettuce-io/lettuce-core/),既处理传统应用,也处理响应式应用。 + +**注** 为了与其它存储系统保持一致,我们也提供了带有响应式支持的`spring-boot-starter-data-redis-reactive`“Starter”。 diff --git a/IV. Spring Boot features/30.1.1. Connecting to Redis.md b/IV. Spring Boot features/30.1.1. Connecting to Redis.md index 1203abaf..67811d84 100644 --- a/IV. Spring Boot features/30.1.1. Connecting to Redis.md +++ b/IV. Spring Boot features/30.1.1. Connecting to Redis.md @@ -1,6 +1,6 @@ ### 30.1.1. 连接Redis -你可以注入一个自动配置的`RedisConnectionFactory`,`StringRedisTemplate`或普通的`RedisTemplate`实例,或任何其他Spring Bean只要你愿意。默认情况下,这个实例将尝试使用`localhost:6379`连接Redis服务器: +你可以注入一个自动配置的`RedisConnectionFactory`,`StringRedisTemplate`或普通的`RedisTemplate`实例,或任何其他Spring Bean只要你愿意。默认情况下,这个实例将尝试使用`localhost:6379`连接Redis服务器。下面的列表展示了这样的bean的一个示例: ```java @Component public class MyBean { @@ -15,6 +15,6 @@ public class MyBean { } ``` -**提示** 为了实现更高级的定制,你也可以注册任意数量的实现了`JedisClientConfigurationBuilderCustomizer`的bean。如果你正在使用Lettuce,那就实现`JedisClientConfigurationBuilderCustomizer`。 +**提示** 为了实现更高级的定制,你也可以注册任意数量的实现了`LettuceClientConfigurationBuilderCustomizer`的bean。如果你使用Jedis,那就实现`JedisClientConfigurationBuilderCustomizer`。 如果你添加一个自己的,或任何自动配置类型的`@Bean`,它将替换默认实例(除了`RedisTemplate`的情况,它是根据`bean`的name 'redisTemplate'而不是类型进行排除的)。如果在classpath路径下存在`commons-pool2`,默认你会获得一个连接池工厂。 diff --git a/IV. Spring Boot features/30.10 InfluxDB.md b/IV. Spring Boot features/30.10 InfluxDB.md index f4484298..3c82a223 100644 --- a/IV. Spring Boot features/30.10 InfluxDB.md +++ b/IV. Spring Boot features/30.10 InfluxDB.md @@ -1,3 +1,3 @@ ### 30.10 InfluxDB -[InfluxDB](https://www.influxdata.com/)是一个开源时序型数据库,着力于在操作监控、应用程序度量、物联网传感器数据和实时分析等领域,快速、高可靠性地存储与查询时序型数据。 \ No newline at end of file +[InfluxDB](https://www.influxdata.com/)是一个开源时序型数据库,着力于操作监控、应用程序度量、物联网传感器数据和实时分析等领域,快速、高可靠性地存储与查询时序型数据。 diff --git a/IV. Spring Boot features/30.10.1 Connecting to InfluxDB.md b/IV. Spring Boot features/30.10.1 Connecting to InfluxDB.md index 2bb10fe1..b8605b2e 100644 --- a/IV. Spring Boot features/30.10.1 Connecting to InfluxDB.md +++ b/IV. Spring Boot features/30.10.1 Connecting to InfluxDB.md @@ -1,7 +1,10 @@ ### 30.10.1 连接InfluxDB -只要`influxdb-java`客户端在类路径下,而且如下所示,设置了数据库的url,Spring Boot就能自动配置InfluxDB实例。 +只要`influxdb-java`客户端在类路径下,而且设置了数据库的url,Spring Boot就能自动配置InfluxDB实例。如下所示: ```properties spring.influx.url=http://172.0.0.1:8086 ``` -如果连接InfluxDB需要用户名和密码,你可以相应地设置`spring.influx.user`和`spring.influx.password`。 \ No newline at end of file + +如果连接InfluxDB需要用户名和密码,你可以相应地设置`spring.influx.user`和`spring.influx.password`。 + +InfluxDB依赖OkHttp。如果你需要调整http客户端`InfluxDB`在幕后使用,你可以注册一个`OkHttpClient.Builder` bean。 diff --git a/IV. Spring Boot features/30.2. MongoDB.md b/IV. Spring Boot features/30.2. MongoDB.md index 9b950aa0..3d0ba2b3 100644 --- a/IV. Spring Boot features/30.2. MongoDB.md +++ b/IV. Spring Boot features/30.2. MongoDB.md @@ -1,3 +1,3 @@ ### 30.2. MongoDB -[MongoDB](http://www.mongodb.com/)是一个开源的NoSQL文档数据库,它使用类JSON格式的模式(schema)替换了传统的基于表的关系数据。Spring Boot为使用MongoDB提供了很多便利,包括`spring-boot-starter-data-mongodb`和`spring-boot-starter-data-mongodb-reactive`'Starter'。 +[MongoDB](https://www.mongodb.com/)是一个开源的NoSQL文档数据库,它使用类JSON格式的模式(schema)替换了传统的基于表的关系数据。Spring Boot为使用MongoDB提供了很多便利,包括`spring-boot-starter-data-mongodb`和`spring-boot-starter-data-mongodb-reactive`“Starter”。 diff --git a/IV. Spring Boot features/30.2.1. Connecting to a MongoDB Database.md b/IV. Spring Boot features/30.2.1. Connecting to a MongoDB Database.md new file mode 100644 index 00000000..a7ed4207 --- /dev/null +++ b/IV. Spring Boot features/30.2.1. Connecting to a MongoDB Database.md @@ -0,0 +1,40 @@ +### 30.2.1. 连接MongoDB数据库 + +你可以注入一个自动配置的`org.springframework.data.mongodb.MongoDbFactory`来访问Mongo数据库。默认情况下,该实例将尝试使用URL `mongodb://localhost/test`连接到MongoDB服务器。下面的例子展示了怎么连接到一个MongoDB数据库: +```java +import org.springframework.data.mongodb.MongoDbFactory; +import com.mongodb.DB; + +@Component +public class MyBean { + + private final MongoDbFactory mongo; + + @Autowired + public MyBean(MongoDbFactory mongo) { + this.mongo = mongo; + } + + // ... + public void example() { + DB db = mongo.getDb(); + // ... + } +} +``` +你可以设置`spring.data.mongodb.uri`来改变该URL,并配置其它的设置,比如副本集,如下所示: +```properties +spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test +``` +另外,跟正在使用的Mongo 2.x一样,你可以指定`host`/`port`,比如,在`application.properties`中添加以下配置: +```java +spring.data.mongodb.host=mongoserver +spring.data.mongodb.port=27017 +``` +**注** Mongo 3.0 Java驱动不支持`spring.data.mongodb.host`和`spring.data.mongodb.port`。对于这种情况,`spring.data.mongodb.uri`需要提供全部的配置信息。 + +**注** 如果没有指定`spring.data.mongodb.port`,默认使用`27017`,上述示例中可以删除这行配置。 + +**注** 如果不使用Spring Data Mongo,你可以注入`com.mongodb.MongoClient`bean,以代替`MongoDbFactory`。如果想完全控制MongoDB连接的建立过程,你可以声明自己的`MongoDbFactory`或`MongoClient`bean。 + +**注** 如果你正在使用响应式的驱动,使用SSL需要Netty。如果Netty可用,并且将使用的工厂没有被配置,那么工厂会被自动配置好。 diff --git a/IV. Spring Boot features/30.2.1. Connecting to a MongoDB database.md b/IV. Spring Boot features/30.2.1. Connecting to a MongoDB database.md deleted file mode 100644 index 7f0cd1b1..00000000 --- a/IV. Spring Boot features/30.2.1. Connecting to a MongoDB database.md +++ /dev/null @@ -1,41 +0,0 @@ -### 30.2.1. 连接MongoDB数据库 - -你可以注入一个自动配置的`org.springframework.data.mongodb.MongoDbFactory`来访问Mongo数据库。默认情况下,该实例将尝试使用URL `mongodb://localhost/test`连接到MongoDB服务器: -```java -import org.springframework.data.mongodb.MongoDbFactory; -import com.mongodb.DB; - -@Component -public class MyBean { - - private final MongoDbFactory mongo; - - @Autowired - public MyBean(MongoDbFactory mongo) { - this.mongo = mongo; - } - - // ... - public void example() { - DB db = mongo.getDb(); - // ... - } -} -``` -你可以设置`spring.data.mongodb.uri`来改变该url,并配置其他的设置,比如副本集: -```properties -spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test -``` -另外,跟正在使用的Mongo 2.x一样,你可以指定`host`/`port`,比如,在`application.properties`中添加以下配置: -```java -spring.data.mongodb.host=mongoserver -spring.data.mongodb.port=27017 -``` -**注** Mongo 3.0 Java驱动不支持`spring.data.mongodb.host`和`spring.data.mongodb.port`,对于这种情况,`spring.data.mongodb.uri`需要提供全部的配置信息。 - -**注** 如果没有指定`spring.data.mongodb.port`,默认使用`27017`,上述示例中可以删除这行配置。 - -**注** 如果不使用Spring Data Mongo,你可以注入`com.mongodb.Mongo beans`以代替`MongoDbFactory`。 - -如果想完全控制MongoDB连接的建立过程,你可以声明自己的`MongoDbFactory`或`Mongo` bean。 -如果想全面控制MongoDB连接的建立,你也可以声明自己的MongoDbFactory或Mongo,@Beans。 diff --git a/IV. Spring Boot features/30.2.2. MongoTemplate.md b/IV. Spring Boot features/30.2.2. MongoTemplate.md index 1ffdbcab..f2957c50 100644 --- a/IV. Spring Boot features/30.2.2. MongoTemplate.md +++ b/IV. Spring Boot features/30.2.2. MongoTemplate.md @@ -1,6 +1,6 @@ ### 30.2.2. MongoDBTemplate -Spring Data Mongo提供了一个[MongoTemplate](http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.html)类,它的设计和Spring的`JdbcTemplate`很相似。跟`JdbcTemplate`一样,Spring Boot会为你自动配置一个bean,你只需简单的注入即可: +[Spring Data MongoDB](https://projects.spring.io/spring-data-mongodb/)提供了一个[MongoTemplate](https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.html)类。它的设计和Spring的`JdbcTemplate`很相似。跟`JdbcTemplate`一样,Spring Boot会为你自动配置一个bean用来注入模版,如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; @@ -18,4 +18,4 @@ public class MyBean { // ... } ``` -具体参考`MongoOperations` Javadoc。 +具体参考[`MongoOperations`Javadoc](https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html)。 diff --git a/IV. Spring Boot features/30.2.3. Spring Data MongoDB Repositories.md b/IV. Spring Boot features/30.2.3. Spring Data MongoDB Repositories.md new file mode 100644 index 00000000..7b109df6 --- /dev/null +++ b/IV. Spring Boot features/30.2.3. Spring Data MongoDB Repositories.md @@ -0,0 +1,23 @@ +### 30.2.3. Spring Data MongoDB仓库 + +Spring Data包含的仓库也支持MongoDB,正如上面讨论的JPA仓库,基于方法名自动创建查询是基本的原则。 + +实际上,不管是Spring Data JPA还是Spring Data MongoDB都共享相同的基础设施。所以你可以使用上面的JPA示例,并假设那个`City`现在是一个Mongo数据类而不是JPA `@Entity`,它将以同样的方式工作,如下所示: +```java +package com.example.myapp.domain; + +import org.springframework.data.domain.*; +import org.springframework.data.repository.*; + +public interface CityRepository extends Repository { + + Page findAll(Pageable pageable); + + City findByNameAndCountryAllIgnoringCase(String name, String country); + +} +``` + +**注** 你可以通过`@EntityScan`注解自定义文档扫描位置。 + +**注** 想详细了解Spring Data MongoDB,包括它丰富的对象映射技术,可以查看它的[参考文档](https://projects.spring.io/spring-data-mongodb/)。 diff --git a/IV. Spring Boot features/30.2.3. Spring Data MongoDB repositories.md b/IV. Spring Boot features/30.2.3. Spring Data MongoDB repositories.md deleted file mode 100644 index c3b0ac54..00000000 --- a/IV. Spring Boot features/30.2.3. Spring Data MongoDB repositories.md +++ /dev/null @@ -1,20 +0,0 @@ -### 30.2.3. Spring Data MongoDB仓库 - -Spring Data包含的仓库也支持MongoDB,正如上面讨论的JPA仓库,基于方法名自动创建查询是基本的原则。 - -实际上,不管是Spring Data JPA还是Spring Data MongoDB都共享相同的基础设施。所以你可以使用上面的JPA示例,并假设那个`City`现在是一个Mongo数据类而不是JPA `@Entity`,它将以同样的方式工作: -```java -package com.example.myapp.domain; - -import org.springframework.data.domain.*; -import org.springframework.data.repository.*; - -public interface CityRepository extends Repository { - - Page findAll(Pageable pageable); - - City findByNameAndCountryAllIgnoringCase(String name, String country); - -} -``` -**注** 想详细了解Spring Data MongoDB,包括它丰富的对象映射技术,可以查看它的[参考文档](http://projects.spring.io/spring-data-mongodb/)。 diff --git a/IV. Spring Boot features/30.3 Neo4j.md b/IV. Spring Boot features/30.3 Neo4j.md index 5bdf5a01..51a57b41 100644 --- a/IV. Spring Boot features/30.3 Neo4j.md +++ b/IV. Spring Boot features/30.3 Neo4j.md @@ -1,3 +1,3 @@ ### 30.3 Neo4j -[Neo4j](http://neo4j.com/)是一个开源的NoSQL图数据库,它使用图(graph)相关的概念来描述数据模型,把数据保存为图中的节点以及节点之间的关系。相比传统rdbms(关系管理系统)的方式,Neo4j更适合大数据关系分析。Spring Boot为使用Neo4j提供很多便利,包括`spring-boot-starter-data-neo4j`‘Starter’。 +[Neo4j](http://neo4j.com/)是一个开源的NoSQL图数据库,它使用图(graph)相关的概念来描述数据模型,把数据保存为图中的节点以及节点之间的关系。相比传统rdbms(关系管理系统)的方式,Neo4j更适合大数据关系分析。Spring Boot为使用Neo4j提供很多便利,包括`spring-boot-starter-data-neo4j`“Starter”。 diff --git a/IV. Spring Boot features/30.3.1 Connecting to a Neo4j Database.md b/IV. Spring Boot features/30.3.1 Connecting to a Neo4j Database.md new file mode 100644 index 00000000..9a0f8b62 --- /dev/null +++ b/IV. Spring Boot features/30.3.1 Connecting to a Neo4j Database.md @@ -0,0 +1,27 @@ +### 30.3.1 连接Neo4j数据库 + +你可以注入一个自动配置的`Neo4jSession`,`Session`,或`Neo4jOperations`实例,就像使用其他Spring Bean那样。该实例默认使用`localhost:7474`连接Neo4j服务器。下面的例子展示了怎么样注入一个Neo4j bean: +```java +@Component +public class MyBean { + + private final Neo4jTemplate neo4jTemplate; + + @Autowired + public MyBean(Neo4jTemplate neo4jTemplate) { + this.neo4jTemplate = neo4jTemplate; + } + + // ... + +} +``` +添加自己的`org.neo4j.ogm.config.Configuration` `@Bean`,你就能完全控制该配置了。同时,添加一个`Neo4jOperations`类型的`@Bean`可以禁用自动配置。 + +通过`spring.data.neo4j.*`属性可以配置使用的用户和凭证,如下所示: + +```properties +spring.data.neo4j.uri=http://my-server:7474 +spring.data.neo4j.username=neo4j +spring.data.neo4j.password=secret +``` diff --git a/IV. Spring Boot features/30.3.1 Connecting to a Neo4j database.md b/IV. Spring Boot features/30.3.1 Connecting to a Neo4j database.md deleted file mode 100644 index 6a95edc2..00000000 --- a/IV. Spring Boot features/30.3.1 Connecting to a Neo4j database.md +++ /dev/null @@ -1,26 +0,0 @@ -### 30.3.1 连接Neo4j数据库 - -你可以注入一个自动配置的`Neo4jSession`,`Session`,或`Neo4jOperations`实例,就像使用其他Spring Bean那样。该实例默认使用`localhost:7474`连接Neo4j服务器: -```java -@Component -public class MyBean { - - private final Neo4jTemplate neo4jTemplate; - - @Autowired - public MyBean(Neo4jTemplate neo4jTemplate) { - this.neo4jTemplate = neo4jTemplate; - } - - // ... - -} -``` -添加自己的`org.neo4j.ogm.config.Configuration` `@Bean`,你就能完全控制该配置了。同时,添加一个`Neo4jOperations`类型的`@Bean`可以禁用自动配置。 - -通过`spring.data.neo4j.*`属性可以配置使用的用户和凭证: -```properties -spring.data.neo4j.uri=http://my-server:7474 -spring.data.neo4j.username=neo4j -spring.data.neo4j.password=secret -``` diff --git a/IV. Spring Boot features/30.3.2 Using the Embedded Mode.md b/IV. Spring Boot features/30.3.2 Using the Embedded Mode.md new file mode 100644 index 00000000..1a588e3f --- /dev/null +++ b/IV. Spring Boot features/30.3.2 Using the Embedded Mode.md @@ -0,0 +1,9 @@ +### 30.3.2 使用内嵌模式 + +如果将`org.neo4j:neo4j-ogm-embedded-driver`依赖添加到应用中,Spring Boot会自动配置一个进程内(in-process)的内嵌Neo4j实例,当应用关闭时,该实例不会持久化任何数据。设置`spring.data.neo4j.embedded.enabled=false`可显式关闭该模式。你也可以提供指向数据库文件的路径,来启用内嵌模式的持久化特性,如下所示: + +```properties +spring.data.neo4j.uri=file://var/tmp/graph.db +``` + +**注** Neo4j OGM内嵌的驱动不提供Neo4j内核。用户需要手动添加依赖,详情请查看[文档](http://neo4j.com/docs/ogm-manual/current/reference/#reference:getting-started)。 diff --git a/IV. Spring Boot features/30.3.2 Using the embedded mode.md b/IV. Spring Boot features/30.3.2 Using the embedded mode.md deleted file mode 100644 index 9fe5981b..00000000 --- a/IV. Spring Boot features/30.3.2 Using the embedded mode.md +++ /dev/null @@ -1,8 +0,0 @@ -### 30.3.2 使用内嵌模式 - -如果将`org.neo4j:neo4j-ogm-embedded-driver`依赖添加到应用中,Spring Boot会自动配置一个进程内(in-process)的内嵌Neo4j实例,当应用关闭时,该实例不会持久化任何数据。设置`spring.data.neo4j.embedded.enabled=false`可显式关闭该模式,你也可以启用内嵌模式的持久化特性: -```properties -spring.data.neo4j.uri=file://var/tmp/graph.db -``` - -**注** Neo4j OGM内嵌的驱动不提供Neo4j内核。用户需要手动添加依赖,详情请查看[文档](http://neo4j.com/docs/ogm-manual/current/reference/#reference:getting-started)。 \ No newline at end of file diff --git a/IV. Spring Boot features/30.3.3 Neo4jSession.md b/IV. Spring Boot features/30.3.3 Neo4jSession.md index 0780e43e..558f3039 100644 --- a/IV. Spring Boot features/30.3.3 Neo4jSession.md +++ b/IV. Spring Boot features/30.3.3 Neo4jSession.md @@ -1,6 +1,7 @@ ### 30.3.3 Neo4jSession -默认地,如果你正在运行一个网络应用,会话会被绑定到请求的整个处理过程的线程上(也就是“在视图中打开会话”模式)。如果你不想要这个行为,在你的`application.properties`中加入下面这句: +默认地,如果你正在运行一个网络应用,会话会被绑定到请求的整个处理过程的线程上(也就是,它使用“在视图中打开会话”模式)。如果你不想要这个行为,在你的`application.properties`中加入下面这行: + ```properties spring.data.neo4j.open-in-view=false -``` \ No newline at end of file +``` diff --git a/IV. Spring Boot features/30.3.4 Spring Data Neo4j Repositories.md b/IV. Spring Boot features/30.3.4 Spring Data Neo4j Repositories.md new file mode 100644 index 00000000..de9a441f --- /dev/null +++ b/IV. Spring Boot features/30.3.4 Spring Data Neo4j Repositories.md @@ -0,0 +1,12 @@ +### 30.3.4 Spring Data Neo4j仓库 + +Spring Data包含的仓库也支持Neo4j,实际上,Spring Data JPA和Spring Data Neo4j使用相同的常用设施,所以你可以采用先前JPA的示例,假设`City`现在是一个Neo4j OGM `@NodeEntity`而不是JPA `@Entity`,它将以同样的方式工作。 + +**注** 你可以使用`@EntityScan`注解定义实体扫描路径。 + +将以下两个注解添加到你的Spring configuration,可以启用repository支持(还有可选的对`@Transactional`的支持): + +```java +@EnableNeo4jRepositories(basePackages = "com.example.myapp.repository") +@EnableTransactionManagement +``` diff --git a/IV. Spring Boot features/30.3.4 Spring Data Neo4j repositories.md b/IV. Spring Boot features/30.3.4 Spring Data Neo4j repositories.md deleted file mode 100644 index d09d9bf6..00000000 --- a/IV. Spring Boot features/30.3.4 Spring Data Neo4j repositories.md +++ /dev/null @@ -1,11 +0,0 @@ -### 30.3.4 Spring Data Neo4j仓库 - -Spring Data包含的仓库也支持Neo4j,实际上,Spring Data JPA和Spring Data Neo4j使用相同的常用设施,所以你可以采用先前JPA的示例,假设`City`现在是一个Neo4j OGM `@NodeEntity`而不是JPA `@Entity`,它将以同样的方式工作。 - -**注** 你可以使用`@EntityScan`注解定义实体扫描路径。 - -将以下两个注解添加到你的Spring configuration,可以启用repository支持(还有可选的对`@Transactional`的支持): -```java -@EnableNeo4jRepositories(basePackages = "com.example.myapp.repository") -@EnableTransactionManagement -``` diff --git a/IV. Spring Boot features/30.3.5 Repository Example.md b/IV. Spring Boot features/30.3.5 Repository Example.md new file mode 100644 index 00000000..72ae9f3e --- /dev/null +++ b/IV. Spring Boot features/30.3.5 Repository Example.md @@ -0,0 +1,20 @@ +### 30.3.5 仓库示例 + +下面的例子展示了Neo4j仓库的接口定义: + +```java +package com.example.myapp.domain; + +import org.springframework.data.domain.*; +import org.springframework.data.repository.*; + +public interface CityRepository extends GraphRepository { + + Page findAll(Pageable pageable); + + City findByNameAndCountry(String name, String country); + +} +``` + +**注** 想详细了解Spring Data Neo4j,包括它丰富的对象映射技术,可查看它的[参考文档](https://projects.spring.io/spring-data-neo4j/)。 diff --git a/IV. Spring Boot features/30.3.5 Repository example.md b/IV. Spring Boot features/30.3.5 Repository example.md deleted file mode 100644 index 52c60862..00000000 --- a/IV. Spring Boot features/30.3.5 Repository example.md +++ /dev/null @@ -1,17 +0,0 @@ -### 30.3.5 仓库示例 - -```java -package com.example.myapp.domain; - -import org.springframework.data.domain.*; -import org.springframework.data.repository.*; - -public interface CityRepository extends GraphRepository { - - Page findAll(Pageable pageable); - - City findByNameAndCountry(String name, String country); - -} -``` -**注** 想详细了解Spring Data Neo4j,包括它丰富的对象映射技术,可查看它的[参考文档](http://projects.spring.io/spring-data-neo4j/)。 diff --git a/IV. Spring Boot features/30.4 Gemfire.md b/IV. Spring Boot features/30.4 Gemfire.md index ad893b9c..b262b9f0 100644 --- a/IV. Spring Boot features/30.4 Gemfire.md +++ b/IV. Spring Boot features/30.4 Gemfire.md @@ -1,3 +1,3 @@ ### 30.4 Gemfire -[Spring Data Gemfire](https://github.com/spring-projects/spring-data-gemfire)为使用[Pivotal Gemfire](http://www.pivotal.io/big-data/pivotal-gemfire#details)数据管理平台提供了方便的,Spring友好的工具。Spring Boot提供了一个用于聚集依赖的`spring-boot-starter-data-gemfire`'Starter',目前不支持Gemfire的自动配置,但你只需使用[一个注解](https://github.com/spring-projects/spring-data-gemfire/blob/master/src/main/java/org/springframework/data/gemfire/repository/config/EnableGemfireRepositories.java)就能使Spring Data仓库支持它。 +[Spring Data Gemfire](https://github.com/spring-projects/spring-data-gemfire)为使用[Pivotal Gemfire](https://pivotal.io/big-data/pivotal-gemfire#details)数据管理平台提供了方便的、对Spring友好的工具。Spring Boot提供了一个用于聚集依赖的`spring-boot-starter-data-gemfire`“Starter”。虽然目前不支持Gemfire的自动配置,但是你可以使用[一个注解:`@EnableGemfireRepositories`](https://github.com/spring-projects/spring-data-gemfire/blob/master/src/main/java/org/springframework/data/gemfire/repository/config/EnableGemfireRepositories.java)启用Spring Data仓库。 diff --git a/IV. Spring Boot features/30.5 Solr.md b/IV. Spring Boot features/30.5 Solr.md index 0da856b0..93881693 100644 --- a/IV. Spring Boot features/30.5 Solr.md +++ b/IV. Spring Boot features/30.5 Solr.md @@ -1,3 +1,3 @@ ### 30.5 Solr -[Apache Solr](http://lucene.apache.org/solr/)是一个搜索引擎。Spring Boot为Solr 5客户端library提供基本的自动配置,[Spring Data Solr](https://github.com/spring-projects/spring-data-solr)提供了在它之上的抽象,还有用于收集依赖的`spring-boot-starter-data-solr`'Starter'。 +[Apache Solr](https://lucene.apache.org/solr/)是一个搜索引擎。Spring Boot为Solr 5客户端library提供基本的自动配置,[Spring Data Solr](https://github.com/spring-projects/spring-data-solr)提供了在它之上的抽象,还有用于收集依赖的`spring-boot-starter-data-solr`”Starter“。 diff --git a/IV. Spring Boot features/30.5.1 Connecting to Solr.md b/IV. Spring Boot features/30.5.1 Connecting to Solr.md index 25d2bda6..4a8f6684 100644 --- a/IV. Spring Boot features/30.5.1 Connecting to Solr.md +++ b/IV. Spring Boot features/30.5.1 Connecting to Solr.md @@ -1,6 +1,6 @@ ### 30.5.1 连接Solr -你可以注入一个自动配置的`SolrClient`实例,就像其他Spring beans那样,该实例默认使用`localhost:8983/solr`连接Solr服务器: +你可以注入一个自动配置的`SolrClient`实例。就像其他Spring beans那样,该实例默认使用`localhost:8983/solr`连接Solr服务器。下面的例子展示了怎样注入一个Solr bean: ```java @Component public class MyBean { diff --git a/IV. Spring Boot features/30.5.2 Spring Data Solr Repositories.md b/IV. Spring Boot features/30.5.2 Spring Data Solr Repositories.md new file mode 100644 index 00000000..e2470e99 --- /dev/null +++ b/IV. Spring Boot features/30.5.2 Spring Data Solr Repositories.md @@ -0,0 +1,7 @@ +### 30.5.2 Spring Data Solr仓库 + +Spring Data包含的仓库也支持Apache Solr,正如先前讨论的JPA仓库,基于方法名自动创建查询是基本的原则。 + +实际上,不管是Spring Data JPA还是Spring Data Solr都共享相同的基础设施。你可以使用先前的JPA示例,并假设那个`City`现在是一个`@SolrDocument`类而不是JPA `@Entity`,它将以同样的方式工作。 + +**注** 具体参考[Spring Data Solr文档](https://projects.spring.io/spring-data-solr/)。 diff --git a/IV. Spring Boot features/30.5.2 Spring Data Solr repositories.md b/IV. Spring Boot features/30.5.2 Spring Data Solr repositories.md deleted file mode 100644 index 86efff9e..00000000 --- a/IV. Spring Boot features/30.5.2 Spring Data Solr repositories.md +++ /dev/null @@ -1,7 +0,0 @@ -### 30.5.2 Spring Data Solr仓库 - -Spring Data包含的仓库也支持Apache Solr,正如先前讨论的JPA仓库,基于方法名自动创建查询是基本的原则。 - -实际上,不管是Spring Data JPA还是Spring Data Solr都共享相同的基础设施。所以你可以使用先前的JPA示例,并假设那个`City`现在是一个`@SolrDocument`类而不是JPA `@Entity`,它将以同样的方式工作。 - -**注** 具体参考[Spring Data Solr文档](http://projects.spring.io/spring-data-solr/)。 diff --git a/IV. Spring Boot features/30.6 Elasticsearch.md b/IV. Spring Boot features/30.6 Elasticsearch.md index 7f035f96..fefa3ae4 100644 --- a/IV. Spring Boot features/30.6 Elasticsearch.md +++ b/IV. Spring Boot features/30.6 Elasticsearch.md @@ -1,3 +1,3 @@ ### 30.6 Elasticsearch -[Elastic Search](http://www.elasticsearch.org/)是一个开源的,分布式,实时搜索和分析引擎。Spring Boot为Elasticsearch提供基本的自动配置,[Spring Data Elasticsearch](https://github.com/spring-projects/spring-data-elasticsearch)提供在它之上的抽象,还有用于收集依赖的`spring-boot-starter-data-elasticsearch`'Starter'。 +[Elastic Search](http://www.elasticsearch.org/)是一个开源的、分布式的、实时搜索和分析引擎。Spring Boot为Elasticsearch提供基本的自动配置。[Spring Data Elasticsearch](https://github.com/spring-projects/spring-data-elasticsearch)提供在它之上的抽象。还有用于收集依赖的`spring-boot-starter-data-elasticsearch`“Starter”。Spring Boot也支持[Jest](https://github.com/searchbox-io/Jest)。 diff --git a/IV. Spring Boot features/30.6.1 Connecting to Elasticsearch by Using Jest.md b/IV. Spring Boot features/30.6.1 Connecting to Elasticsearch by Using Jest.md new file mode 100644 index 00000000..d984f248 --- /dev/null +++ b/IV. Spring Boot features/30.6.1 Connecting to Elasticsearch by Using Jest.md @@ -0,0 +1,25 @@ +### 30.6.1 使用Jest连接Elasticsearch + +如果添加`Jest`依赖,你可以注入一个自动配置的`JestClient`,默认目标为`http://localhost:9200/`。你也可以进一步配置该客户端,如下所示: + +```properties +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 +``` + +为了实现更高级的定制,你也可以注册任意数量的实现了`HttpClientConfigBuilderCustomizer`的bean。下面的例子调整了额外的HTTP设置。 + +```java +static class HttpSettingsCustomizer implements HttpClientConfigBuilderCustomizer { + + @Override + public void customize(HttpClientConfig.Builder builder) { + builder.maxTotalConnection(100).defaultMaxTotalConnectionPerRoute(5); + } + +} +``` + +定义一个`JestClient` bean以完全控制注册过程。 diff --git a/IV. Spring Boot features/30.6.1 Connecting to Elasticsearch using Jest.md b/IV. Spring Boot features/30.6.1 Connecting to Elasticsearch using Jest.md deleted file mode 100644 index 0a9fb0c6..00000000 --- a/IV. Spring Boot features/30.6.1 Connecting to Elasticsearch using Jest.md +++ /dev/null @@ -1,21 +0,0 @@ -### 30.6.1 使用Jest连接Elasticsearch - -如果添加`Jest`依赖,你可以注入一个自动配置的`JestClient`,默认目标为`http://localhost:9200/`,也可以进一步配置该客户端: -```properties -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 -``` -为了实现更高级的定制,你也可以注册任意数量的实现了`HttpClientConfigBuilderCustomizer`的bean。下面的例子调整了额外的HTTP设置。 -```java -static class HttpSettingsCustomizer implements HttpClientConfigBuilderCustomizer { - - @Override - public void customize(HttpClientConfig.Builder builder) { - builder.maxTotalConnection(100).defaultMaxTotalConnectionPerRoute(5); - } - -} -``` -定义一个`JestClient` bean以完全控制注册过程。 diff --git a/IV. Spring Boot features/30.6.2 Connecting to Elasticsearch by Using Spring Data.md b/IV. Spring Boot features/30.6.2 Connecting to Elasticsearch by Using Spring Data.md new file mode 100644 index 00000000..5036fa55 --- /dev/null +++ b/IV. Spring Boot features/30.6.2 Connecting to Elasticsearch by Using Spring Data.md @@ -0,0 +1,24 @@ +### 30.6.2 使用Spring Data连接Elasticsearch + +为了连接Elasticsearch,你必须提供一个或者更多的集群节点的地址。可以通过设置`spring.data.elasticsearch.cluster-nodes`(逗号分隔的‘host:port’列表),来指定地址。当配置完成后,`ElasticsearchTemplate`或者`TransportClient`就能够像其它Spring bean一样被注入。如下所示: + +```properties +spring.data.elasticsearch.cluster-nodes=localhost:9300 +``` + +```java +@Component +public class MyBean { + + private final ElasticsearchTemplate template; + + public MyBean(ElasticsearchTemplate template) { + this.template = template; + } + + // ... + +} +``` + +如果你添加自己的`ElasticsearchTemplate`或者`TransportClient` `@Bean`,它将覆盖默认实例。 diff --git a/IV. Spring Boot features/30.6.2 Connecting to Elasticsearch using Spring Data.md b/IV. Spring Boot features/30.6.2 Connecting to Elasticsearch using Spring Data.md deleted file mode 100644 index cb3e3ab5..00000000 --- a/IV. Spring Boot features/30.6.2 Connecting to Elasticsearch using Spring Data.md +++ /dev/null @@ -1,21 +0,0 @@ -### 30.6.2 使用Spring Data连接Elasticsearch - -为了连接Elasticsearch,你必须提供一个或者更多的集群节点的地址。可以通过设置`spring.data.elasticsearch.cluster-nodes`(逗号分隔的‘host:port’列表),来指定地址。当配置完成后,`ElasticsearchTemplate`或者`TransportClient`就能够像其它Spring bean一样被注入。 -```properties -spring.data.elasticsearch.cluster-nodes=localhost:9300 -``` -```java -@Component -public class MyBean { - - private final ElasticsearchTemplate template; - - public MyBean(ElasticsearchTemplate template) { - this.template = template; - } - - // ... - -} -``` -如果你添加自己的`ElasticsearchTemplate`或者`TransportClient``@Bean`,它将覆盖默认实例。 diff --git a/IV. Spring Boot features/30.6.3 Spring Data Elasticsearch Repositories.md b/IV. Spring Boot features/30.6.3 Spring Data Elasticsearch Repositories.md new file mode 100644 index 00000000..43f2cc38 --- /dev/null +++ b/IV. Spring Boot features/30.6.3 Spring Data Elasticsearch Repositories.md @@ -0,0 +1,7 @@ +### 30.6.3 Spring Data Elasticseach仓库 + +Spring Data包含的仓库也支持Elasticsearch,正如前面讨论的JPA仓库,基于方法名自动创建查询是基本的原则。 + +实际上,不管是Spring Data JPA还是Spring Data Elasticsearch都共享相同的基础设施。所以你可以使用前面的JPA示例,并假设那个`City`现在是一个Elasticsearch `@Document`类而不是JPA `@Entity`,它将以同样的方式工作。 + +**注** 具体参考[Spring Data Elasticsearch文档](https://docs.spring.io/spring-data/elasticsearch/docs/)。 diff --git a/IV. Spring Boot features/30.6.3 Spring Data Elasticsearch repositories.md b/IV. Spring Boot features/30.6.3 Spring Data Elasticsearch repositories.md deleted file mode 100644 index f4a90366..00000000 --- a/IV. Spring Boot features/30.6.3 Spring Data Elasticsearch repositories.md +++ /dev/null @@ -1,7 +0,0 @@ -### 30.6.3 Spring Data Elasticseach仓库 - -Spring Data包含的仓库也支持Elasticsearch,正如前面讨论的JPA仓库,基于方法名自动创建查询是基本的原则。 - -实际上,不管是Spring Data JPA还是Spring Data Elasticsearch都共享相同的基础设施。所以你可以使用前面的JPA示例,并假设那个`City`现在是一个Elasticsearch `@Document`类而不是JPA `@Entity`,它将以同样的方式工作。 - -**注** 具体参考[Spring Data Elasticsearch文档](http://docs.spring.io/spring-data/elasticsearch/docs/)。 diff --git a/IV. Spring Boot features/30.7 Cassandra.md b/IV. Spring Boot features/30.7 Cassandra.md index 55ee494f..53b9023f 100644 --- a/IV. Spring Boot features/30.7 Cassandra.md +++ b/IV. Spring Boot features/30.7 Cassandra.md @@ -1,3 +1,3 @@ ### 30.7 Cassandra -[Cassandra](http://cassandra.apache.org/)是一个开源,分布式数据库管理系统,设计用于处理跨很多商品服务器的大数据。Spring Boot为Cassandra提供自动配置,[Spring Data Cassandra](https://github.com/spring-projects/spring-data-cassandra)提供在它之上的抽象,还有收集依赖的`spring-boot-starter-data-cassandra`‘Starter’。 +[Cassandra](https://cassandra.apache.org/)是一个开源的、分布式数据库管理系统,设计用于处理跨很多商品服务器的大数据。Spring Boot为Cassandra提供自动配置。[Spring Data Cassandra](https://github.com/spring-projects/spring-data-cassandra)提供在它之上的抽象。`spring-boot-starter-data-cassandra`“Starter”方便地收集了依赖。 diff --git a/IV. Spring Boot features/30.7.1 Connecting to Cassandra.md b/IV. Spring Boot features/30.7.1 Connecting to Cassandra.md index 247151a0..4682759d 100644 --- a/IV. Spring Boot features/30.7.1 Connecting to Cassandra.md +++ b/IV. Spring Boot features/30.7.1 Connecting to Cassandra.md @@ -1,10 +1,14 @@ ### 30.7.1 连接Cassandra -你可以注入一个自动配置的`CassandraTemplate`或Cassandra `Session`实例,就像注入其他Spring Bean那样。`spring.data.cassandra.*`属性可用来自定义该连接,通常你需要提供`keyspace-name`和`contact-points`属性: +你可以注入一个自动配置的`CassandraTemplate`或Cassandra `Session`实例,就像注入其他Spring Bean那样。`spring.data.cassandra.*`属性可用来自定义该连接,通常你需要提供`keyspace-name`和`contact-points`属性。如下所示: + ```properties spring.data.cassandra.keyspace-name=mykeyspace spring.data.cassandra.contact-points=cassandrahost1,cassandrahost2 ``` + +下面的代码展示了怎样注入Cassandra bean: + ```java @Component public class MyBean { @@ -20,4 +24,5 @@ public class MyBean { } ``` + 如果添加自己的`CassandraTemplate`类型的`@Bean`,它将替换默认实例。 diff --git a/IV. Spring Boot features/30.7.2 Spring Data Cassandra Repositories.md b/IV. Spring Boot features/30.7.2 Spring Data Cassandra Repositories.md new file mode 100644 index 00000000..b6e24af0 --- /dev/null +++ b/IV. Spring Boot features/30.7.2 Spring Data Cassandra Repositories.md @@ -0,0 +1,5 @@ +### 30.7.2 Spring Data Cassandra仓库 + +Spring Data包含的仓库对Cassandra提供基本支持,目前受到的限制比先前讨论的JPA仓库要多,并且需要使用`@Query`注解相应的查找方法。 + +**注** 想全面了解Spring Data Cassandra,可查看它的[参考指南](https://docs.spring.io/spring-data/cassandra/docs/)。 diff --git a/IV. Spring Boot features/30.7.2 Spring Data Cassandra repositories.md b/IV. Spring Boot features/30.7.2 Spring Data Cassandra repositories.md deleted file mode 100644 index a2441b2a..00000000 --- a/IV. Spring Boot features/30.7.2 Spring Data Cassandra repositories.md +++ /dev/null @@ -1,5 +0,0 @@ -### 30.7.2 Spring Data Cassandra仓库 - -Spring Data包含的仓库对Cassandra提供基本支持,目前受到的限制比先前讨论的JPA仓库要多,并且需要使用`@Query`注解相应的查找方法。 - -**注** 想全面了解Spring Data Cassandra,可查看它的[参考指南](http://docs.spring.io/spring-data/cassandra/docs/)。 diff --git a/IV. Spring Boot features/30.8 Couchbase.md b/IV. Spring Boot features/30.8 Couchbase.md index b8f3d9d5..dab3d97e 100644 --- a/IV. Spring Boot features/30.8 Couchbase.md +++ b/IV. Spring Boot features/30.8 Couchbase.md @@ -1,3 +1,3 @@ ### 30.8 Couchbase -[Couchbase](http://www.couchbase.com/)是一个基于文档,分布式多模型的开源数据库,设计用于交互式应用程序。Spring Boot为Couchbase提供自动配置,[Spring Data Couchbase](https://github.com/spring-projects/spring-data-couchbase)提供在它之上的抽象,还有收集依赖的`spring-boot-starter-data-couchbase`‘Starter’。 +[Couchbase](https://www.couchbase.com/)是一个基于文档的、分布式多模型的开源数据库,设计用于交互式应用程序。Spring Boot为Couchbase提供自动配置,[Spring Data Couchbase](https://github.com/spring-projects/spring-data-couchbase)提供在它之上的抽象,还有收集依赖的`spring-boot-starter-data-couchbase`“Starter”。 diff --git a/IV. Spring Boot features/30.8.1 Connecting to Couchbase.md b/IV. Spring Boot features/30.8.1 Connecting to Couchbase.md index 955dd326..cdd14d37 100644 --- a/IV. Spring Boot features/30.8.1 Connecting to Couchbase.md +++ b/IV. Spring Boot features/30.8.1 Connecting to Couchbase.md @@ -1,17 +1,21 @@ ### 30.8.1 连接Couchbase -通过添加Couchbase SDK和一些配置,你可以很容易获取一个`Bucket`和`Cluster`,`spring.couchbase.*`属性可用于自定义该连接。通常,你需要提供启动hosts,bucket name和password: +通过添加Couchbase SDK和一些配置,你可以获取一个`Bucket`和`Cluster`,`spring.couchbase.*`属性可用于自定义该连接。通常,你需要提供启动hosts、bucket name和password。如下所示: + ```properties spring.couchbase.bootstrap-hosts=my-host-1,192.168.1.123 spring.couchbase.bucket.name=my-bucket spring.couchbase.bucket.password=secret ``` + **注** 你至少需要提供启动host(s),在这种情况下,bucket name默认为`default`,password默认为空字符串。另外,你可以定义自己的`org.springframework.data.couchbase.config.CouchbaseConfigurer` `@Bean`来把控所有配置。 你也可以自定义一些`CouchbaseEnvironment`设置,例如,以下配置改变打开新`Bucket`的超时时间(timeout),还启用了SSL支持: + ```properties 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.*`属性。 diff --git a/IV. Spring Boot features/30.8.2 Spring Data Couchbase Repositories.md b/IV. Spring Boot features/30.8.2 Spring Data Couchbase Repositories.md new file mode 100644 index 00000000..e65a216e --- /dev/null +++ b/IV. Spring Boot features/30.8.2 Spring Data Couchbase Repositories.md @@ -0,0 +1,47 @@ +### 30.8.2 Spring Data Couchbase仓库 + +Spring Data包含的仓库也支持Couchbase,具体可查看Spring Data Couchbase的[参考文档](https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/)。 + +你可以注入一个自动配置的`CouchbaseTemplate`实例,就像注入其他Spring Bean那样,只要默认的`CouchbaseConfigurer`可以使用。 + +下面的例子展示了怎么样注入一个Couchbase bean: + +```java +@Component +public class MyBean { + + private final CouchbaseTemplate template; + + @Autowired + public MyBean(CouchbaseTemplate template) { + this.template = template; + } + + // ... + +} +``` + +你可以在你自己的配置中定义一些bean,来覆盖自动配置中提供的那些: + +* `CouchbaseTemplate` `@Bean` ,称为`couchbaseTemplate` +* `IndexManager` `@Bean`,称为`couchbaseIndexManager` +* `CustomConversions` `@Bean`,称为`couchbaseCustomConversions` + +为了避免在你的配置中硬编码那些名字,你可以重复使用由Spring Data Couchbase提供的`BeanNames`。例如,你可以像下面这样自定义要使用的转换器: + +```java +@Configuration +public class SomeConfiguration { + + @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) + public CustomConversions myCustomConversions() { + return new CustomConversions(...); + } + + // ... + +} +``` + +**提示** 如果想完全关闭Spring Data Couchbase的自动配置,你可以提供自己的`org.springframework.data.couchbase.config.AbstractCouchbaseDataConfiguration`实现。 diff --git a/IV. Spring Boot features/30.8.2 Spring Data Couchbase repositories.md b/IV. Spring Boot features/30.8.2 Spring Data Couchbase repositories.md deleted file mode 100644 index 8df2201c..00000000 --- a/IV. Spring Boot features/30.8.2 Spring Data Couchbase repositories.md +++ /dev/null @@ -1,41 +0,0 @@ -### 30.8.2 Spring Data Couchbase仓库 - -Spring Data包含的仓库也支持Couchbase,具体可查看Spring Data Couchbase的[参考文档](http://docs.spring.io/spring-data/couchbase/docs/current/reference/html/)。 - -你可以注入一个自动配置的`CouchbaseTemplate`实例,就像注入其他Spring Bean那样,只要默认的`CouchbaseConfigurer`可以使用。 -```java -@Component -public class MyBean { - - private final CouchbaseTemplate template; - - @Autowired - public MyBean(CouchbaseTemplate template) { - this.template = template; - } - - // ... - -} -``` -你可以在你自己的配置中定义一些bean,来覆盖自动配置中提供的那些: - -* `CouchbaseTemplate` `@Bean` ,称为`couchbaseTemplate` -* `IndexManager` `@Bean`,称为`couchbaseIndexManager` -* `CustomConversions` `@Bean`,称为`couchbaseCustomConversions` - -为了避免在你的配置中硬编码那些名字,你可以重复使用由Spring Data Couchbase提供的`BeanNames`。例如,你可以像下面这样自定义要使用的转换器: -```java -@Configuration -public class SomeConfiguration { - - @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS) - public CustomConversions myCustomConversions() { - return new CustomConversions(...); - } - - // ... - -} -``` -**提示** 如果想完全关闭Spring Data Couchbase的自动配置,你可以提供自己的`org.springframework.data.couchbase.config.AbstractCouchbaseDataConfiguration`实现。 diff --git a/IV. Spring Boot features/30.9 LDAP.md b/IV. Spring Boot features/30.9 LDAP.md index 090a1ec8..4b0adb2f 100644 --- a/IV. Spring Boot features/30.9 LDAP.md +++ b/IV. Spring Boot features/30.9 LDAP.md @@ -1,5 +1,5 @@ ### 30.9 LDAP -[LDAP](https://zh.wikipedia.org/wiki/%E8%BD%BB%E5%9E%8B%E7%9B%AE%E5%BD%95%E8%AE%BF%E9%97%AE%E5%8D%8F%E8%AE%AE) (轻型目录访问协议)是一个开放的,中立的,工业标准的应用协议,通过IP协议提供访问控制和维护分布式信息的目录信息。Spring Boot为任何兼容的LDAP服务器提供自动配置,同时也支持[UnboundID](https://www.ldap.com/unboundid-ldap-sdk-for-java) 的嵌入式内存中LDAP服务器。 +[LDAP](https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol) (轻型目录访问协议)是一个开放的、中立的、工业标准的应用协议,通过IP协议提供访问控制和维护分布式信息的目录信息。Spring Boot为任何兼容的LDAP服务器提供自动配置,同时也支持[UnboundID](https://www.ldap.com/unboundid-ldap-sdk-for-java) 的嵌入式内存中LDAP服务器。 -[Spring Data LDAP](https://github.com/spring-projects/spring-data-ldap)提供了LDAP抽象. `spring-boot-starter-data-ldap`”Starter“方便地集合了依赖。 \ No newline at end of file +[Spring Data LDAP](https://github.com/spring-projects/spring-data-ldap)提供了LDAP抽象。`spring-boot-starter-data-ldap`”Starter“方便地集合了依赖。 diff --git a/IV. Spring Boot features/30.9.1 Connecting to an LDAP Server.md b/IV. Spring Boot features/30.9.1 Connecting to an LDAP Server.md new file mode 100644 index 00000000..54e6a39f --- /dev/null +++ b/IV. Spring Boot features/30.9.1 Connecting to an LDAP Server.md @@ -0,0 +1,11 @@ +### 30.9.1 连接LDAP服务器 + +为了连接LDAP服务器,你需要确保声明了`spring-boot-starter-data-ldap`“Starter”或者`spring-ldap-core`依赖,然后在你的`application.properties`中声明你的服务器的URL。如下所示: + +```properties +spring.ldap.urls=ldap://myserver:1235 +spring.ldap.username=admin +spring.ldap.password=secret +``` + +如果你需要自定义连接设置,你可以使用`spring.ldap.base`或者`spring.ldap.base-environment`属性。 diff --git a/IV. Spring Boot features/30.9.1 Connecting to an LDAP server.md b/IV. Spring Boot features/30.9.1 Connecting to an LDAP server.md deleted file mode 100644 index 290b0a85..00000000 --- a/IV. Spring Boot features/30.9.1 Connecting to an LDAP server.md +++ /dev/null @@ -1,9 +0,0 @@ -### 30.9.1 连接LDAP服务器 - -为了连接LDAP服务器,你需要确保声明了`spring-boot-starter-data-ldap`“Starter”或者`spring-ldap-core`依赖,然后在你的`application.properties`中声明你的服务器的URLs。 -```properties -spring.ldap.urls=ldap://myserver:1235 -spring.ldap.username=admin -spring.ldap.password=secret -``` -如果你需要自定义连接设置,你可以使用`spring.ldap.base`或者`spring.ldap.base-environment`属性。 \ No newline at end of file diff --git a/IV. Spring Boot features/30.9.2 Spring Data LDAP Repositories.md b/IV. Spring Boot features/30.9.2 Spring Data LDAP Repositories.md new file mode 100644 index 00000000..9633f606 --- /dev/null +++ b/IV. Spring Boot features/30.9.2 Spring Data LDAP Repositories.md @@ -0,0 +1,21 @@ +### 30.9.2 Spring Data LDAP仓库 + +Spring Data包含了支持LDAP的仓库。Spring Data LDAP的详细情况,请查看他们的[参考文档](https://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/)。 + +你也可以像其它Spring Bean一样,注入一个自动配置的`LdapTemplate`实例。 + +```java +@Component +public class MyBean { + + private final LdapTemplate template; + + @Autowired + public MyBean(LdapTemplate template) { + this.template = template; + } + + // ... + +} +``` diff --git a/IV. Spring Boot features/30.9.2 Spring Data LDAP repositories.md b/IV. Spring Boot features/30.9.2 Spring Data LDAP repositories.md deleted file mode 100644 index fdab9521..00000000 --- a/IV. Spring Boot features/30.9.2 Spring Data LDAP repositories.md +++ /dev/null @@ -1,19 +0,0 @@ -### 30.9.2 Spring Data LDAP仓库 - -Spring Data包含了支持LDAP的仓库。Spring Data LDAP的详细情况,请查看他们的[参考文档](http://docs.spring.io/spring-data/ldap/docs/1.0.x/reference/html/)。 -你也可以像其它Spring Bean一样,注入一个自动配置的`LdapTemplate`实例。 -```java -@Component -public class MyBean { - - private final LdapTemplate template; - - @Autowired - public MyBean(LdapTemplate template) { - this.template = template; - } - - // ... - -} -``` \ No newline at end of file diff --git a/IV. Spring Boot features/30.9.3 Embedded In-memory LDAP Server.md b/IV. Spring Boot features/30.9.3 Embedded In-memory LDAP Server.md new file mode 100644 index 00000000..604e5d18 --- /dev/null +++ b/IV. Spring Boot features/30.9.3 Embedded In-memory LDAP Server.md @@ -0,0 +1,27 @@ +### 30.9.3 嵌入式内存中LDAP服务器 + +为了方便测试,Spring Boot支持[UnboundID](https://www.ldap.com/unboundid-ldap-sdk-for-java) 的嵌入式内存中LDAP服务器的自动配置。在`com.unboundid:unboundid-ldapsdk`里添加依赖,声明`base-dn`属性,来配置服务器: + +```properties +spring.ldap.embedded.base-dn=dc=spring,dc=io +``` + +**注** 定义多个base-dn的值是可行的。但是,识别名称通常包含逗号。它们必须使用正确的符号定义。 + +在yaml文件里,你可以使用yaml列表符号: +```properties +spring.ldap.embedded.base-dn: + - dc=spring,dc=io + - dc=pivotal,dc=io + ``` + +在properties文件里,你必须把索引作为属性名的一部分: +```properties +spring.ldap.embedded.base-dn[0]=dc=spring,dc=io +spring.ldap.embedded.base-dn[1]=dc=pivotal,dc=io +``` + +默认地,服务器会在一个随机的端口中开始运行。它们会触发常规的LDAP支持(不需要指定`spring.ldap.urls`属性)。 +如果在你的类路径下存在`schema.ldif`文件,它会被用于初始化服务器。如果你想要从不同的资源加载初始化脚本,你可以使用`pring.ldap.embedded.ldif`属性。 + +默认地,一个标准的模式会被用于验证`LDIF`文件,你可以设置`spring.ldap.embedded.validation.enabled`属性完全地关闭验证。如果你有自定义的属性,你可以使用`spring.ldap.embedded.validation.schema`来定义你的自定义属性类型或对象类。 diff --git a/IV. Spring Boot features/30.9.3 Embedded in-memory LDAP server.md b/IV. Spring Boot features/30.9.3 Embedded in-memory LDAP server.md deleted file mode 100644 index bc455274..00000000 --- a/IV. Spring Boot features/30.9.3 Embedded in-memory LDAP server.md +++ /dev/null @@ -1,9 +0,0 @@ -### 30.9.3 嵌入式内存中LDAP服务器 - -为了方便测试,Spring Boot支持[UnboundID](https://www.ldap.com/unboundid-ldap-sdk-for-java) 的嵌入式内存中LDAP服务器的自动配置。在`com.unboundid:unboundid-ldapsdk`里添加依赖,声明`base-dn`属性,来配置服务器: -```properties -spring.ldap.embedded.base-dn=dc=spring,dc=io -``` -默认地,服务器会在一个随机的端口中开始运行。它们会触发常规的LDAP支持(不需要指定`spring.ldap.urls`属性)。 -如果在你的类路径下存在`schema.ldif`文件,它会被用于初始化服务器。如果你想要从不同的资源加载初始化脚本,你可以使用`pring.ldap.embedded.ldif`属性。 -默认地,一个标准的模式会被用于验证`LDIF`文件,你可以使用`spring.ldap.embedded.validation.enabled`属性完全地关闭验证。如果你有自定义的属性,你可以使用`spring.ldap.embedded.validation.schema`来定义你的自定义属性类型或对象类。 \ No newline at end of file diff --git a/IV. Spring Boot features/31. Caching.md b/IV. Spring Boot features/31. Caching.md index 2dd1294e..394194cc 100644 --- a/IV. Spring Boot features/31. Caching.md +++ b/IV. Spring Boot features/31. Caching.md @@ -1,10 +1,10 @@ ### 31. 缓存 -Spring框架提供为应用透明添加缓存的支持,核心思想是,将抽象应用到缓存方法,基于缓存中可用信息减少方法的执行。缓存逻辑的应用是透明的,不会干扰调用者。只要通过`@EnableCaching`注解开启缓存支持,Spring Boot就会自动配置缓存基础结构。 +Spring框架提供为应用透明添加缓存的支持。其核心思想是:将抽象应用到缓存方法,基于缓存中可用信息减少方法的执行。缓存逻辑的应用是透明的,不会干扰调用者。只要通过`@EnableCaching`注解开启缓存支持,Spring Boot就会自动配置缓存基础结构。 -**注** 具体参考Spring框架指南的[相应章节](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#cache)。 +**注** 具体参考Spring框架指南的[相应章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#cache)。 -简而言之,为服务的某个操作添加缓存跟为方法添加相应注解那样简单: +简而言之,为服务的某个操作添加缓存跟为方法添加相应注解那样简单。如下所示: ```java import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Component; @@ -23,8 +23,8 @@ public class MathService { **注** 你也可以透明地使用标准的JSR-107 (JCache)注解(比如`@CacheResult`)。我们强烈建议你不要混淆使用。 -如果你不添加特定的缓存库,Spring Boot将会自动配置一个在内存中使用并发映射的[Simple提供商](../IV. Spring Boot features/31.1.10 Simple.md)。当需要缓存时(比如上面的例子里的`piDecimals`),提供商将会为你实时创建。不推荐你在产品环境中使用Simple提供商。但是它使得入门变得非常容易,确保了你理解特性。当你下定决心使用某个缓存提供商,请阅读这份文档理解如何配置缓存。实际上所有的提供商,都要求你明确地配置你在应用中使用的每一处缓存。有些提供了方法,通过`spring.cache.cache-names`来自定义默认的缓存。 +如果你不添加特定的缓存库,Spring Boot将会自动配置一个在内存中使用并发映射的[Simple提供商](../IV. Spring Boot features/31.1.9 Simple.md)。当需要缓存时(比如上面的例子里的`piDecimals`),提供商将会为你实时创建。不推荐你在产品环境中使用Simple提供商。但是它使得入门变得非常容易,确保了你理解特性。当你下定决心使用某个缓存提供商,请阅读这份文档理解如何配置缓存。实际上所有的提供商,都要求你明确地配置你在应用中使用的每一处缓存。有些提供了方法,通过`spring.cache.cache-names`来自定义默认的缓存。 -**提示** 透明地[更新](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#cache-annotations-put)或[去除](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#cache-annotations-evict)缓存数据也是可以的。 +**提示** 透明地[更新](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#cache-annotations-put)或[去除](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#cache-annotations-evict)缓存数据也是可以的。 **注** 如果你正在使用的缓存基础结构beans不是基于接口的,确保启用了`@EnableCaching`的`proxyTargetClass`属性。 diff --git a/IV. Spring Boot features/31.1 Supported Cache Providers.md b/IV. Spring Boot features/31.1 Supported Cache Providers.md new file mode 100644 index 00000000..fa9fcb13 --- /dev/null +++ b/IV. Spring Boot features/31.1 Supported Cache Providers.md @@ -0,0 +1,33 @@ +### 31.1 支持的缓存提供商 + +缓存抽象不提供实际的存储,而是依赖于`org.springframework.cache.Cache`和`org.springframework.cache.CacheManager`接口的实现。 + +如果你还没有定义一个`CacheManager`类型的bean,或一个名为`cacheResolver`的`CacheResolver`(查看`CachingConfigurer`),Spring Boot将尝试以下提供商(按这个顺序): + + 1. [Generic](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-generic) + 2. [JCache (JSR-107)](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-jcache)(EhCache 3, Hazelcast, Infinispan, etc) + 3. [EhCache 2.x](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-ehcache2) + 4. [Hazelcast](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-hazelcast) + 5. [Infinispan](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-infinispan) + 6. [Couchbase](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-couchbase) + 7. [Redis](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-redis) + 8. [Caffeine](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-caffeine) + 9. [Simple](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-simple) + + **提示** `spring.cache.type`属性可强制指定使用的缓存提供商,如果需要在一些环境(比如,测试)中[禁用全部缓存](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-none)也可以使用该属性。 + + **提示** 使用`spring-boot-starter-cache`“Starter”来快速添加基础的缓存依赖。“Starter”带来了`spring-context-support`:如果你手动添加依赖,为了使用JCache、EhCache2.x或者Guava的支持,你必须添加`spring-context-support`。 + + 如果`CacheManager`是Spring Boot自动配置的,你可以在它完全初始化前,通过实现`CacheManagerCustomizer`接口进一步配置,以下设置标志表明空值应当传递给底层映射: + ```java +@Bean +public CacheManagerCustomizer cacheManagerCustomizer() { + return new CacheManagerCustomizer() { + @Override + public void customize(ConcurrentMapCacheManager cacheManager) { + cacheManager.setAllowNullValues(false); + } + }; +} + ``` + **注** 在以上示例中,希望得到一个自动配置好的`ConcurrentMapCacheManager`。如果没有配置(要么你提供你自己的配置,要么一个不同的缓存提供商被自动配置),则自定义器(customizer)将不会被调用。自定义器你添加多少都可以,并可以使用`@Order`或`Ordered`对它们进行排序。 diff --git a/IV. Spring Boot features/31.1 Supported cache providers.md b/IV. Spring Boot features/31.1 Supported cache providers.md deleted file mode 100644 index 9c56d981..00000000 --- a/IV. Spring Boot features/31.1 Supported cache providers.md +++ /dev/null @@ -1,33 +0,0 @@ -### 31.1 支持的缓存提供商 - -缓存抽象不提供实际的存储,而是依赖于`org.springframework.cache.Cache`和`org.springframework.cache.CacheManager`接口的实现。 - -如果你还没有定义一个`CacheManager`类型的bean,或一个名为`cacheResolver`的`CacheResolver`(查看`CachingConfigurer`),Spring Boot将尝试以下提供商(按这个顺序): - - * [Generic](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-generic) - * [JCache (JSR-107)](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-jcache)(EhCache 3, Hazelcast, Infinispan, etc) - * [EhCache 2.x](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-ehcache2) - * [Hazelcast](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-hazelcast) - * [Infinispan](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-infinispan) - * [Couchbase](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-couchbase) - * [Redis](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-redis) - * [Caffeine](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-caffeine) - * [Simple](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-simple) - - **提示** `spring.cache.type`属性可强制指定使用的缓存提供商,如果需要在一些环境(比如,测试)中[禁用全部缓存](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-caching-provider-none)也可以使用该属性。 - - **提示** 使用`spring-boot-starter-cache`“Starter”来快速添加基础的缓存依赖。“Starter”带来了`spring-context-support`:如果你手动添加依赖,为了使用JCache、EhCache2.x或者Guava的支持,你必须添加`spring-context-support`。 - - 如果`CacheManager`是Spring Boot自动配置的,你可以在它完全初始化前,通过实现`CacheManagerCustomizer`接口进一步配置,以下设置标志表明空值应当传递给底层映射: - ```java -@Bean -public CacheManagerCustomizer cacheManagerCustomizer() { - return new CacheManagerCustomizer() { - @Override - public void customize(ConcurrentMapCacheManager cacheManager) { - cacheManager.setAllowNullValues(false); - } - }; -} - ``` - **注** 在以上示例中,希望得到一个自动配置好的`ConcurrentMapCacheManager`。如果没有配置(要么你提供你自己的配置,要么一个不同的缓存提供商被自动配置),则自定义器(customizer)将不会被调用。自定义器你添加多少都可以,并可以使用`@Order`或`Ordered`对它们进行排序。 diff --git a/IV. Spring Boot features/31.1.10 None.md b/IV. Spring Boot features/31.1.10 None.md index 4cc85f81..b4bf552a 100644 --- a/IV. Spring Boot features/31.1.10 None.md +++ b/IV. Spring Boot features/31.1.10 None.md @@ -1,6 +1,7 @@ ### 31.1.10 None -如果配置类中出现`@EnableCaching`,一个合适的缓存配置也同样被期待。如果在某些环境需要禁用全部缓存,强制将缓存类型设为`none`将会使用一个no-op实现(没有任何实现的实现): +如果配置类中出现`@EnableCaching`,一个合适的缓存配置也同样被期待。如果在某些环境需要禁用全部缓存,强制将缓存类型设为`none`将会使用一个no-op实现(没有任何实现的实现),如下所示: + ```properties spring.cache.type=none ``` diff --git "a/IV. Spring Boot features/31.1.2 JCache\357\274\210JSR-107\357\274\211.md" "b/IV. Spring Boot features/31.1.2 JCache\357\274\210JSR-107\357\274\211.md" index abca3fe1..4b72d9fb 100644 --- "a/IV. Spring Boot features/31.1.2 JCache\357\274\210JSR-107\357\274\211.md" +++ "b/IV. Spring Boot features/31.1.2 JCache\357\274\210JSR-107\357\274\211.md" @@ -1,6 +1,6 @@ ### 31.1.2 JCache (JSR-107) -classpath下存在`javax.cache.spi.CachingProvider`(比如,一个遵循JSR-107的缓存library),并且`spring-boot-starter-cache`“Starter”提供了`JCacheCacheManager`,则JCache将启动。这里有很多遵循JSR-107的libraries,Spring Boot为Ehcache 3, Hazelcast和Infinispan提供依赖管理,其他library也可以像这样添加。 +类路径下存在`javax.cache.spi.CachingProvider`(也就是,类路径下存在一个遵循JSR-107的缓存库),并且`spring-boot-starter-cache`“Starter”提供了`JCacheCacheManager`,则[JCache](https://jcp.org/en/jsr/detail?id=107)将启动。这里有很多遵循JSR-107的库,Spring Boot为Ehcache 3、Hazelcast和Infinispan提供依赖管理。也可以添加其他库。 如果出现多个提供商,你需要明确指定使用哪个(提供商)。尽管JSR-107标准没有强制定义配置文件的位置,Spring Boot会尽量配合各实现情况: ```properties @@ -8,9 +8,10 @@ classpath下存在`javax.cache.spi.CachingProvider`(比如,一个遵循JSR-1 spring.cache.jcache.provider=com.acme.MyCachingProvider spring.cache.jcache.config=classpath:acme.xml ``` + **注** 由于一个缓存library可能提供的既有native实现,也有JSR-107支持,Spring Boot将优先使用JSR-107支持,这样如果你切换到不同的JSR-107实现,相同特性依旧可以使用。 -**提示** Spring Boot对Hazelcast有[广泛支持](../IV. Spring Boot features/37. Hazelcast.md)。如果单个的`HazelcastInstance`可用,它就会被`CacheManager`重复使用,除非指定了`spring.cache.jcache.config`属性。 +**提示** Spring Boot对Hazelcast有[广泛支持](../IV. Spring Boot features/38. Hazelcast.md)。如果单个的`HazelcastInstance`可用,它就会被`CacheManager`重复使用,除非指定了`spring.cache.jcache.config`属性。 以下方式可以自定义底层的`javax.cache.cacheManager`: diff --git a/IV. Spring Boot features/31.1.3 EhCache 2.x.md b/IV. Spring Boot features/31.1.3 EhCache 2.x.md index d370a78c..9913fd85 100644 --- a/IV. Spring Boot features/31.1.3 EhCache 2.x.md +++ b/IV. Spring Boot features/31.1.3 EhCache 2.x.md @@ -1,6 +1,7 @@ ### 31.1.3 EhCache 2.x -如果在classpath下的根目录可以找到一个名为`ehcache.xml`的文件,则缓存将使用EhCache 2.x。如果EhCache 2.x(由`spring-boot-starter-cache`”Starter“提供的`EhCacheCacheManager`)和这样的文件出现,那它们将用于启动缓存管理器,使用以下配置也可以提供替换的配置文件: +如果类路径下存在一个名为`ehcache.xml`的文件,则缓存将使用[EhCache](http://www.ehcache.org/) 2.x。如果存在EhCache 2.x,由`spring-boot-starter-cache`“Starter”提供的`EhCacheCacheManager`将用于启动缓存管理器。也可以提供一个替代的配置文件,如下所示: + ```properties spring.cache.ehcache.config=classpath:config/another-config.xml ``` diff --git a/IV. Spring Boot features/31.1.4 Hazelcast.md b/IV. Spring Boot features/31.1.4 Hazelcast.md index a57dd022..51f1b084 100644 --- a/IV. Spring Boot features/31.1.4 Hazelcast.md +++ b/IV. Spring Boot features/31.1.4 Hazelcast.md @@ -1,3 +1,3 @@ ### 31.1.4 Hazelcast -Spring Boot为Hazelcast提供[通常的支持](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-hazelcast),如果`HazelcastInstance`被自动配置,那它将自动包装进一个`CacheManager`。 +Spring Boot为Hazelcast提供[通常的支持](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-hazelcast)。如果`HazelcastInstance`被自动配置,那它将自动包装进一个`CacheManager`。 diff --git a/IV. Spring Boot features/31.1.5 Infinispan.md b/IV. Spring Boot features/31.1.5 Infinispan.md index 98038dfa..34b36b0a 100644 --- a/IV. Spring Boot features/31.1.5 Infinispan.md +++ b/IV. Spring Boot features/31.1.5 Infinispan.md @@ -1,9 +1,10 @@ ### 31.1.5 Infinispan -Infinispan没有默认的配置文件位置,所以需要显式指定: +Infinispan没有默认的配置文件位置,所以必须显式指定。否则,会使用默认的启动。 ```properties spring.cache.infinispan.config=infinispan.xml ``` -通过设置`spring.cache.cache-names`属性可以让缓存在启动时就被创建,如果定义了`ConfigurationBuilder` bean,它将用来定义该实例。 -**提示** Spring Boot对Infinispan的嵌入模式的支持受限,而且相当基础。如果你需要更多的选择项,你应当使用官方的Infinispan Spring Boot starter,查看[文档](https://github.com/infinispan/infinispan-spring-boot)获取更多详细情况。 +通过设置`spring.cache.cache-names`属性可以让缓存在启动时就被创建。如果定义了自定义的`ConfigurationBuilder` bean,它将用来自定义缓存。 + +**提示** Spring Boot对Infinispan的嵌入模式的支持受限,而且相当基础。如果你需要更多的选择项,你应当使用官方的Infinispan Spring Boot starter。查看[文档](https://github.com/infinispan/infinispan-spring-boot)获取更多详细情况。 diff --git a/IV. Spring Boot features/31.1.6 Couchbase.md b/IV. Spring Boot features/31.1.6 Couchbase.md index 942a7c64..7eee3956 100644 --- a/IV. Spring Boot features/31.1.6 Couchbase.md +++ b/IV. Spring Boot features/31.1.6 Couchbase.md @@ -1,10 +1,12 @@ ### 31.1.6 Couchbase -如果Couchbase Java客户端和`couchbase-spring-cache`实现可用,并且已经配置好了,`CouchbaseCacheManager`将会自动配置,使用`spring.cache.cache-names`属性可以在启动时创建其他缓存。对`Bucket`的操作也是自动配置的,你可以使用customizer在另一个`Bucket`上创建其他缓存:假设你需要在“main” `Bucket`上存放两个缓存(`foo`和`bar`),在另一个`Bucket`上存放一个存活时间为2秒的`biz`缓存。首先,你通过配置创建两个缓存: +如果[Couchbase](https://www.couchbase.com/) Java客户端和`couchbase-spring-cache`实现可用,并且已经配置好了,`CouchbaseCacheManager`将会自动配置,使用`spring.cache.cache-names`属性可以在启动时创建其他缓存。对`Bucket`的操作也是自动配置的,你可以使用customizer在另一个`Bucket`上创建其他缓存:假设你需要在“main” `Bucket`上存放两个缓存(`cache1`和`cache2`),在另一个`Bucket`上存放一个存活时间为2秒的`cache3`缓存。首先,你通过配置创建两个缓存: + ```properties -spring.cache.cache-names=foo,bar +spring.cache.cache-names=cache1,cache2 ``` -然后定义其他`@Configuration`来配置另一个`Bucket`和`biz`缓存: + +然后定义其他`@Configuration`来配置另一个`Bucket`和`cache3`缓存: ```java @Configuration public class CouchbaseCacheConfiguration { @@ -23,7 +25,7 @@ public class CouchbaseCacheConfiguration { @Bean public CacheManagerCustomizer cacheManagerCustomizer() { return c -> { - c.prepareCache("biz", CacheBuilder.newInstance(anotherBucket()) + c.prepareCache("cache3", CacheBuilder.newInstance(anotherBucket()) .withExpiration(2)); }; } diff --git a/IV. Spring Boot features/31.1.7 Redis.md b/IV. Spring Boot features/31.1.7 Redis.md index ad90dc6d..47d9d18e 100644 --- a/IV. Spring Boot features/31.1.7 Redis.md +++ b/IV. Spring Boot features/31.1.7 Redis.md @@ -1,5 +1,13 @@ ### 31.1.7 Redis -如果Redis可用,并配置好了,`RedisCacheManager`将被自动配置,使用`spring.cache.cache-names`可以在启动时创建其他缓存。 +如果[Redis](http://redis.io/)可用,并配置好了,`RedisCacheManager`将被自动配置。设置`spring.cache.cache-names`属性可以在启动时创建额外的缓存。使用`spring.cache.redis.*`属性可以配置缓存的默认值。比如,下面的配置会创建缓存`cache1`和`cache2`。它们的存活时间为10分钟。 + +```properties +spring.cache.cache-names=cache1,cache2 +spring.cache.redis.time-to-live=600000 +``` **注** 默认会添加key前缀以防止两个单独的缓存使用相同的key,否则Redis将存在重复的key,有可能返回不可用的值。如果创建自己的`RedisCacheManager`,强烈建议你保留该配置处于启用状态。 + + +**注** 你可以添加自己的`RedisCacheConfiguration` `@Bean`,完全掌控配置。如果你正在寻找自定义序列化策略,这会很有用。 diff --git a/IV. Spring Boot features/31.1.8 Caffeine.md b/IV. Spring Boot features/31.1.8 Caffeine.md index d4df468d..595e7ee0 100644 --- a/IV. Spring Boot features/31.1.8 Caffeine.md +++ b/IV. Spring Boot features/31.1.8 Caffeine.md @@ -1,14 +1,15 @@ ### 31.1.8 Caffeine -Caffeine是Java8对Guava缓存的重写版本,取代了Guava。如果出现Caffeine,`CaffeineCacheManager`(由`spring-boot-starter-cache` Starter提供)将会自动配置。使用`spring.cache.cache-names`属性可以在启动时创建缓存,并可以通过以下配置进行自定义(按顺序): +[Caffeine](https://github.com/ben-manes/caffeine)是Java 8对Guava缓存的重写版本,取代了Guava。如果出现Caffeine,`CaffeineCacheManager`(由`spring-boot-starter-cache` Starter提供)将会自动配置。使用`spring.cache.cache-names`属性可以在启动时创建缓存,并可以通过以下配置中的一个进行自定义(按指示的顺序): 1. `spring.cache.caffeine.spec`定义的特殊缓存 2. `com.github.benmanes.caffeine.cache.CaffeineSpec` bean定义 3. `com.github.benmanes.caffeine.cache.Caffeine` bean定义 -例如,以下配置创建一个`foo`和`bar`缓存,最大数量为500,存活时间为10分钟: +例如,以下配置创建一个`cache1 `和`cache2`缓存,最大数量为500,存活时间为10分钟: ```properties -spring.cache.cache-names=foo,bar +spring.cache.cache-names=cache1,cache2 spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s ``` -除此之外,如果定义了`com.github.benmanes.caffeine.cache.CacheLoader`,它会自动关联到`CaffeineCacheManager`。由于该`CacheLoader`将关联被该缓存管理器管理的所有缓存,所以它必须定义为`CacheLoader`,自动配置将忽略所有泛型类型。 + +除此之外,如果定义了`com.github.benmanes.caffeine.cache.CacheLoader`,它会自动关联到`CaffeineCacheManager`。由于该`CacheLoader`将关联被该缓存管理器管理的所有缓存,所以它必须定义为`CacheLoader`。自动配置将忽略所有泛型类型。 diff --git a/IV. Spring Boot features/31.1.9 Simple.md b/IV. Spring Boot features/31.1.9 Simple.md index cddae53b..bb3cd064 100644 --- a/IV. Spring Boot features/31.1.9 Simple.md +++ b/IV. Spring Boot features/31.1.9 Simple.md @@ -1,7 +1,8 @@ ### 31.1.9 Simple -如果找不到其它提供商,一个使用`ConcurrentHashMap`作为缓存存储的简单实现将被配置,这是应用没有添加缓存library的默认设置。默认地,缓存在运行中被创建。但是你可以通过使用`cache-names`属性来限制可用的缓存。例如,如果你只想要`foo`和`bar`缓存: +如果找不到其它提供商,一个使用`ConcurrentHashMap`作为缓存存储的简单实现将被配置。这是应用没有添加缓存库的默认设置。默认地,缓存按需被创建。但是你可以通过设置`cache-names`属性来限制可用的缓存。例如,如果你只想要`cache1`和`cache2`缓存,如下设置`cache-names`属性: ```properties -spring.cache.cache-names=foo,bar +spring.cache.cache-names=cache1,cache2 ``` -如果你这样做了,而你的应用使用了一个没有列举在以上列表中的缓存,那么当需要此缓存时,获取缓存的操作会在运行时失败,而不是在启动时。这和实际的缓存提供商的行为相似,如果你使用了一个没有声明的缓存。 \ No newline at end of file + +如果你这样做了,而你的应用使用了一个没有列举在以上列表中的缓存,那么当需要此缓存时,获取缓存的操作会在运行时失败,而不是在启动时。这和实际的缓存提供商的行为相似,如果你使用了一个没有声明的缓存。 diff --git a/IV. Spring Boot features/32. Messaging.md b/IV. Spring Boot features/32. Messaging.md index 2e5a0330..0d649174 100644 --- a/IV. Spring Boot features/32. Messaging.md +++ b/IV. Spring Boot features/32. Messaging.md @@ -1,3 +1,3 @@ ### 32. 消息 -Spring Framework框架为集成消息系统提供了扩展(extensive)支持:从使用`JmsTemplate`简化JMS API,到实现一个能够异步接收消息的完整的底层设施。Spring AMQP提供一个相似的用于'高级消息队列协议'的特征集,并且Spring Boot也为`RabbitTemplate`和RabbitMQ提供了自动配置选项。Spring Websocket提供原生的STOMP消息支持,并且Spring Boot也提供了starters和自动配置支持。Spring Boot也提供了对Apache Kafka的支持。 +Spring框架为集成消息系统提供了扩展支持:从使用`JmsTemplate`简化JMS API,到实现一个能够异步接收消息的完整的底层设施。Spring AMQP提供一个相似的用于“高级消息队列协议”的特征集。并且,Spring Boot也为`RabbitTemplate`和RabbitMQ提供了自动配置选项。Spring Websocket提供原生的STOMP消息支持,并且Spring Boot也提供了starters和自动配置支持。Spring Boot也提供了对Apache Kafka的支持。 diff --git a/IV. Spring Boot features/32.1. JMS.md b/IV. Spring Boot features/32.1. JMS.md index d25d2bd0..bdc45a0e 100644 --- a/IV. Spring Boot features/32.1. JMS.md +++ b/IV. Spring Boot features/32.1. JMS.md @@ -1,4 +1,4 @@ ### 32.1. JMS `javax.jms.ConnectionFactory`接口提供标准的用于创建`javax.jms.Connection`的方法,`javax.jms.Connection`用于和JMS代理(broker)交互。 -尽管Spring需要一个`ConnectionFactory`才能使用JMS,通常你不需要直接使用它,而是依赖于上层消息抽象(具体参考Spring框架的[相关章节](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#jms)),Spring Boot会自动配置发送和接收消息需要的设施(infrastructure)。 +尽管Spring需要一个`ConnectionFactory`才能使用JMS,通常你不需要直接使用它,而是依赖于上层消息抽象(具体参考Spring框架的[相关章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#jms)),Spring Boot会自动配置发送和接收消息需要的设施(infrastructure)。 diff --git a/IV. Spring Boot features/32.1.1 ActiveMQ Support.md b/IV. Spring Boot features/32.1.1 ActiveMQ Support.md new file mode 100644 index 00000000..d45ee93f --- /dev/null +++ b/IV. Spring Boot features/32.1.1 ActiveMQ Support.md @@ -0,0 +1,20 @@ +### 32.1.1 ActiveQ支持 + +如果ActiveMQ在类路径下,Spring Boot会配置一个`ConnectionFactory`。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(只要配置中没有指定代理URL)。 + +ActiveMQ是通过`spring.activemq.*`外部配置来控制的,例如,你可能在`application.properties`中声明以下片段: +```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`。如下所示: +```properties +spring.activemq.pool.enabled=true +spring.activemq.pool.max-connections=50 +``` + +具体参考[ActiveMQProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java)。你也可以注册任意数量的实现`ActiveMQConnectionFactoryCustomizer`的bean,来实现更多高级的自定义。 + +默认情况下,如果目标不存在,ActiveMQ将创建一个,所以目标是通过它们提供的名称解析出来的。 diff --git a/IV. Spring Boot features/32.1.1 ActiveMQ support.md b/IV. Spring Boot features/32.1.1 ActiveMQ support.md deleted file mode 100644 index 5a648e82..00000000 --- a/IV. Spring Boot features/32.1.1 ActiveMQ support.md +++ /dev/null @@ -1,18 +0,0 @@ -### 32.1.1 ActiveQ支持 - -如果发现ActiveMQ在classpath下可用,Spring Boot会配置一个`ConnectionFactory`。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(只要配置中没有指定代理URL)。 - -ActiveMQ是通过`spring.activemq.*`外部配置来控制的,例如,你可能在`application.properties`中声明以下片段: -```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`: -```properties -spring.activemq.pool.enabled=true -spring.activemq.pool.max-connections=50 -``` -具体参考[ActiveMQProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java)。 - -默认情况下,如果目标不存在,ActiveMQ将创建一个,所以目标是通过它们提供的名称解析出来的。 diff --git a/IV. Spring Boot features/32.1.2 Artemis Support.md b/IV. Spring Boot features/32.1.2 Artemis Support.md new file mode 100644 index 00000000..41385f57 --- /dev/null +++ b/IV. Spring Boot features/32.1.2 Artemis Support.md @@ -0,0 +1,14 @@ +### 32.1.2 Artemis支持 + +如果发现classpath下存在[Artemis](http://activemq.apache.org/artemis/)依赖,Spring Boot将自动配置一个`ConnectionFactory`。如果需要broker,Spring Boot将启动内嵌的broker,并对其自动配置(除非模式mode属性被显式设置)。支持的modes包括:`embedded`(明确需要内嵌broker,如果classpath下不存在则出错),`native`(使用`netty`传输协议连接broker)。当配置`native`模式,Spring Boot将配置一个连接broker的`ConnectionFactory`,该broker使用默认的设置运行在本地机器。 +**注** 使用`spring-boot-starter-artemis` 'Starter',则连接已存在的Artemis实例及Spring设施集成JMS所需依赖都会提供,添加`org.apache.activemq:artemis-jms-server`依赖,你可以使用内嵌模式。 + +Artemis配置控制在外部配置属性`spring.artemis.*`中,例如,在`application.properties`声明以下片段: +```properties +spring.artemis.mode=native +spring.artemis.host=192.168.1.210 +spring.artemis.port=9876 +spring.artemis.user=admin +spring.artemis.password=secret +``` +当使用内嵌模式时,你可以选择是否启用持久化,及目的地列表。这些可以通过逗号分割的列表来指定,也可以分别定义`org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration`或`org.apache.activemq.artemis.jms.server.config.TopicConfiguration`类型的bean来进一步配置队列和topic。具体支持选项可参考[ArtemisProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisProperties.java)。 diff --git a/IV. Spring Boot features/32.1.2 Artemis support.md b/IV. Spring Boot features/32.1.2 Artemis support.md deleted file mode 100644 index f68b9cb5..00000000 --- a/IV. Spring Boot features/32.1.2 Artemis support.md +++ /dev/null @@ -1,14 +0,0 @@ -### 32.1.2 Artemis支持 - -如果发现classpath下存在Artemis依赖,Spring Boot将自动配置一个`ConnectionFactory`。如果需要broker,Spring Boot将启动内嵌的broker,并对其自动配置(除非模式mode属性被显式设置)。支持的modes包括:`embedded`(明确需要内嵌broker,如果classpath下不存在则出错),`native`(使用`netty`传输协议连接broker)。当配置`native`模式,Spring Boot将配置一个连接broker的`ConnectionFactory`,该broker使用默认的设置运行在本地机器。 -**注** 使用`spring-boot-starter-artemis` 'Starter',则连接已存在的Artemis实例及Spring设施集成JMS所需依赖都会提供,添加`org.apache.activemq:artemis-jms-server`依赖,你可以使用内嵌模式。 - -Artemis配置控制在外部配置属性`spring.artemis.*`中,例如,在`application.properties`声明以下片段: -```properties -spring.artemis.mode=native -spring.artemis.host=192.168.1.210 -spring.artemis.port=9876 -spring.artemis.user=admin -spring.artemis.password=secret -``` -当使用内嵌模式时,你可以选择是否启用持久化,及目的地列表。这些可以通过逗号分割的列表来指定,也可以分别定义`org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration`或`org.apache.activemq.artemis.jms.server.config.TopicConfiguration`类型的bean来进一步配置队列和topic,具体支持选项可参考[ArtemisProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisProperties.java)。 diff --git a/IV. Spring Boot features/32.1.4 Sending a Message.md b/IV. Spring Boot features/32.1.4 Sending a Message.md new file mode 100644 index 00000000..22a74a2a --- /dev/null +++ b/IV. Spring Boot features/32.1.4 Sending a Message.md @@ -0,0 +1,20 @@ +### 32.1.4 发送消息 + +Spring的`JmsTemplate`会被自动配置,你可以将它直接注入到自己的beans中: + +```java +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](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/jms/core/JmsMessagingTemplate.html)。如果定义了一个`DestinationResolver`或`MessageConverter` bean,它将自动关联到自动配置的`JmsTemplate`。 diff --git a/IV. Spring Boot features/32.1.4 Sending a message.md b/IV. Spring Boot features/32.1.4 Sending a message.md deleted file mode 100644 index f3636038..00000000 --- a/IV. Spring Boot features/32.1.4 Sending a message.md +++ /dev/null @@ -1,19 +0,0 @@ -### 32.1.4 发送消息 - -Spring的`JmsTemplate`会被自动配置,你可以将它直接注入到自己的beans中: -```java -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](https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/org/springframework/jms/core/JmsMessagingTemplate.html)。如果定义了`DestinationResolver`或`MessageConverter` beans,它们将自动关联到自动配置的`JmsTemplate`。 diff --git a/IV. Spring Boot features/32.1.5 Receiving a Message.md b/IV. Spring Boot features/32.1.5 Receiving a Message.md new file mode 100644 index 00000000..91f7aa77 --- /dev/null +++ b/IV. Spring Boot features/32.1.5 Receiving a Message.md @@ -0,0 +1,49 @@ +### 32.1.5 接收消息 + +当JMS基础设施能够使用时,任何bean都能够被`@JmsListener`注解,以创建一个监听者端点。如果没有定义`JmsListenerContainerFactory`,将自动配置一个默认的。如果定义了一个`DestinationResolver`或`MessageConverter` bean,它将自动关联该默认factory。 + +默认factory是事务性的,如果运行的设施出现`JtaTransactionManager`,它默认将关联到监听器容器。如果没有,`sessionTransacted`标记将启用。在后一场景中,你可以通过在监听器方法上添加`@Transactional`,以本地数据存储事务处理接收的消息,这可以确保接收的消息在本地事务完成后只确认一次。 + +下面的组件创建了一个以`someQueue`为目标的监听器端点: +```java +@Component +public class MyBean { +@JmsListener(destination = "someQueue") +public void processMessage(String content) { +// ... +} +} +``` +具体查看[@EnableJms javadoc](https://docs.spring.io/spring/docs/5.0.4.RELEASE/javadoc-api/org/springframework/jms/annotation/EnableJms.html)。 + +如果想创建多个`JmsListenerContainerFactory`实例或覆盖默认实例,你可以使用Spring Boot提供的`DefaultJmsListenerContainerFactoryConfigurer`,通过它可以使用跟自动配置的实例相同配置来初始化一个`DefaultJmsListenerContainerFactory`。 + +例如,以下使用一个特殊的`MessageConverter`创建另一个factory: +```java +@Configuration +static class JmsConfiguration { + + @Bean + public DefaultJmsListenerContainerFactory myFactory( + DefaultJmsListenerContainerFactoryConfigurer configurer) { + DefaultJmsListenerContainerFactory factory = + new DefaultJmsListenerContainerFactory(); + configurer.configure(factory, connectionFactory()); + factory.setMessageConverter(myMessageConverter()); + return factory; + } + +} +``` +然后,你可以像下面那样在任何`@JmsListener`注解中使用: +```java +@Component +public class MyBean { + + @JmsListener(destination = "someQueue", containerFactory="myFactory") + public void processMessage(String content) { + // ... + } + +} +``` diff --git a/IV. Spring Boot features/32.1.5 Receiving a message.md b/IV. Spring Boot features/32.1.5 Receiving a message.md deleted file mode 100644 index ada2f93a..00000000 --- a/IV. Spring Boot features/32.1.5 Receiving a message.md +++ /dev/null @@ -1,49 +0,0 @@ -### 32.1.5 接收消息 - -当JMS基础设施能够使用时,任何bean都能够被`@JmsListener`注解,以创建一个监听者端点。如果没有定义`JmsListenerContainerFactory`,将自动配置一个默认的。如果定义`DestinationResolver`或`MessageConverter` beans,它们将自动关联该默认factory。 - -默认factory是事务性的,如果运行的设施出现`JtaTransactionManager`,它默认将关联到监听器容器。如果没有,`sessionTransacted`标记将启用。在后一场景中,你可以通过在监听器方法上添加`@Transactional`,以本地数据存储事务处理接收的消息,这可以确保接收的消息在本地事务完成后只确认一次。 - -下面的组件创建了一个以`someQueue`为目标的监听器端点: -```java -@Component -public class MyBean { -@JmsListener(destination = "someQueue") -public void processMessage(String content) { -// ... -} -} -``` -具体查看[@EnableJms javadoc](https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/org/springframework/jms/annotation/EnableJms.html)。 - -如果想创建多个`JmsListenerContainerFactory`实例或覆盖默认实例,你可以使用Spring Boot提供的`DefaultJmsListenerContainerFactoryConfigurer`,通过它可以使用跟自动配置的实例相同配置来初始化一个`DefaultJmsListenerContainerFactory`。 - -例如,以下使用一个特殊的`MessageConverter`创建另一个factory: -```java -@Configuration -static class JmsConfiguration { - - @Bean - public DefaultJmsListenerContainerFactory myFactory( - DefaultJmsListenerContainerFactoryConfigurer configurer) { - DefaultJmsListenerContainerFactory factory = - new DefaultJmsListenerContainerFactory(); - configurer.configure(factory, connectionFactory()); - factory.setMessageConverter(myMessageConverter()); - return factory; - } - -} -``` -然后,你可以像下面那样在任何`@JmsListener`注解中使用: -```java -@Component -public class MyBean { - - @JmsListener(destination = "someQueue", containerFactory="myFactory") - public void processMessage(String content) { - // ... - } - -} -``` diff --git a/IV. Spring Boot features/32.2.1 RabbitMQ support.md b/IV. Spring Boot features/32.2.1 RabbitMQ support.md index ed44df27..6a70452c 100644 --- a/IV. Spring Boot features/32.2.1 RabbitMQ support.md +++ b/IV. Spring Boot features/32.2.1 RabbitMQ support.md @@ -1,9 +1,12 @@ -###32.2.1 RabbitMQ支持 -RabbitMQ是一个基于AMQP协议,轻量级的,可靠的,可扩展的和可移植的消息代理,Spring就使用它进行消息传递。RabbitMQ配置被外部属性`spring.rabbitmq.*`控制,例如,在`application.properties`中声明以下片段: +### 32.2.1 RabbitMQ支持 + +[RabbitMQ](https://www.rabbitmq.com/)是一个基于AMQP协议的、轻量级的、可靠的、可扩展的和可移植的消息代理。Spring使用它进行消息传递。RabbitMQ配置被外部属性`spring.rabbitmq.*`控制。例如,在`application.properties`中声明以下片段: ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=secret ``` -更多选项参考[RabbitProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitProperties.java)。 +更多选项参考[RabbitProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitProperties.java)。 + +**注** 更多细节,请查看[理解AMQP,RabbitMQ使用的协议](https://spring.io/blog/2010/06/14/understanding-amqp-the-protocol-used-by-rabbitmq/)。 diff --git a/IV. Spring Boot features/32.2.2 Sending a Message.md b/IV. Spring Boot features/32.2.2 Sending a Message.md new file mode 100644 index 00000000..d605da34 --- /dev/null +++ b/IV. Spring Boot features/32.2.2 Sending a Message.md @@ -0,0 +1,28 @@ +### 32.2.2 发送消息 + +Spring的`AmqpTemplate`和`AmqpAdmin`会被自动配置,你可以将它们直接注入beans中: +```java +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`](https://docs.spring.io/spring-amqp/docs/current/api/org/springframework/amqp/rabbit/core/RabbitMessagingTemplate.html),如果定义`MessageConverter` bean,它将自动关联到自动配置的`AmqpTemplate`。 + +如果需要的话,所有定义为bean的`org.springframework.amqp.core.Queue`将自动在RabbitMQ实例中声明相应的队列。你可以启用`AmqpTemplate`的重试选项,例如代理连接丢失时,重试默认不启用。 diff --git a/IV. Spring Boot features/32.2.2 Sending a message.md b/IV. Spring Boot features/32.2.2 Sending a message.md deleted file mode 100644 index dcdcc247..00000000 --- a/IV. Spring Boot features/32.2.2 Sending a message.md +++ /dev/null @@ -1,27 +0,0 @@ -###32.2.2 发送消息 -Spring的`AmqpTemplate`和`AmqpAdmin`会被自动配置,你可以将它们直接注入beans中: -```java -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`,如果定义`MessageConverter` bean,它将自动关联到自动配置的`AmqpTemplate`。 - -如果需要的话,所有定义为bean的`org.springframework.amqp.core.Queue`将自动在RabbitMQ实例中声明相应的队列。你可以启用`AmqpTemplate`的重试选项,例如代理连接丢失时,重试默认不启用。 diff --git a/IV. Spring Boot features/32.2.3 Receiving a Message.md b/IV. Spring Boot features/32.2.3 Receiving a Message.md new file mode 100644 index 00000000..23aa2cc7 --- /dev/null +++ b/IV. Spring Boot features/32.2.3 Receiving a Message.md @@ -0,0 +1,55 @@ +### 32.2.3 接收消息 + +当Rabbit设施出现时,所有bean都可以注解`@RabbitListener`来创建一个监听器端点。如果没有定义`RabbitListenerContainerFactory`,Spring Boot将自动配置一个默认的`SimpleRabbitListenerContainerFactory`。你可以使用`spring.rabbitmq.listener.type`属性,转换到一个直接的容器。如果定义`MessageConverter` 或者`MessageRecoverer` bean,它将自动关联到默认的factory。 + +下面的组件创建一个`someQueue`队列上的监听器端点: +```java +@Component +public class MyBean { + + @RabbitListener(queues = "someQueue") + public void processMessage(String content) { + // ... + } + +} +``` +**注** 具体参考[@EnableRabbit的Javadoc](https://docs.spring.io/spring-amqp/docs/current/api/org/springframework/amqp/rabbit/annotation/EnableRabbit.html)。 + +如果需要创建多个`RabbitListenerContainerFactory`实例,或想覆盖默认实例,你可以使用Spring Boot提供的`SimpleRabbitListenerContainerFactoryConfigurer`和`DirectRabbitListenerContainerFactoryConfigurer`,通过它们可以使用跟自动配置实例相同的配置初始化`SimpleRabbitListenerContainerFactory`。 + +**提示** 使用哪个容器无关紧要,自动配置将会暴露那两个bean。 + +例如,下面使用一个特殊的`MessageConverter`配置类创建了另一个factory: +```java +@Configuration +static class RabbitConfiguration { + + @Bean + public SimpleRabbitListenerContainerFactory myFactory( + SimpleRabbitListenerContainerFactoryConfigurer configurer) { + SimpleRabbitListenerContainerFactory factory = + new SimpleRabbitListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + factory.setMessageConverter(myMessageConverter()); + return factory; + } + +} + +``` +然后,你可以像下面那样在所有`@RabbitListener`注解方法中使用: +```java +@Component +public class MyBean { + + @RabbitListener(queues = "someQueue", containerFactory="myFactory") + public void processMessage(String content) { + // ... + } + +} +``` +你可以启动重试处理那些监听器抛出异常的情况。默认地,`RejectAndDontRequeueRecoverer`被使用,但是你可以定义一个你自己的`MessageRecoverer`。当重试次数达到限制时,该消息将被拒绝,要不被丢弃,要不路由到一个dead-letter交换器,如果broker这样配置的话,默认禁用重试。 + +**重要** 默认的,如果禁用了重试,且监听器抛出异常,则Rabbit会无限期地进行重试。你可以采用两种方式修改该行为:设置`defaultRequeueRejected`属性为`false`,这样就不会重试,或者抛出一个`AmqpRejectAndDontRequeueException`异常表示该消息应该被拒绝。后面这个是开启重试,且达到最大重试次数时使用的策略。 diff --git a/IV. Spring Boot features/32.2.3 Receiving a message.md b/IV. Spring Boot features/32.2.3 Receiving a message.md deleted file mode 100644 index 2a5bb290..00000000 --- a/IV. Spring Boot features/32.2.3 Receiving a message.md +++ /dev/null @@ -1,53 +0,0 @@ -###32.2.3 接收消息 -当Rabbit设施出现时,所有bean都可以注解`@RabbitListener`来创建一个监听器端点。如果没有定义`RabbitListenerContainerFactory`,Spring Boot将自动配置一个默认的`SimpleRabbitListenerContainerFactory`。你可以使用`spring.rabbitmq.listener.type`属性,转换到一个直接的容器。如果定义`MessageConverter` 或者`MessageRecoverer`beans,它们将自动关联到默认的factory。 - -下面的组件创建一个`someQueue`队列上的监听器端点: -```java -@Component -public class MyBean { - - @RabbitListener(queues = "someQueue") - public void processMessage(String content) { - // ... - } - -} -``` -**注** 具体参考[@EnableRabbit](http://docs.spring.io/spring-amqp/docs/current/api/org/springframework/amqp/rabbit/annotation/EnableRabbit.html)。 - -如果需要创建多个`RabbitListenerContainerFactory`实例,或想覆盖默认实例,你可以使用Spring Boot提供的`SimpleRabbitListenerContainerFactoryConfigurer`和`DirectRabbitListenerContainerFactoryConfigurer`,通过它们可以使用跟自动配置实例相同的配置初始化`SimpleRabbitListenerContainerFactory`。 - -**提示** 使用哪个容器无关紧要,自动配置将会暴露那两个bean。 - -例如,下面使用一个特殊的`MessageConverter`创建了另一个factory: -```java -@Configuration -static class RabbitConfiguration { - - @Bean - public SimpleRabbitListenerContainerFactory myFactory( - SimpleRabbitListenerContainerFactoryConfigurer configurer) { - SimpleRabbitListenerContainerFactory factory = - new SimpleRabbitListenerContainerFactory(); - configurer.configure(factory, connectionFactory); - factory.setMessageConverter(myMessageConverter()); - return factory; - } - -} -``` -然后,你可以像下面那样在所有`@RabbitListener`注解方法中使用: -```java -@Component -public class MyBean { - - @RabbitListener(queues = "someQueue", containerFactory="myFactory") - public void processMessage(String content) { - // ... - } - -} -``` -你可以启动重试处理那些监听器抛出异常的情况。默认地,`RejectAndDontRequeueRecoverer`被使用,但是你可以定义一个你自己的`MessageRecoverer`。当重试次数达到限制时,该消息将被拒绝,要不被丢弃,要不路由到一个dead-letter交换器,如果broker这样配置的话,默认禁用重试。 - -**重要** 如果没启用重试,且监听器抛出异常,则Rabbit会不定期进行重试。你可以采用两种方式修改该行为:设置`defaultRequeueRejected`属性为`false`,这样就不会重试;或抛出一个`AmqpRejectAndDontRequeueException`异常表示该消息应该被拒绝,这是开启重试,且达到最大重试次数时使用的策略。 diff --git a/IV. Spring Boot features/32.3 Apache Kafka Support.md b/IV. Spring Boot features/32.3 Apache Kafka Support.md index 81cdb2ca..dce75bc5 100644 --- a/IV. Spring Boot features/32.3 Apache Kafka Support.md +++ b/IV. Spring Boot features/32.3 Apache Kafka Support.md @@ -6,4 +6,4 @@ Kafka配置在外部的配置属性中,定义在`spring.kafka.*`。例如, spring.kafka.bootstrap-servers=localhost:9092 spring.kafka.consumer.group-id=myGroup ``` -更多支持的选项,请查看[`KafkaProperties`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java)。 +更多支持的选项,请查看[`KafkaProperties`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java)。 diff --git a/IV. Spring Boot features/32.3.1 Sending a Message.md b/IV. Spring Boot features/32.3.1 Sending a Message.md index 46765ed6..088dac55 100644 --- a/IV. Spring Boot features/32.3.1 Sending a Message.md +++ b/IV. Spring Boot features/32.3.1 Sending a Message.md @@ -1,6 +1,7 @@ ### 32.3.1 发送消息 -Spring的`KafkaTemplate`会自动配置。你可以直接在你自己的bean里面自动装配它们: +Spring的`KafkaTemplate`会自动配置。你可以直接在你自己的bean里面自动装配它。如下所示: + ```java @Component public class MyBean { @@ -16,3 +17,5 @@ public class MyBean { } ``` + +**注** 如果定义了`RecordMessageConverter` bean,它会自动关联到自动配置好的`KafkaTemplate`。 diff --git a/IV. Spring Boot features/32.3.2 Receiving a Message.md b/IV. Spring Boot features/32.3.2 Receiving a Message.md index 41ffe51a..c57396ff 100644 --- a/IV. Spring Boot features/32.3.2 Receiving a Message.md +++ b/IV. Spring Boot features/32.3.2 Receiving a Message.md @@ -1,6 +1,6 @@ ### 32.3.2 接收消息 -当完成Apache Kafka的基础配置,任何的bean都可以标注为`@KafkaListener`,来创建一个监听器端点。如果没有定义`KafkaListenerContainerFactory`,一个默认的将会用定义在`spring.kafka.listener.*`里的键值自动配置。 +当完成Apache Kafka的基础配置,任何的bean都可以标注为`@KafkaListener`,来创建一个监听器端点。如果没有定义`KafkaListenerContainerFactory`,一个默认的将会用定义在`spring.kafka.listener.*`里的键值自动配置。另外,如果定义了一个`RecordMessageConverter` bean,它会自动关联到默认的工厂。 下面的组件在`someTopic`主题上创建了一个监听器端点: ```java diff --git a/IV. Spring Boot features/32.3.3 Additional Kafka Properties.md b/IV. Spring Boot features/32.3.3 Additional Kafka Properties.md index a2e0fd92..f73279e3 100644 --- a/IV. Spring Boot features/32.3.3 Additional Kafka Properties.md +++ b/IV. Spring Boot features/32.3.3 Additional Kafka Properties.md @@ -6,40 +6,24 @@ 只有Kafka支持的属性的一个子集能够通过`KafkaProperties`类来定义。如果你希望用其它的不被直接支持的属性,来配置生产者或者消费者,使用下面的例子: ```properties -spring.kafka.properties.foo.bar=baz +spring.kafka.properties.prop.one=first +spring.kafka.admin.properties.prop.two=second +spring.kafka.consumer.properties.prop.three=third +spring,kafka.producer.properties.prop.four=fourth ``` -这把通常的`foo.bar`Kafka属性设置为`baz`。 +这把通常的`prop.one`Kafka属性设置为`first`(应用到producers、consumers和admins)。`prop.two`admin属性设置为`second`。`prop.three`consumer属性设置为`third`。`prop.four`producer属性设置为`fourth`。 -这些属性会被生产者和消费者的工厂bean共同分享。如果你想用不同的属性自定义这些组件,例如为了各种使用不同的度量读取器,你可以如下重写bean定义: -```java -@Configuration -public static class CustomKafkaBeans { - - /** - * Customized ProducerFactory bean. - * @param properties the kafka properties. - * @return the bean. - */ - @Bean - public ProducerFactory kafkaProducerFactory(KafkaProperties properties) { - Map producerProperties = properties.buildProducerProperties(); - producerProperties.put(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG, - MyProducerMetricsReporter.class); - return new DefaultKafkaProducerFactory<>(producerProperties); - } - - /** - * Customized ConsumerFactory bean. - * @param properties the kafka properties. - * @return the bean. - */ - @Bean - public ConsumerFactory kafkaConsumerFactory(KafkaProperties properties) { - Map consumerProperties = properties.buildConsumerProperties(); - consumerProperties.put(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG, - MyConsumerMetricsReporter.class); - return new DefaultKafkaConsumerFactory<>(consumerProperties); - } +你也可以如下配置Spring Kafka `JsonDeserializer`: +```properties +spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer +spring.kafka.consumer.properties.spring.json.value.default.type=org.foo.Invoice +spring.kafka.consumer.properties.spring.json.trusted.packages=org.foo,org.bar +``` -} +相似地,你可以禁用`JsonSerializer`的默认行为——在header里传递类型信息: +```properties +spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer +spring.kafka.producer.properties.spring.json.add.type.headers=false ``` + +**重要** 以此种方式定义的属性会覆盖任何Spring Boot明确支持的配置项。 diff --git a/IV. Spring Boot features/33. Calling REST Services with RestTemplate.md b/IV. Spring Boot features/33. Calling REST Services with RestTemplate.md new file mode 100644 index 00000000..b95590bc --- /dev/null +++ b/IV. Spring Boot features/33. Calling REST Services with RestTemplate.md @@ -0,0 +1,22 @@ +### 33. 使用RestTemplate调用REST服务 + +如果应用需要调用远程REST服务,你可以使用Spring框架的`RestTemplate`类。由于`RestTemplate`实例经常在使用前需要自定义,Spring Boot就没有提供任何自动配置的`RestTemplate` bean。不过,你可以通过自动配置的`RestTemplateBuilder`创建自己需要的`RestTemplate`实例。自动配置的`RestTemplateBuilder`会确保应用到`RestTemplate`实例的`HttpMessageConverters`是合适的。 + +以下是典型的示例: +```java +@Service +public class MyService { + + private final RestTemplate restTemplate; + + public MyBean(RestTemplateBuilder restTemplateBuilder) { + this.restTemplate = restTemplateBuilder.build(); + } + + public Details someRestCall(String name) { + return this.restTemplate.getForObject("/{name}/details", Details.class, name); + } + +} +``` +**注** `RestTemplateBuilder`包含很多有用的方法,可以用于快速配置一个`RestTemplate`。例如,你可以使用`builder.basicAuthorization("user", "password").build()`添加基本的认证支持(BASIC auth)。 diff --git a/IV. Spring Boot features/33. Calling REST services.md b/IV. Spring Boot features/33. Calling REST services.md deleted file mode 100644 index c972aed1..00000000 --- a/IV. Spring Boot features/33. Calling REST services.md +++ /dev/null @@ -1,21 +0,0 @@ -###33. 调用REST服务 -如果应用需要调用远程REST服务,你可以使用Spring框架的`RestTemplate`类。由于`RestTemplate`实例经常在使用前需要自定义,Spring Boot就没有提供任何自动配置的`RestTemplate` bean,不过你可以通过自动配置的`RestTemplateBuilder`创建自己需要的`RestTemplate`实例。自动配置的`RestTemplateBuilder`会确保应用到`RestTemplate`实例的`HttpMessageConverters`是合适的。 - -以下是典型的示例: -```java -@Service -public class MyBean { - - private final RestTemplate restTemplate; - - public MyBean(RestTemplateBuilder restTemplateBuilder) { - this.restTemplate = restTemplateBuilder.build(); - } - - public Details someRestCall(String name) { - return this.restTemplate.getForObject("/{name}/details", Details.class, name); - } - -} -``` -**注** `RestTemplateBuilder`包含很多有用的方法,可以用于快速配置一个`RestTemplate`。例如,你可以使用`builder.basicAuthorization("user", "password").build()`添加基本的认证支持(BASIC auth)。 diff --git a/IV. Spring Boot features/33.1 RestTemplate customization.md b/IV. Spring Boot features/33.1 RestTemplate Customization.md similarity index 100% rename from IV. Spring Boot features/33.1 RestTemplate customization.md rename to IV. Spring Boot features/33.1 RestTemplate Customization.md diff --git a/IV. Spring Boot features/34. Calling REST Services with WebClient.md b/IV. Spring Boot features/34. Calling REST Services with WebClient.md new file mode 100644 index 00000000..87b22ddf --- /dev/null +++ b/IV. Spring Boot features/34. Calling REST Services with WebClient.md @@ -0,0 +1,24 @@ +### 34. 使用WebClient调用REST服务 + +如果你的类路径上存在Spring WebFlux,你也可以选择使用`WebClient`调用REST服务。与`RestTemplate`相比,`WebClient`更有函数式的感觉,而且完全是响应式的。你可以使用`WebClient.create()`创建你自己的client实例。查看[与WebClient有关的章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#web-reactive-client)。 + +Spring Boot为你创建并预先配置了这样一个builder。比如,客户端HTTP编解码器会以与服务器端相同的方式被配置好(查看[WebFlux HTTP编解码器的自动配置](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-webflux-httpcodecs))。 + +以下是典型的示例: +```java +@Service +public class MyService { + + private final WebClient webClient; + + public MyBean(WebClient.Builder webClientBuilder) { + this.webClient = webClientBuilder.baseUrl("http://example.org/").build(); + } + + public Mono
someRestCall(String name) { + return this.webClient.get().url("http://github.com/%7Bname%7D/details%22,%20name) + .retrieve().bodyToMono(Details.class); + } + +} +``` diff --git a/IV. Spring Boot features/34. Validation.md b/IV. Spring Boot features/34. Validation.md deleted file mode 100644 index cfa17e9c..00000000 --- a/IV. Spring Boot features/34. Validation.md +++ /dev/null @@ -1,17 +0,0 @@ -### 34. 验证 - -只要在类路径上存在JSR-303实现(比如Hibernate validator),Bean Validation 1.1支持的方法验证特性就会自动启用。这允许bean方法的参数和/或者返回值,被标注为`javax.validation`约束。为了让这样的带标注的方法在搜索行内约束标注时被找到,拥有它们的目标类,需要在类型层次上被标注为`@Validated`。 - -例如,下面的服务触发第一个参数的验证,确保它的大小在8和10之间: -```java -@Service -@Validated -public class MyBean { - - public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code, - Author author) { - ... - } - -} -``` diff --git a/IV. Spring Boot features/34.1 WebClient Customization.md b/IV. Spring Boot features/34.1 WebClient Customization.md new file mode 100644 index 00000000..6fcb8214 --- /dev/null +++ b/IV. Spring Boot features/34.1 WebClient Customization.md @@ -0,0 +1,9 @@ +### 34.1 自定义WebClient + +有三种主要的方式实现`WebClient`的自定义,用哪种方式取决于你想多大范围地应用自定义。 + +为了使自定义的范围尽可能的小,注入自动配置的`WebClient.Builder`,然后根据需要调用它的方法。`WebClient.Builder`实例有状态:在builder上的任何改变都会反映在其后创建的所有客户端里。如果你想要使用相同的builder创建几个客户端,你也可以使用`WebClient.Builder other = builder.clone();`克隆builder。。 + +为了对`WebClient.Builder`实例实现整个应用范围的自定义,你可以声明`WebClientCustomizer` bean,并且在注入时局部地改变`WebClient.Builder`。 + +最后,你可以回到原始API,使用`WebClient.create()`。那种情况下,不会应用自动配置或者`WebClientCustomizer`。 diff --git a/IV. Spring Boot features/35. Sending email.md b/IV. Spring Boot features/35. Sending email.md deleted file mode 100644 index 17a007df..00000000 --- a/IV. Spring Boot features/35. Sending email.md +++ /dev/null @@ -1,12 +0,0 @@ -### 35. 发送邮件 -Spring框架通过`JavaMailSender`接口为发送邮件提供了一个简单的抽象,并且Spring Boot也为它提供了自动配置和一个starter模块。 -具体查看[`JavaMailSender`参考文档](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#mail)。 - -如果`spring.mail.host`和相关的libraries(通过`spring-boot-starter-mail`定义的)都可用,Spring Boot将创建一个默认的`JavaMailSender`,该sender可以通过`spring.mail`命名空间下的配置项进一步自定义,具体参考[MailProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailProperties.java)。 - -特别地,某些默认的超时值是无限的。你可能想改变它,以避免由无响应的邮件服务器引起的线程阻塞: -```properties -spring.mail.properties.mail.smtp.connectiontimeout=5000 -spring.mail.properties.mail.smtp.timeout=3000 -spring.mail.properties.mail.smtp.writetimeout=5000 -``` \ No newline at end of file diff --git a/IV. Spring Boot features/35. Validation.md b/IV. Spring Boot features/35. Validation.md new file mode 100644 index 00000000..539c9414 --- /dev/null +++ b/IV. Spring Boot features/35. Validation.md @@ -0,0 +1,17 @@ +### 35. 验证 + +只要在类路径上存在JSR-303实现(比如Hibernate validator),Bean Validation 1.1支持的方法验证特性就会自动启用。这允许bean方法的参数和/或者返回值,被标注为`javax.validation`约束。为了让这样的带标注的方法在搜索行内约束标注时被找到,拥有它们的目标类,需要在类型层次上被标注为`@Validated`。 + +例如,下面的服务触发第一个参数的验证,确保它的大小在8和10之间: +```java +@Service +@Validated +public class MyBean { + + public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code, + Author author) { + ... + } + +} +``` diff --git a/IV. Spring Boot features/36. Distributed Transactions with JTA.md b/IV. Spring Boot features/36. Distributed Transactions with JTA.md deleted file mode 100644 index 2663cfcd..00000000 --- a/IV. Spring Boot features/36. Distributed Transactions with JTA.md +++ /dev/null @@ -1,5 +0,0 @@ -### 36. 使用JTA处理分布式事务 - -Spring Boot通过[Atomkos](http://www.atomikos.com/)或[Bitronix](http://docs.codehaus.org/display/BTM/Home)的内嵌事务管理器支持跨多个XA资源的分布式JTA事务,当部署到恰当的J2EE应用服务器时也会支持JTA事务。 - -当发现JTA环境时,Spring Boot将使用Spring的`JtaTransactionManager`来管理事务。自动配置的JMS,DataSource和JPA beans将被升级以支持XA事务。你可以使用标准的Spring idioms,比如`@Transactional`,来参与到一个分布式事务中。如果处于JTA环境,但仍想使用本地事务,你可以将`spring.jta.enabled`属性设置为`false`来禁用JTA自动配置功能。 diff --git a/IV. Spring Boot features/36. Sending Email.md b/IV. Spring Boot features/36. Sending Email.md new file mode 100644 index 00000000..4fd2a873 --- /dev/null +++ b/IV. Spring Boot features/36. Sending Email.md @@ -0,0 +1,12 @@ +### 36. 发送邮件 +Spring框架通过`JavaMailSender`接口为发送邮件提供了一个简单的抽象,并且Spring Boot也为它提供了自动配置和一个starter模块。 +具体查看[`JavaMailSender`参考文档](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/integration.html#mail)。 + +如果`spring.mail.host`和相关的libraries(通过`spring-boot-starter-mail`定义的)都可用,Spring Boot将创建一个默认的`JavaMailSender`,该sender可以通过`spring.mail`命名空间下的配置项进一步自定义,具体参考[MailProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailProperties.java)。 + +特别地,某些默认的超时值是无限的。你可能想改变它,以避免由无响应的邮件服务器引起的线程阻塞: +```properties +spring.mail.properties.mail.smtp.connectiontimeout=5000 +spring.mail.properties.mail.smtp.timeout=3000 +spring.mail.properties.mail.smtp.writetimeout=5000 +``` diff --git a/IV. Spring Boot features/36.1 Using an Atomikos transaction manager.md b/IV. Spring Boot features/36.1 Using an Atomikos transaction manager.md deleted file mode 100644 index c1403794..00000000 --- a/IV. Spring Boot features/36.1 Using an Atomikos transaction manager.md +++ /dev/null @@ -1,7 +0,0 @@ -### 36.1 使用Atomikos事务管理器 - -Atomikos是一个非常流行的开源事务管理器,并且可以嵌入到你的Spring Boot应用中。你可以使用`spring-boot-starter-jta-atomikos`Starter去获取正确的Atomikos库。Spring Boot会自动配置Atomikos,并将合适的`depends-on`应用到你的Spring Beans上,确保它们以正确的顺序启动和关闭。 - -默认情况下,Atomikos事务日志将被记录在应用home目录(你的应用jar文件放置的目录)下的`transaction-logs`文件夹中。你可以在`application.properties`文件中通过设置`spring.jta.log-dir`属性来定义该目录,以`spring.jta.atomikos.properties`开头的属性能用来定义Atomikos的`UserTransactionServiceIml`实现,具体参考[AtomikosProperties javadoc](http://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/jta/atomikos/AtomikosProperties.html)。 - -**注** 为了确保多个事务管理器能够安全地和相应的资源管理器配合,每个Atomikos实例必须设置一个唯一的ID。默认情况下,该ID是Atomikos实例运行的机器上的IP地址。为了确保生产环境中该ID的唯一性,你需要为应用的每个实例设置不同的`spring.jta.transaction-manager-id`属性值。 diff --git a/IV. Spring Boot features/36.2 Using a Bitronix transaction manager.md b/IV. Spring Boot features/36.2 Using a Bitronix transaction manager.md deleted file mode 100644 index 1e65936f..00000000 --- a/IV. Spring Boot features/36.2 Using a Bitronix transaction manager.md +++ /dev/null @@ -1,7 +0,0 @@ -### 36.2 使用Bitronix事务管理器 - -Bitronix是一个流行的开源JTA事务管理器实现,你可以使用`spring-boot-starter-jta-bitronix`starter为项目添加合适的Birtronix依赖。和Atomikos类似,Spring Boot将自动配置Bitronix,并对beans进行后处理(post-process)以确保它们以正确的顺序启动和关闭。 - -默认情况下,Bitronix事务日志(`part1.btm`和`part2.btm`)将被记录到应用home目录下的`transaction-logs`文件夹中,你可以通过设置`spring.jta.log-dir`属性来自定义该目录。以`spring.jta.bitronix.properties`开头的属性将被绑定到`bitronix.tm.Configuration` bean,你可以通过这完成进一步的自定义,具体参考[Bitronix文档](https://github.com/bitronix/btm/wiki/Transaction-manager-configuration)。 - -**注** 为了确保多个事务管理器能够安全地和相应的资源管理器配合,每个Bitronix实例必须设置一个唯一的ID。默认情况下,该ID是Bitronix实例运行的机器上的IP地址。为了确保生产环境中该ID的唯一性,你需要为应用的每个实例设置不同的`spring.jta.transaction-manager-id`属性值。 diff --git a/IV. Spring Boot features/36.3 Using a Narayana transaction manager.md b/IV. Spring Boot features/36.3 Using a Narayana transaction manager.md deleted file mode 100644 index d8309bf2..00000000 --- a/IV. Spring Boot features/36.3 Using a Narayana transaction manager.md +++ /dev/null @@ -1,7 +0,0 @@ -### 36.3 使用Narayana事务管理器 - -Narayana是一个流行的开源JTA事务管理器实现,目前只有JBoss支持。你可以使用`spring-boot-starter-jta-narayana` starter添加合适的Narayana依赖,像Atomikos和Bitronix那样,Spring Boot将自动配置Narayana,并对你的beans后处理(post-process)以确保正确启动和关闭。 - -Narayana事务日志默认记录到应用home目录(放置应用jar的目录)的`transaction-logs`目录下,你可以通过设置`application.properties`中的`spring.jta.log-dir`属性自定义该目录。以`spring.jta.narayana.properties`开头的属性可用于自定义Narayana配置,具体参考[NarayanaProperties](http://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/jta/narayana/NarayanaProperties.html)。 - -**注** 为了确保多事务管理器能够安全配合相应资源管理器,每个Narayana实例必须配置唯一的ID,默认ID设为`1`。为确保生产环境中ID唯一性,你可以为应用的每个实例配置不同的`spring.jta.transaction-manager-id`属性值。 diff --git a/IV. Spring Boot features/36.4 Using a Java EE managed transaction manager.md b/IV. Spring Boot features/36.4 Using a Java EE managed transaction manager.md deleted file mode 100644 index 862a8afa..00000000 --- a/IV. Spring Boot features/36.4 Using a Java EE managed transaction manager.md +++ /dev/null @@ -1,3 +0,0 @@ -### 36.4 使用J2EE管理的事务管理器 - -如果你将Spring Boot应用打包为一个`war`或`ear`文件,并将它部署到一个J2EE的应用服务器中,那你就能使用应用服务器内建的事务管理器。Spring Boot将尝试通过查找常见的JNDI路径(`java:comp/UserTransaction`, `java:comp/TransactionManager`等)来自动配置一个事务管理器。如果使用应用服务器提供的事务服务,你通常需要确保所有的资源都被应用服务器管理,并通过JNDI暴露出去。Spring Boot通过查找JNDI路径`java:/JmsXA`或`java:/XAConnectionFactory`获取一个`ConnectionFactory`来自动配置JMS,并且你可以使用`spring.datasource.jndi-name`属性配置你的`DataSource`。 diff --git a/IV. Spring Boot features/36.5 Mixing XA and non-XA JMS connections.md b/IV. Spring Boot features/36.5 Mixing XA and non-XA JMS connections.md deleted file mode 100644 index 80f9d14d..00000000 --- a/IV. Spring Boot features/36.5 Mixing XA and non-XA JMS connections.md +++ /dev/null @@ -1,20 +0,0 @@ -### 36.5 混合XA和non-XA的JMS连接 - -当使用JTA时,primary JMS `ConnectionFactory`bean将能识别XA,并参与到分布式事务中。有些情况下,你可能需要使用non-XA的`ConnectionFactory`去处理一些JMS消息。例如,你的JMS处理逻辑可能比XA超时时间长。 - -如果想使用一个non-XA的`ConnectionFactory`,你可以注入`nonXaJmsConnectionFactory` bean而不是`@Primary` `jmsConnectionFactory` bean。为了保持一致,`jmsConnectionFactory` bean将以别名`xaJmsConnectionFactor`来被使用。 - -示例如下: -```java -// Inject the primary (XA aware) ConnectionFactory -@Autowired -private ConnectionFactory defaultConnectionFactory; -// Inject the XA aware ConnectionFactory (uses the alias and injects the same as above) -@Autowired -@Qualifier("xaJmsConnectionFactory") -private ConnectionFactory xaConnectionFactory; -// Inject the non-XA aware ConnectionFactory -@Autowired -@Qualifier("nonXaJmsConnectionFactory") -private ConnectionFactory nonXaConnectionFactory; -``` diff --git a/IV. Spring Boot features/36.6 Supporting an alternative embedded transaction manager.md b/IV. Spring Boot features/36.6 Supporting an alternative embedded transaction manager.md deleted file mode 100644 index 5203639a..00000000 --- a/IV. Spring Boot features/36.6 Supporting an alternative embedded transaction manager.md +++ /dev/null @@ -1,5 +0,0 @@ -### 36.6 支持可替代的内嵌事务管理器 - -[XAConnectionFactoryWrapper](http://github.com/spring-projects/spring-boot/tree/master/spring-boot/src/main/java/org/springframework/boot/jta/XAConnectionFactoryWrapper.java)和[XADataSourceWrapper](http://github.com/spring-projects/spring-boot/tree/master/spring-boot/src/main/java/org/springframework/boot/jta/XADataSourceWrapper.java)接口用于支持可替换的内嵌事务管理器。该接口用于包装`XAConnectionFactory`和`XADataSource` beans,并将它们暴露为普通的`ConnectionFactory`和`DataSource` beans,这样在分布式事务中可以透明使用。Spring Boot将使用注册到`ApplicationContext`的合适的XA包装器及`JtaTransactionManager` bean自动配置你的DataSource和JMS。 - -[BitronixXAConnectionFactoryWrapper](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java)和[BitronixXADataSourceWrapper](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java)提供很好的示例用于演示怎么编写XA包装器。 diff --git a/IV. Spring Boot features/37. Distributed Transactions with JTA.md b/IV. Spring Boot features/37. Distributed Transactions with JTA.md new file mode 100644 index 00000000..110ce871 --- /dev/null +++ b/IV. Spring Boot features/37. Distributed Transactions with JTA.md @@ -0,0 +1,5 @@ +### 37. 使用JTA处理分布式事务 + +Spring Boot通过[Atomkos](http://www.atomikos.com/)或[Bitronix](https://github.com/bitronix/btm)的内嵌事务管理器支持跨多个XA资源的分布式JTA事务,当部署到恰当的J2EE应用服务器时也会支持JTA事务。 + +当发现JTA环境时,Spring Boot将使用Spring的`JtaTransactionManager`来管理事务。自动配置的JMS,DataSource和JPA beans将被升级以支持XA事务。你可以使用标准的Spring idioms,比如`@Transactional`,来参与到一个分布式事务中。如果处于JTA环境,但仍想使用本地事务,你可以将`spring.jta.enabled`属性设置为`false`来禁用JTA自动配置功能。 diff --git a/IV. Spring Boot features/37. Hazelcast.md b/IV. Spring Boot features/37. Hazelcast.md deleted file mode 100644 index bbd74315..00000000 --- a/IV. Spring Boot features/37. Hazelcast.md +++ /dev/null @@ -1,16 +0,0 @@ -### 37. Hazelcast - -如果添加hazelcast依赖并正确配置好了,Spring Boot将自动配置一个`HazelcastInstance`,你可以注入到应用中。 -如果定义了`com.hazelcast.config.Config` bean,则Spring Boot将使用它。如果你的配置指定了实例的名称,Spring Boot将尝试定位已存在的而不是创建一个新实例。你可以在配置中指定将要使用的`hazelcast.xml`配置文件: -```properties -spring.hazelcast.config=classpath:config/my-hazelcast.xml -``` -否则,Spring Boot尝试从默认路径查找Hazelcast配置,也就是`hazelcast.xml`所在的工作路径或classpath的根路径。Spring Boot也会检查是否设置`hazelcast.config`系统属性,具体参考[Hazelcast文档](http://docs.hazelcast.org/docs/latest/manual/html-single/)。 - -如果`hazelcast-client`存在于类路径中,Spring Boot将会首先尝试使用与上面相似的规则创建一个客户端,也就是: -* 一个`com.hazelcast.client.config.ClientConfig`bean -* 由`spring.hazelcast.config`属性定义的配置文件 -* `hazelcast.client.config`系统属性 -* 一个在工作目录或者类路径的根目录中的`hazelcast-client.xml` - -**注** Spring Boot为Hazelcast提供了缓存支持,如果开启缓存的话,`HazelcastInstance`实例将自动包装进一个`CacheManager`实现中。 diff --git a/IV. Spring Boot features/37.1 Using an Atomikos Transaction Manager.md b/IV. Spring Boot features/37.1 Using an Atomikos Transaction Manager.md new file mode 100644 index 00000000..61cf8e67 --- /dev/null +++ b/IV. Spring Boot features/37.1 Using an Atomikos Transaction Manager.md @@ -0,0 +1,7 @@ +### 37.1 使用Atomikos事务管理器 + +[Atomikos](https://www.atomikos.com/)是一个非常流行的开源事务管理器,并且可以嵌入到你的Spring Boot应用中。你可以使用`spring-boot-starter-jta-atomikos`Starter去获取正确的Atomikos库。Spring Boot会自动配置Atomikos,并将合适的`depends-on`应用到你的Spring Beans上,确保它们以正确的顺序启动和关闭。 + +默认情况下,Atomikos事务日志将被记录在应用home目录(你的应用jar文件放置的目录)下的`transaction-logs`文件夹中。你可以在`application.properties`文件中通过设置`spring.jta.log-dir`属性来定义该目录,以`spring.jta.atomikos.properties`开头的属性能用来定义Atomikos的`UserTransactionServiceIml`实现,具体参考[AtomikosProperties javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/jta/atomikos/AtomikosProperties.html)。 + +**注** 为了确保多个事务管理器能够安全地和相应的资源管理器配合,每个Atomikos实例必须设置一个唯一的ID。默认情况下,该ID是Atomikos实例运行的机器上的IP地址。为了确保生产环境中该ID的唯一性,你需要为应用的每个实例设置不同的`spring.jta.transaction-manager-id`属性值。 diff --git a/IV. Spring Boot features/37.2 Using a Bitronix Transaction Manager.md b/IV. Spring Boot features/37.2 Using a Bitronix Transaction Manager.md new file mode 100644 index 00000000..c6d7dd74 --- /dev/null +++ b/IV. Spring Boot features/37.2 Using a Bitronix Transaction Manager.md @@ -0,0 +1,7 @@ +### 37.2 使用Bitronix事务管理器 + +[Bitronix](https://github.com/bitronix/btm)是一个流行的开源JTA事务管理器实现,你可以使用`spring-boot-starter-jta-bitronix`starter为项目添加合适的Birtronix依赖。和Atomikos类似,Spring Boot将自动配置Bitronix,并对beans进行后处理(post-process)以确保它们以正确的顺序启动和关闭。 + +默认情况下,Bitronix事务日志(`part1.btm`和`part2.btm`)将被记录到应用home目录下的`transaction-logs`文件夹中,你可以通过设置`spring.jta.log-dir`属性来自定义该目录。以`spring.jta.bitronix.properties`开头的属性将被绑定到`bitronix.tm.Configuration` bean,你可以通过这完成进一步的自定义,具体参考[Bitronix文档](https://github.com/bitronix/btm/wiki/Transaction-manager-configuration)。 + +**注** 为了确保多个事务管理器能够安全地和相应的资源管理器配合,每个Bitronix实例必须设置一个唯一的ID。默认情况下,该ID是Bitronix实例运行的机器上的IP地址。为了确保生产环境中该ID的唯一性,你需要为应用的每个实例设置不同的`spring.jta.transaction-manager-id`属性值。 diff --git a/IV. Spring Boot features/37.3 Using a Narayana Transaction Manager.md b/IV. Spring Boot features/37.3 Using a Narayana Transaction Manager.md new file mode 100644 index 00000000..eae6ead7 --- /dev/null +++ b/IV. Spring Boot features/37.3 Using a Narayana Transaction Manager.md @@ -0,0 +1,7 @@ +### 37.3 使用Narayana事务管理器 + +[Narayana](http://narayana.io/)是一个流行的开源JTA事务管理器实现,目前只有JBoss支持。你可以使用`spring-boot-starter-jta-narayana` starter添加合适的Narayana依赖,像Atomikos和Bitronix那样,Spring Boot将自动配置Narayana,并对你的beans后处理(post-process)以确保正确启动和关闭。 + +Narayana事务日志默认记录到应用home目录(放置应用jar的目录)的`transaction-logs`目录下,你可以通过设置`application.properties`中的`spring.jta.log-dir`属性自定义该目录。以`spring.jta.narayana.properties`开头的属性可用于自定义Narayana配置,具体参考[NarayanaProperties](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/jta/narayana/NarayanaProperties.html)。 + +**注** 为了确保多事务管理器能够安全配合相应资源管理器,每个Narayana实例必须配置唯一的ID,默认ID设为`1`。为确保生产环境中ID唯一性,你可以为应用的每个实例配置不同的`spring.jta.transaction-manager-id`属性值。 diff --git a/IV. Spring Boot features/37.4 Using a Java EE Managed Transaction Manager.md b/IV. Spring Boot features/37.4 Using a Java EE Managed Transaction Manager.md new file mode 100644 index 00000000..78a7f785 --- /dev/null +++ b/IV. Spring Boot features/37.4 Using a Java EE Managed Transaction Manager.md @@ -0,0 +1,3 @@ +### 37.4 使用J2EE管理的事务管理器 + +如果你将Spring Boot应用打包为一个`war`或`ear`文件,并将它部署到一个J2EE的应用服务器中,那你就能使用应用服务器内建的事务管理器。Spring Boot将尝试通过查找常见的JNDI路径(`java:comp/UserTransaction`, `java:comp/TransactionManager`等)来自动配置一个事务管理器。如果使用应用服务器提供的事务服务,你通常需要确保所有的资源都被应用服务器管理,并通过JNDI暴露出去。Spring Boot通过查找JNDI路径(`java:/JmsXA`或`java:/XAConnectionFactory`),获取一个`ConnectionFactory`来自动配置JMS,并且你可以使用[`spring.datasource.jndi-name`属性](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-connecting-to-a-jndi-datasource)配置你的`DataSource`。 diff --git a/IV. Spring Boot features/37.5 Mixing XA and Non-XA JMS Connections.md b/IV. Spring Boot features/37.5 Mixing XA and Non-XA JMS Connections.md new file mode 100644 index 00000000..16b3b540 --- /dev/null +++ b/IV. Spring Boot features/37.5 Mixing XA and Non-XA JMS Connections.md @@ -0,0 +1,20 @@ +### 37.5 混合XA和non-XA的JMS连接 + +当使用JTA时,primary JMS `ConnectionFactory`bean将能识别XA,并参与到分布式事务中。有些情况下,你可能需要使用non-XA的`ConnectionFactory`去处理一些JMS消息。例如,你的JMS处理逻辑可能比XA超时时间长。 + +如果想使用一个non-XA的`ConnectionFactory`,你可以注入`nonXaJmsConnectionFactory` bean而不是`@Primary` `jmsConnectionFactory` bean。为了保持一致,`jmsConnectionFactory` bean将以别名`xaJmsConnectionFactor`来被使用。 + +示例如下: +```java +// Inject the primary (XA aware) ConnectionFactory +@Autowired +private ConnectionFactory defaultConnectionFactory; +// Inject the XA aware ConnectionFactory (uses the alias and injects the same as above) +@Autowired +@Qualifier("xaJmsConnectionFactory") +private ConnectionFactory xaConnectionFactory; +// Inject the non-XA aware ConnectionFactory +@Autowired +@Qualifier("nonXaJmsConnectionFactory") +private ConnectionFactory nonXaConnectionFactory; +``` diff --git a/IV. Spring Boot features/37.6 Supporting an Alternative Embedded Transaction Manager.md b/IV. Spring Boot features/37.6 Supporting an Alternative Embedded Transaction Manager.md new file mode 100644 index 00000000..2de48e85 --- /dev/null +++ b/IV. Spring Boot features/37.6 Supporting an Alternative Embedded Transaction Manager.md @@ -0,0 +1,5 @@ +### 37.6 支持可替代的内嵌事务管理器 + +[XAConnectionFactoryWrapper](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jms/XAConnectionFactoryWrapper.java)和[XADataSourceWrapper](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/XADataSourceWrapper.java)接口用于支持可替换的内嵌事务管理器。该接口用于包装`XAConnectionFactory`和`XADataSource` beans,并将它们暴露为普通的`ConnectionFactory`和`DataSource` beans,这样在分布式事务中可以透明使用。Spring Boot将使用注册到`ApplicationContext`的合适的XA包装器及`JtaTransactionManager` bean自动配置你的DataSource和JMS。 + +[BitronixXAConnectionFactoryWrapper](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java)和[BitronixXADataSourceWrapper](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java)提供很好的示例用于演示怎么编写XA包装器。 diff --git a/IV. Spring Boot features/38. Hazelcast.md b/IV. Spring Boot features/38. Hazelcast.md new file mode 100644 index 00000000..c994c699 --- /dev/null +++ b/IV. Spring Boot features/38. Hazelcast.md @@ -0,0 +1,17 @@ +### 38. Hazelcast + +如果添加[Hazelcast](https://hazelcast.com/)依赖并正确配置好了,Spring Boot将自动配置一个`HazelcastInstance`,你可以注入到应用中。 + +如果定义了`com.hazelcast.config.Config` bean,则Spring Boot将使用它。如果你的配置指定了实例的名称,Spring Boot将尝试定位已存在的而不是创建一个新实例。你可以在配置中指定将要使用的`hazelcast.xml`配置文件: +```properties +spring.hazelcast.config=classpath:config/my-hazelcast.xml +``` +否则,Spring Boot尝试从默认路径查找Hazelcast配置,也就是`hazelcast.xml`所在的工作路径或classpath的根路径。Spring Boot也会检查是否设置`hazelcast.config`系统属性,具体参考[Hazelcast文档](http://docs.hazelcast.org/docs/latest/manual/html-single/)。 + +如果`hazelcast-client`存在于类路径中,Spring Boot将会首先尝试使用与上面相似的规则创建一个客户端,也就是: +* 一个`com.hazelcast.client.config.ClientConfig`bean +* 由`spring.hazelcast.config`属性定义的配置文件 +* `hazelcast.client.config`系统属性 +* 一个在工作目录或者类路径的根目录中的`hazelcast-client.xml` + +**注** Spring Boot[为Hazelcast提供了缓存支持](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-hazelcast)。如果开启缓存的话,`HazelcastInstance`实例将自动包装进一个`CacheManager`实现中。 diff --git a/IV. Spring Boot features/38. Quartz Scheduler.md b/IV. Spring Boot features/38. Quartz Scheduler.md deleted file mode 100644 index 5df3fd03..00000000 --- a/IV. Spring Boot features/38. Quartz Scheduler.md +++ /dev/null @@ -1,43 +0,0 @@ -### 38. Quartz调度器 - -Spring Boot包含有`spring-boot-starter-quartz`Starter,方便了使用Quartz调度器。如果Quartz可用,调度器会被自动配置(通过SchedulerFactoryBean抽象)。 - -以下类型的bean会被自动捡起并关联到调度器: -* `JobDetail`:定义一个特别的Job。`JobDetail`实例能够容易地用`JobBuilder`API创建 -* `Calendar` -* `Trigger`:定义何时一个特别的Job被触发 - -默认的,一个内存中`JobStore`会被使用。但是,配置一个基于JDBC的store是可能的。如果在你的应用中`DataSource`bean可用,而且`spring.quartz.job-store-type`属性如下配置: -```properties -spring.quartz.job-store-type=jdbc -``` -当jdbc store被使用,模式能够在启动时被初始化: -```properties -spring.quartz.jdbc.initialize-schema=true -``` - -**注** 数据库会默认被检查,而且会被初始化(使用由Quartz库提供的标准脚本)。也可以使用`spring.quartz.jdbc.schema`属性提供一个自定义脚本。 - -Quartz调度器的配置能够使用Quartz配置属性(查看`spring.quartz.properties.*`),和`SchedulerFactoryBeanCustomizer`bean(允许程序化的`SchedulerFactoryBean`配置)来自定义 。 - -Job能够定义setter来注入数据映射属性。普通的bean也能够用相似的行为来注入: -```java -public class SampleJob extends QuartzJobBean { - - private MyService myService; - private String name; - - // Inject "MyService" bean - public void setMyService(MyService myService) { ... } - - // Inject the "name" job data property - public void setName(String name) { ... } - - @Override - protected void executeInternal(JobExecutionContext context) - throws JobExecutionException { - ... - } - -} -``` diff --git a/IV. Spring Boot features/39. Quartz Scheduler.md b/IV. Spring Boot features/39. Quartz Scheduler.md new file mode 100644 index 00000000..e472643e --- /dev/null +++ b/IV. Spring Boot features/39. Quartz Scheduler.md @@ -0,0 +1,43 @@ +### 39. Quartz调度器 + +Spring Boot包含有`spring-boot-starter-quartz`Starter,方便了使用[Quartz调度器](http://www.quartz-scheduler.org/)。如果Quartz可用,调度器会被自动配置(通过SchedulerFactoryBean抽象)。 + +以下类型的bean会被自动捡起并关联到调度器: +* `JobDetail`:定义一个特别的Job。`JobDetail`实例能够容易地用`JobBuilder`API创建 +* `Calendar` +* `Trigger`:定义何时一个特别的Job被触发 + +默认的,一个内存中`JobStore`会被使用。但是,配置一个基于JDBC的store是可能的。如果在你的应用中`DataSource`bean可用,而且`spring.quartz.job-store-type`属性如下配置: +```properties +spring.quartz.job-store-type=jdbc +``` +当jdbc store被使用,模式能够在启动时被初始化: +```properties +spring.quartz.jdbc.initialize-schema=always +``` + +**注** 数据库会默认被检查,而且会被初始化(使用由Quartz库提供的标准脚本)。也可以使用`spring.quartz.jdbc.schema`属性提供一个自定义脚本。 + +Quartz调度器的配置能够使用Quartz配置属性(查看`spring.quartz.properties.*`),和`SchedulerFactoryBeanCustomizer`bean(允许程序化的`SchedulerFactoryBean`配置)来自定义 。 + +Job能够定义setter来注入数据映射属性。普通的bean也能够用相似的行为来注入: +```java +public class SampleJob extends QuartzJobBean { + + private MyService myService; + private String name; + + // Inject "MyService" bean + public void setMyService(MyService myService) { ... } + + // Inject the "name" job data property + public void setName(String name) { ... } + + @Override + protected void executeInternal(JobExecutionContext context) + throws JobExecutionException { + ... + } + +} +``` diff --git a/IV. Spring Boot features/39. Spring Integration.md b/IV. Spring Boot features/39. Spring Integration.md deleted file mode 100644 index 1763d330..00000000 --- a/IV. Spring Boot features/39. Spring Integration.md +++ /dev/null @@ -1,10 +0,0 @@ -### 39. Spring集成 - -Spring Boot为Spring集成提供了一些便利,包括`spring-boot-starter-integration` ‘Starter’。 -Spring集成提供基于消息和其他传输协议的抽象,比如HTTP,TCP等。如果添加Spring集成依赖,使用`@EnableIntegration`注解可以初始化它。 - -Spring Boot也会配置一些由另外的Spring集成模块触发的特性。如果classpath下存在`'spring-integration-jmx'`依赖,则消息处理统计分析将通过JMX发布出去。如果`'spring-integration-jdbc'`可用,默认的数据库模式会在启动时被创建: -```properties -spring.integration.jdbc.initializer.enabled =true -``` -更多细节请查看[`IntegrationAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java)和[`IntegrationProperties`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationProperties.java)类。 diff --git a/IV. Spring Boot features/40. Spring Integration.md b/IV. Spring Boot features/40. Spring Integration.md new file mode 100644 index 00000000..db1f6160 --- /dev/null +++ b/IV. Spring Boot features/40. Spring Integration.md @@ -0,0 +1,11 @@ +### 40. Spring集成 + +Spring Boot为[Spring集成](https://projects.spring.io/spring-integration/)提供了一些便利,包括`spring-boot-starter-integration` ‘Starter’。 +Spring集成提供基于消息和其他传输协议的抽象,比如HTTP,TCP等。如果添加Spring集成依赖,使用`@EnableIntegration`注解可以初始化它。 + +Spring Boot也会配置一些由另外的Spring集成模块触发的特性。如果classpath下存在`'spring-integration-jmx'`依赖,则消息处理统计分析将通过JMX发布出去。如果`'spring-integration-jdbc'`可用,默认的数据库模式会在启动时被创建: +```properties +spring.integration.jdbc.initialize-schema=always +``` + +更多细节请查看[`IntegrationAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java)和[`IntegrationProperties`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationProperties.java)类。 diff --git a/IV. Spring Boot features/40. Spring Session.md b/IV. Spring Boot features/40. Spring Session.md deleted file mode 100644 index 2c6eac8b..00000000 --- a/IV. Spring Boot features/40. Spring Session.md +++ /dev/null @@ -1,19 +0,0 @@ -###40. Spring Session -Spring Boot为Spring Session自动配置了各种存储: - -* JDBC -* Redis -* Hazelcast -* HashMap - -如果Spring Session可用,你必须选择想要的存储sessions的存储类型[StoreType](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/StoreType.java)。例如,按如下配置将使用JDBC作为后端存储: -```properties -spring.session.store-type=jdbc -``` - -**提醒** 设置`store-type`为`none`可以禁用Spring Session。 - -每个存储都有特殊设置,例如,对于jdbc存储可自定义表名: -```properties -spring.session.jdbc.table-name=SESSIONS -``` diff --git a/IV. Spring Boot features/41. Monitoring and management over JMX.md b/IV. Spring Boot features/41. Monitoring and management over JMX.md deleted file mode 100644 index 5ef7229a..00000000 --- a/IV. Spring Boot features/41. Monitoring and management over JMX.md +++ /dev/null @@ -1,3 +0,0 @@ -### 41. 基于JMX的监控和管理 - -Java管理扩展(JMX)提供了一个标准的用于监控和管理应用的机制。默认情况下,Spring Boot将创建一个id为‘mbeanServer’的`MBeanServer`,并导出任何被Spring JMX注解(`@ManagedResource`,`@ManagedAttribute`,`@ManagedOperation`)的beans,具体参考[JmxAutoConfiguration类](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java)。 diff --git a/IV. Spring Boot features/41. Spring Session.md b/IV. Spring Boot features/41. Spring Session.md new file mode 100644 index 00000000..ab45b197 --- /dev/null +++ b/IV. Spring Boot features/41. Spring Session.md @@ -0,0 +1,25 @@ +### 41. Spring Session + +Spring Boot为Spring Session自动配置了各种数据存储。当构建Servlet网络应用时,以下存储方式会被自动配置: + +* JDBC +* Redis +* Hazelcast +* MongoDB + +当构建响应式网络应用时,以下存储方式会被自动配置: + +* Redis +* MongoDB + +如果Spring Session可用,你必须选择想要的存储sessions的存储类型[StoreType](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/StoreType.java)。例如,按如下配置将使用JDBC作为后端存储: +```properties +spring.session.store-type=jdbc +``` + +**提醒** 设置`store-type`为`none`可以禁用Spring Session。 + +每个存储都有特殊设置,例如,对于jdbc存储可自定义表名: +```properties +spring.session.jdbc.table-name=SESSIONS +``` diff --git a/IV. Spring Boot features/42. Monitoring and Management over JMX.md b/IV. Spring Boot features/42. Monitoring and Management over JMX.md new file mode 100644 index 00000000..1d13ba58 --- /dev/null +++ b/IV. Spring Boot features/42. Monitoring and Management over JMX.md @@ -0,0 +1,3 @@ +### 42. 基于JMX的监控和管理 + +Java管理扩展(JMX)提供了一个标准的用于监控和管理应用的机制。默认情况下,Spring Boot将创建一个ID为`mbeanServer`的`MBeanServer`,并导出任何被Spring JMX注解(`@ManagedResource`,`@ManagedAttribute`,`@ManagedOperation`)的bean,具体参考[JmxAutoConfiguration类](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java)。 diff --git a/IV. Spring Boot features/42. Testing.md b/IV. Spring Boot features/42. Testing.md deleted file mode 100644 index de09e8f2..00000000 --- a/IV. Spring Boot features/42. Testing.md +++ /dev/null @@ -1,5 +0,0 @@ -###42. 测试 - -Spring Boot提供很多有用的工具类和注解用于帮助你测试应用,主要分两个模块:`spring-boot-test`包含核心组件,`spring-boot-test-autoconfigure`为测试提供自动配置。 - -大多数开发者只需要引用`spring-boot-starter-test` ‘Starter’,它既提供Spring Boot测试模块,也提供JUnit,AssertJ,Hamcrest和很多有用的依赖。 diff --git a/IV. Spring Boot features/42.1 Test scope dependencies.md b/IV. Spring Boot features/42.1 Test scope dependencies.md deleted file mode 100644 index 829a26c3..00000000 --- a/IV. Spring Boot features/42.1 Test scope dependencies.md +++ /dev/null @@ -1,13 +0,0 @@ -###42.1 测试作用域依赖 - -如果使用`spring-boot-starter-test` ‘Starter’(在`test` `scope`内),你将发现下列被提供的库: - -- [JUnit](http://junit.org/) - 事实上的(de-facto)标准,用于Java应用的单元测试。 -- [Spring Test](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#integration-testing.html) & Spring Boot Test  - 对Spring应用的集成测试支持。 -- [AssertJ](http://joel-costigliola.github.io/assertj/) - 一个流式断言库。 -- [Hamcrest](http://hamcrest.org/JavaHamcrest/) - 一个匹配对象的库(也称为约束或前置条件)。 -- [Mockito](http://mockito.org/) - 一个Java模拟框架。 -- [JSONassert](https://github.com/skyscreamer/JSONassert) - 一个针对JSON的断言库。 -- [JsonPath](https://github.com/jayway/JsonPath) - 用于JSON的XPath。 - -这是写测试用例经常用到的库,如果它们不能满足要求,你可以随意添加其他的依赖。 diff --git a/IV. Spring Boot features/42.2 Testing Spring applications.md b/IV. Spring Boot features/42.2 Testing Spring applications.md deleted file mode 100644 index aa273b7e..00000000 --- a/IV. Spring Boot features/42.2 Testing Spring applications.md +++ /dev/null @@ -1,7 +0,0 @@ -###42.2 测试Spring应用 - -依赖注入主要优势之一就是它能够让你的代码更容易进行单元测试。你只需简单的通过`new`操作符实例化对象,甚至不需要涉及Spring,也可以使用模拟对象替换真正的依赖。 - -你常常需要在进行单元测试后,开始集成测试(在这个过程中只需要涉及到Spring的`ApplicationContext`)。在执行集成测试时,不需要部署应用或连接到其他基础设施是非常有用的,Spring框架为实现这样的集成测试提供了一个专用的测试模块,通过声明`org.springframework:spring-test`的依赖,或使用`spring-boot-starter-test` ‘Starter’就可以使用它了。 - -如果以前没有使用过`spring-test`模块,可以查看Spring框架参考文档中的[相关章节](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/testing.html#testing)。 diff --git a/IV. Spring Boot features/42.3 Testing Spring Boot applications.md b/IV. Spring Boot features/42.3 Testing Spring Boot applications.md deleted file mode 100644 index 000b4cf7..00000000 --- a/IV. Spring Boot features/42.3 Testing Spring Boot applications.md +++ /dev/null @@ -1,21 +0,0 @@ -### 42.3 测试Spring Boot应用 - -Spring Boot应用只是一个Spring `ApplicationContext`,所以在测试时对它只需要像处理普通Spring context那样即可。唯一需要注意的是,如果你使用`SpringApplication`创建上下文,外部配置,日志和Spring Boot的其他特性只会在默认的上下文中起作用。 - -Spring Boot提供一个`@SpringApplicationConfiguration`注解用于替换标准的`spring-test` `@ContextConfiguration`注解,该组件工作方式是通过`SpringApplication`创建用于测试的`ApplicationContext`。 - -你可以使用`@SpringBootTest`的`webEnvironment`属性定义怎么运行测试: - -* `MOCK` - 加载`WebApplicationContext`,并提供一个mock servlet环境,使用该注解时内嵌servlet容器将不会启动。如果classpath下不存在servlet APIs,该模式将创建一个常规的non-web `ApplicationContext`。Can be used in conjunction with @AutoConfigureMockMvc for MockMvc -based testing of your application. - -* `RANDOM_PORT` - 加载`ServletWebServerApplicationContext`,并提供一个真实的servlet环境。使用该模式内嵌容器将启动,并监听在一个随机端口。 - -* `DEFINED_PORT` - 加载`ServletWebServerApplicationContext`,并提供一个真实的servlet环境。使用该模式内嵌容器将启动,并监听一个定义好的端口(比如`application.properties`中定义的或默认的`8080`端口)。 - -* `NONE` - 使用`SpringApplication`加载一个`ApplicationContext`,但不提供任何servlet环境(不管是mock还是其他)。 - -**注** 如果你的测试标注了`@Transactional`,默认的,在每一个测试方法结束时,它将会回滚事务。如果你正是此种情况,而且用了`RANDOM_PORT`或是`DEFINED_PORT`。那么,任何在服务器上初始化的事务都不会回滚,因为测试正运行在一个不同的线程上,服务器不会进行处理。 - -**注** 除了`@SpringBootTest`,还有许多另外的注解被提供,用来测试应用的更多特定的部分。细节请看下面。 - -**注** 不要忘记在测试用例上添加`@RunWith(SpringRunner.class)`,否则该注解将被忽略。 diff --git a/IV. Spring Boot features/42.3.1 Detecting test configuration.md b/IV. Spring Boot features/42.3.1 Detecting test configuration.md deleted file mode 100644 index 819b8ef2..00000000 --- a/IV. Spring Boot features/42.3.1 Detecting test configuration.md +++ /dev/null @@ -1,8 +0,0 @@ -###42.3.1 发现测试配置 -如果熟悉Spring测试框架,你可能经常通过`@ContextConfiguration(classes=…)`指定加载哪些Spring `@Configuration`,也可能经常在测试类中使用内嵌`@Configuration`类。当测试Spring Boot应用时这些就不需要了,Spring Boot的`@*Test`注解会自动搜索主配置类,即使你没有显式定义它。 - -搜索算法是从包含测试类的package开始搜索,直到发现`@SpringBootApplication`或`@SpringBootConfiguration`注解的类,只要按[恰当的方式组织代码](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#using-boot-structuring-your-code),通常都会发现主配置类。 - -如果想自定义主配置类,你可以使用一个内嵌的`@TestConfiguration`类。不像内嵌的`@Configuration`类(会替换应用主配置类),内嵌的`@TestConfiguration`类是可以跟应用主配置类一块使用的。 - -**注** Spring测试框架在测试过程中会缓存应用上下文,因此,只要你的测试共享相同的配置(不管是怎么发现的),加载上下文的潜在时间消耗都只会发生一次。 diff --git a/IV. Spring Boot features/42.3.10 Auto-configured jOOQ tests.md b/IV. Spring Boot features/42.3.10 Auto-configured jOOQ tests.md deleted file mode 100644 index b27c96f2..00000000 --- a/IV. Spring Boot features/42.3.10 Auto-configured jOOQ tests.md +++ /dev/null @@ -1,23 +0,0 @@ -### 42.3.10 自动配置的jOOQ测试 - -`@JooqTest`的使用方式同`@JdbcTest`相似,不过是给jOOQ相关的测试用的。由于jOOQ严重依靠与数据库模式相对应的基于Java的模式,既存的`DataSource`将会被使用。如果你想要用一个内存数据库代替它,你可以使用`@AutoconfigureTestDatabase`来覆盖那些设置。 - -`@JooqTest`将会配置一个`DSLContext`。常规的`@Component`bean将不会加载进`ApplicationContext`: -```java -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测试类是事务型的,默认在每个测试结束时回滚。如果这不是你想要的结果,你可以按照[上面例子中的方式](./42.3.9 Auto-configured JDBC tests.md)对一个测试或是整个类禁用事务管理。 - -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@JooqTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/42.3.11 Auto-configured Data MongoDB tests.md b/IV. Spring Boot features/42.3.11 Auto-configured Data MongoDB tests.md deleted file mode 100644 index 51457744..00000000 --- a/IV. Spring Boot features/42.3.11 Auto-configured Data MongoDB tests.md +++ /dev/null @@ -1,34 +0,0 @@ -### 42.3.11 自动配置的Data MongoDB测试 - -如果你想要测试MongoDB应用,你可以使用`@DataMongoTest`。默认的,它将会配置一个内存MongoDB(如果可用),配置一个`@MongoTemplate`,扫描`@Document`类和配置Spring Data MongoDB仓库。常规的`@Component`bean将不会加载进`ApplicationContext`: -```java -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@DataMongoTest -public class ExampleDataMongoTests { - - @Autowired - private MongoTemplate mongoTemplate; - - // -} -``` -由于内存MongoDB快,而且不需要任何开发者安装,它总体上在测试中工作得很好。但是,如果你更喜欢在一个非真实的MongoDB服务器上运行你的测试,你应当排除内嵌的MongoDB自动配置: -```java -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 { - -} -``` -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataMongoTest`开启的自动配置列表。 \ No newline at end of file diff --git a/IV. Spring Boot features/42.3.12 Auto-configured Data Neo4j tests.md b/IV. Spring Boot features/42.3.12 Auto-configured Data Neo4j tests.md deleted file mode 100644 index 7c8c6d29..00000000 --- a/IV. Spring Boot features/42.3.12 Auto-configured Data Neo4j tests.md +++ /dev/null @@ -1,36 +0,0 @@ -### 42.3.12 自动配置的Data Neo4j测试 - -如果你想要测试Neo4j应用,你可以使用`@DataNeo4jTest`。默认的,它将会配置一个内存Neo4j(如果内嵌的驱动可用),扫描`@NodeEntity`类和配置Spring Data Neo4j仓库。常规的`@Component`bean将不会加载进`ApplicationContext`: -```java -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测试类是事务型的,默认在每个测试结束时回滚,具体查看Spring参考文档的[相关章节](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle#testcontext-tx-enabling-transactions)。如果这不是你想要的结果,你可以按如下方式对一个测试或是整个类禁用事务管理: -```java -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 { - -} -``` -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataNeo4jTest`开启的自动配置列表。 \ No newline at end of file diff --git a/IV. Spring Boot features/42.3.13 Auto-configured Data Redis tests.md b/IV. Spring Boot features/42.3.13 Auto-configured Data Redis tests.md deleted file mode 100644 index cb99bd67..00000000 --- a/IV. Spring Boot features/42.3.13 Auto-configured Data Redis tests.md +++ /dev/null @@ -1,20 +0,0 @@ -### 42.3.13 自动配置的Data Redis测试 - -如果你想要测试Redis应用,你可以使用`@DataRedisTest`。默认的,它将会扫描`@RedisHash`类和配置Spring Data Redis仓库。常规的`@Component`bean将不会加载进`ApplicationContext`: -```java -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; - - // -} -``` -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataRedisTest`开启的自动配置列表。 \ No newline at end of file diff --git a/IV. Spring Boot features/42.3.14 Auto-configured Data LDAP tests.md b/IV. Spring Boot features/42.3.14 Auto-configured Data LDAP tests.md deleted file mode 100644 index 67db937b..00000000 --- a/IV. Spring Boot features/42.3.14 Auto-configured Data LDAP tests.md +++ /dev/null @@ -1,35 +0,0 @@ -### 42.3.14 自动配置的Data LDAP测试 - -如果你想要测试LDAP应用,你可以使用`@DataLdapTest`。默认的,它将会配置一个内存LDAP(如果可用)、一个`@LdapTemplate`,扫描`@Entry`类和配置Spring Data LDAP仓库。常规的`@Component`bean将不会加载进`ApplicationContext`: -```java -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自动配置: -In-memory embedded LDAP 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 LDAP server you should exclude the embedded LDAP auto-configuration: -```java -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 { - -} -``` -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataLdapTest`开启的自动配置列表。 \ No newline at end of file diff --git a/IV. Spring Boot features/42.3.15 Auto-configured REST clients.md b/IV. Spring Boot features/42.3.15 Auto-configured REST clients.md deleted file mode 100644 index 2df38596..00000000 --- a/IV. Spring Boot features/42.3.15 Auto-configured REST clients.md +++ /dev/null @@ -1,25 +0,0 @@ -###42.3.15 自动配置的REST客户端 -你可以使用`@RestClientTest`测试REST客户端,它默认会自动配置Jackson和GSON,配置`RestTemplateBuilder`,并添加`MockRestServiceServer`支持。你需要将`@RestClientTest`的`value`或`components`属性值设置为待测试类: -```java -@RunWith(SpringRunner.class) -@RestClientTest(RemoteVehicleDetailsService.class) -public class ExampleRestClientTest { - - @Autowired - private RemoteVehicleDetailsService service; - - @Autowired - private MockRestServiceServer server; - - @Test - public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() - throws Exception { - this.server.expect(requestTo("/greet/details")) - .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN)); - String greeting = this.service.callRestService(); - assertThat(greeting).isEqualTo("hello"); - } - -} -``` -在[附录](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@RestClientTest`启用的自动配置列表。 diff --git a/IV. Spring Boot features/42.3.16 Auto-configured Spring REST Docs tests.md b/IV. Spring Boot features/42.3.16 Auto-configured Spring REST Docs tests.md deleted file mode 100644 index ae060274..00000000 --- a/IV. Spring Boot features/42.3.16 Auto-configured Spring REST Docs tests.md +++ /dev/null @@ -1,58 +0,0 @@ -###42.3.16 自动配置的Spring REST Docs测试 -如果想在测试类中使用Spring REST Docs,你可以使用`@AutoConfigureRestDocs`注解,它会自动配置`MockMvc`去使用Spring REST Docs,并移除对Spring REST Docs的JUnit规则的需要。 -```java -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`能够用于覆盖默认的输出目录(如果你使用的是Maven,默认的输出目录是`target/generated-snippets`。使用的是Gradle的话,就是`build/generated-snippets`)。`@AutoConfigureRestDocs`也能配置将出现在任何文档化的URLs中的部分,比如host,scheme和port等。如果需要控制更多Spring REST Docs的配置,你可以使用`RestDocsMockMvcConfigurationCustomizer` bean: -```java -@TestConfiguration -static class CustomizationConfiguration - implements RestDocsMockMvcConfigurationCustomizer { - - @Override - public void customize(MockMvcRestDocumentationConfigurer configurer) { - configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); - } - -} -``` -如果想充分利用Spring REST Docs对参数化输出目录的支持,你可以创建一个`RestDocumentationResultHandler` bean,自动配置将使用它调用`alwaysDo`方法,进而促使每个`MockMvc`调用都会自动产生默认片段: -```java -@TestConfiguration -static class ResultHandlerConfiguration { - - @Bean - public RestDocumentationResultHandler restDocumentation() { - return MockMvcRestDocumentation.document("{method-name}"); - } - -} -``` diff --git a/IV. Spring Boot features/42.3.17 Using Spock to test Spring Boot applications.md b/IV. Spring Boot features/42.3.17 Using Spock to test Spring Boot applications.md deleted file mode 100644 index 938f57d2..00000000 --- a/IV. Spring Boot features/42.3.17 Using Spock to test Spring Boot applications.md +++ /dev/null @@ -1,3 +0,0 @@ -###42.3.17 使用Spock测试Spring Boot应用 - -如果想使用Spock测试Spring Boot应用,你需要为应用添加Spock的`spock-spring`依赖,该依赖已将Spring测试框架集成进Spock。推荐使用Spock 1.1或之后的版本,以便获得最近关于Spock的Spring框架和Spring Boot的集成的大量改进。详细内容请查看[Spock的Spring模块的文档](http://spockframework.org/spock/docs/1.1/modules.html)。 \ No newline at end of file diff --git a/IV. Spring Boot features/42.3.2 Excluding test configuration.md b/IV. Spring Boot features/42.3.2 Excluding test configuration.md deleted file mode 100644 index e3ac160a..00000000 --- a/IV. Spring Boot features/42.3.2 Excluding test configuration.md +++ /dev/null @@ -1,19 +0,0 @@ -### 42.3.2 排除测试配置 - -如果应用使用组件扫描,比如`@SpringBootApplication`或`@ComponentScan`,你可能发现为测试类创建的顶级配置类在任何地方都可能偶然被扫描到。 - -向[上面看到](./42.3.1 Detecting test configuration.md)的那样,为了自定义原始的配置,`@TestConfiguration`可以用在一个测试的内部类上。当把`@TestConfiguration`放在顶级类上时,`@TestConfiguration`表明在`src/test/java`中的类扫描无效。你可以在需要的地方,明确地导入那个类: -```java -@RunWith(SpringRunner.class) -@SpringBootTest -@Import(MyTestsConfiguration.class) -public class MyTests { - - @Test - public void exampleTest() { - ... - } - -} -``` -**注** 如果直接使用`@ComponentScan`(比如不通过`@SpringBootApplication`),你需要为它注册`TypeExcludeFilter`,具体参考[Javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/context/TypeExcludeFilter.html)。 diff --git a/IV. Spring Boot features/42.3.3 Working with random ports.md b/IV. Spring Boot features/42.3.3 Working with random ports.md deleted file mode 100644 index e0773447..00000000 --- a/IV. Spring Boot features/42.3.3 Working with random ports.md +++ /dev/null @@ -1,32 +0,0 @@ -### 42.3.3 使用随机端口 - -如果你需要为测试启动一个完整运行的服务器,我们建议你使用随机端口。如果你使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`,每次运行测试都会为你分配一个可用的随机端口。 - -`@LocalServerPort`注解用于[注入测试用例实际使用的端口](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-discover-the-http-port-at-runtime),简单起见,需要发起REST调用到启动服务器的测试可以额外`@Autowire`一个`TestRestTemplate`,它可以解析到运行服务器的相关链接: -```java -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"); - } - -} -``` diff --git a/IV. Spring Boot features/42.3.4 Mocking and spying beans.md b/IV. Spring Boot features/42.3.4 Mocking and spying beans.md deleted file mode 100644 index 0541868d..00000000 --- a/IV. Spring Boot features/42.3.4 Mocking and spying beans.md +++ /dev/null @@ -1,39 +0,0 @@ -### 42.3.4 模拟和监视beans - -有时候需要在运行测试用例时mock一些组件,例如,你可能需要一些远程服务的门面,但在开发期间不可用。Mocking在模拟真实环境很难复现的失败情况时非常有用。 - -Spring Boot提供一个`@MockBean`注解,可用于为`ApplicationContext`中的bean定义一个Mockito mock,你可以使用该注解添加新beans,或替换已存在的bean定义。该注解可直接用于测试类,也可用于测试类的字段,或用于`@Configuration`注解的类和字段。当用于字段时,创建mock的实例也会被注入。Mock beans每次调用完测试方法后会自动重置。 - -下面是一个典型示例,演示使用mock实现替换真实存在的`RemoteService` bean: -```java -import org.junit.*; -import org.junit.runner.*; -import org.springframework.beans.factory.annotation.*; -import org.springframework.boot.test.context.*; -import org.springframework.boot.test.mock.mockito.*; -import org.springframework.test.context.junit4.*; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.BDDMockito.*; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class MyTests { - - @MockBean - private RemoteService remoteService; - - @Autowired - private Reverser reverser; - - @Test - public void exampleTest() { - // RemoteService has been injected into the reverser bean - given(this.remoteService.someCall()).willReturn("mock"); - String reverse = reverser.reverseSomeCall(); - assertThat(reverse).isEqualTo("kcom"); - } - -} -``` -此外,你可以使用`@SpyBean`和Mockito `spy`包装一个已存在的bean,具体参考文档。 diff --git a/IV. Spring Boot features/42.3.5 Auto-configured tests.md b/IV. Spring Boot features/42.3.5 Auto-configured tests.md deleted file mode 100644 index a2c2616f..00000000 --- a/IV. Spring Boot features/42.3.5 Auto-configured tests.md +++ /dev/null @@ -1,9 +0,0 @@ -### 42.3.5 自动配置测试 - -Spring Boot的自动配置系统对应用来说很合适,但用于测试就有点杀鸡用牛刀了,测试时只加载需要的应用片段(slice)通常是有好处的。例如,你可能想测试Spring MVC控制器映射URLs是否正确,且不想在这些测试中涉及到数据库调用;或者你想测试JPA实体,那测试运行时你可能对web层不感兴趣。 - -`spring-boot-test-autoconfigure`模块包含很多用来自动配置这些片段(slices)的注解,每个工作方式都相似,都是提供一个`@…Test`注解,然后加载`ApplicationContext`,使用一个或多个`@AutoConfigure…`注解自定义设置。 - -**注** 每个部分加载了自动配置类的一个非常受限的集合。如果你需要排除它们中的一个,大部分`@…​Test`注解提供了一个`excludeAutoConfiguration`属性。或者,你可以使用`@ImportAutoConfiguration#exclude`。 - -**注** `@AutoConfigure…`注解也可以跟标准的`@SpringBootTest`注解一块使用,如果对应用片段不感兴趣,只是想获取自动配置的一些测试beans,你可以使用该组合。 diff --git a/IV. Spring Boot features/42.3.6 Auto-configured JSON tests.md b/IV. Spring Boot features/42.3.6 Auto-configured JSON tests.md deleted file mode 100644 index c6ca809d..00000000 --- a/IV. Spring Boot features/42.3.6 Auto-configured JSON tests.md +++ /dev/null @@ -1,46 +0,0 @@ -###42.3.6 自动配置的JSON测试 -你可以使用`@JsonTest`测试对象JSON序列化和反序列化是否工作正常,该注解将自动配置Jackson `ObjectMapper`,`@JsonComponent`和Jackson `Modules`。如果碰巧使用gson代替Jackson,该注解将配置`Gson`。使用`@AutoConfigureJsonTesters`可以配置auto-configuration的元素。 - -Spring Boot提供基于AssertJ的帮助类(helpers),可用来配合JSONassert和JsonPath libraries检测JSON是否为期望的,`JacksonTester`,`GsonTester`,`BasicJsonTester`分别用于Jackson,Gson,Strings。当使用`@JsonTest`时,你可以在测试类中`@Autowired`任何helper字段: -```java -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 json; - - @Test - public void testSerialize() throws Exception { - VehicleDetails details = new VehicleDetails("Honda", "Civic"); - // Assert against a `.json` file in the same package as the test - assertThat(this.json.write(details)).isEqualToJson("expected.json"); - // Or use JSON path based assertions - assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); - assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") - .isEqualTo("Honda"); - } - - @Test - public void testDeserialize() throws Exception { - String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; - assertThat(this.json.parse(content)) - .isEqualTo(new VehicleDetails("Ford", "Focus")); - assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); - } - -} -``` -**注** JSON帮助类可用于标准单元测试类,如果没有使用`@JsonTest`,你需要在`@Before`方法中调用帮助类的`initFields`方法。 - -在[附录](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@JsonTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/42.3.7 Auto-configured Spring MVC tests.md b/IV. Spring Boot features/42.3.7 Auto-configured Spring MVC tests.md deleted file mode 100644 index 02381754..00000000 --- a/IV. Spring Boot features/42.3.7 Auto-configured Spring MVC tests.md +++ /dev/null @@ -1,77 +0,0 @@ -### 42.3.7 自动配置的Spring MVC测试 - -你可以使用`@WebMvcTest`检测Spring MVC控制器是否工作正常,该注解将自动配置Spring MVC设施,并且只扫描注解`@Controller`,`@ControllerAdvice`,`@JsonComponent`,`Filter`,`WebMvcConfigurer`和`HandlerMethodArgumentResolver`的beans,其他常规的`@Component` beans将不会被扫描。 - -通常`@WebMvcTest`只限于单个控制器(controller)使用,并结合`@MockBean`以提供需要的协作者(collaborators)的mock实现。`@WebMvcTest`也会自动配置`MockMvc`,Mock MVC为快速测试MVC控制器提供了一种强大的方式,并且不需要启动一个完整的HTTP服务器。 - -**注** 使用`@AutoConfigureMockMvc`注解一个non-`@WebMvcTest`的类(比如`SpringBootTest`)也可以自动配置`MockMvc`。 - -```java -import org.junit.*; -import org.junit.runner.*; -import org.springframework.beans.factory.annotation.*; -import org.springframework.boot.test.autoconfigure.web.servlet.*; -import org.springframework.boot.test.mock.mockito.*; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.BDDMockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -@RunWith(SpringRunner.class) -@WebMvcTest(UserVehicleController.class) -public class MyControllerTests { - - @Autowired - private MockMvc mvc; - - @MockBean - private UserVehicleService userVehicleService; - - @Test - public void testExample() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) - .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); - } - -} -``` -**注** 如果需要定义自定配置(auto-configuration)的元素(比如什么时候使用servlet filters),你可以使用`@AutoConfigureMockMvc`的属性。 - -如果你使用HtmlUnit或Selenium, 自动配置将提供一个`WebClient` bean和/或`WebDriver` bean,以下是使用HtmlUnit的示例: -```java -import com.gargoylesoftware.htmlunit.*; -import org.junit.*; -import org.junit.runner.*; -import org.springframework.beans.factory.annotation.*; -import org.springframework.boot.test.autoconfigure.web.servlet.*; -import org.springframework.boot.test.mock.mockito.*; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.BDDMockito.*; - -@RunWith(SpringRunner.class) -@WebMvcTest(UserVehicleController.class) -public class MyHtmlUnitTests { - - @Autowired - private WebClient webClient; - - @MockBean - private UserVehicleService userVehicleService; - - @Test - public void testExample() throws Exception { - given(this.userVehicleService.getVehicleDetails("sboot")) - .willReturn(new VehicleDetails("Honda", "Civic")); - HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); - assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); - } - -} -``` -**注** 默认地,为了确保驱动器在每个测试后停止,而且一个新的实例被注入,Spring Boot将会把`WebDriver`bean放在一个特殊的“作用域”里。如果你不想要这个行为,你可以在你的`WebDriver``@Bean`定义上加上`@Scope("singleton")`。 - -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@WebMvcTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/42.3.8 Auto-configured Data JPA tests.md b/IV. Spring Boot features/42.3.8 Auto-configured Data JPA tests.md deleted file mode 100644 index 714d3302..00000000 --- a/IV. Spring Boot features/42.3.8 Auto-configured Data JPA tests.md +++ /dev/null @@ -1,60 +0,0 @@ -### 42.3.8 自动配置的Data JPA测试 - -你可以使用`@DataJpaTest`测试JPA应用,它默认配置一个内存型的内嵌数据库,扫描`@Entity`类,并配置Spring Data JPA仓库,其他常规的`@Component` beans不会加载进`ApplicationContext`。 - -Data JPA测试类是事务型的,默认在每个测试结束时回滚,具体查看Spring参考文档的[相关章节](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle#testcontext-tx-enabling-transactions)。如果这不是你想要的结果,你可以按如下方式对一个测试或是整个类禁用事务管理: -```java -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 { - -} -``` -Data JPA测试类可能会注入一个专为测试设计的[`TestEntityManager`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java)bean以替换标准的JPA `EntityManager`。如果想在`@DataJpaTests`外使用`TestEntityManager`,你可以使用`@AutoConfigureTestEntityManager`注解。如果需要,`JdbcTemplate `也是可用的。 -```java -import org.junit.*; -import org.junit.runner.*; -import org.springframework.boot.test.autoconfigure.orm.jpa.*; - -import static org.assertj.core.api.Assertions.*; - -@RunWith(SpringRunner.class) -@DataJpaTest -public class ExampleRepositoryTests { - - @Autowired - private TestEntityManager entityManager; - - @Autowired - private UserRepository repository; - - @Test - public void testExample() throws Exception { - this.entityManager.persist(new User("sboot", "1234")); - User user = this.repository.findByUsername("sboot"); - assertThat(user.getUsername()).isEqualTo("sboot"); - assertThat(user.getVin()).isEqualTo("1234"); - } - -} -``` -对于测试来说,内存型的内嵌数据库通常是足够的,因为它们既快又不需要任何安装。如果比较喜欢在真实数据库上运行测试,你可以使用`@AutoConfigureTestDatabase`注解: -```java -@RunWith(SpringRunner.class) -@DataJpaTest -@AutoConfigureTestDatabase(replace=Replace.NONE) -public class ExampleRepositoryTests { - - // ... - -} -``` -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataJpaTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/42.3.9 Auto-configured JDBC tests.md b/IV. Spring Boot features/42.3.9 Auto-configured JDBC tests.md deleted file mode 100644 index d17c432b..00000000 --- a/IV. Spring Boot features/42.3.9 Auto-configured JDBC tests.md +++ /dev/null @@ -1,23 +0,0 @@ -### 42.3.9 自动配置的JDBC测试 - -`@JdbcTest`同`@DataJpaTest`相似,不过是给纯jdbc相关的测试用的。默认的,它将会配置一个内存数据库和一个`JdbcTemplate`。常规的`@Component`bean将不会加载进`ApplicationContext`。 - -JDBC测试类是事务型的,默认在每个测试结束时回滚,具体查看Spring参考文档的[相关章节](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle#testcontext-tx-enabling-transactions)。如果这不是你想要的结果,你可以按如下方式对一个测试或是整个类禁用事务管理: -```java -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 { - -} -``` -如果你更喜欢在非真实的数据库上运行你的测试,你可以和`DataJpaTest`一样,使用`@AutoConfigureTestDatabase`注解。 - -在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#test-auto-configuration)中可以查看`@JdbcTest`开启的自动配置列表。 \ No newline at end of file diff --git a/IV. Spring Boot features/42.4 Test utilities.md b/IV. Spring Boot features/42.4 Test utilities.md deleted file mode 100644 index 0ad2cda4..00000000 --- a/IV. Spring Boot features/42.4 Test utilities.md +++ /dev/null @@ -1,2 +0,0 @@ -### 42.4 测试工具类 -一些测试工具类也打包进了`spring-boot`,在测试时使用它们会有很大帮助。 diff --git a/IV. Spring Boot features/42.4.1 ConfigFileApplicationContextInitializer.md b/IV. Spring Boot features/42.4.1 ConfigFileApplicationContextInitializer.md deleted file mode 100644 index 2642847f..00000000 --- a/IV. Spring Boot features/42.4.1 ConfigFileApplicationContextInitializer.md +++ /dev/null @@ -1,8 +0,0 @@ -###42.4.1 ConfigFileApplicationContextInitializer - -`ConfigFileApplicationContextInitializer`是一个`ApplicationContextInitializer`,可在测试类中用于加载Spring Boot的`application.properties`文件。当不需要使用`@SpringBootTest`提供的全部特性时,你可以使用它。 - -```java -@ContextConfiguration(classes = Config.class,initializers = ConfigFileApplicationContextInitializer.class) -``` -**注** 单独使用`ConfigFileApplicationContextInitializer`不会提供`@Value("${…}")`注入支持,它只负责确保`application.properties`文件加载进Spring的`Environment`。为了`@Value`支持,你需要额外配置一个`PropertySourcesPlaceholderConfigurer`或使用`@SpringBootTest`为你自动配置一个。 diff --git a/IV. Spring Boot features/42.4.2 EnvironmentTestUtils.md b/IV. Spring Boot features/42.4.2 EnvironmentTestUtils.md deleted file mode 100644 index d39f8b37..00000000 --- a/IV. Spring Boot features/42.4.2 EnvironmentTestUtils.md +++ /dev/null @@ -1,4 +0,0 @@ -###42.4.2 EnvironmentTestUtils -使用简单的`key=value`字符串调用`EnvironmentTestUtils`就可以快速添加属性到`ConfigurableEnvironment`或`ConfigurableApplicationContext`: -```java -EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot"); diff --git a/IV. Spring Boot features/42.4.3 OutputCapture.md b/IV. Spring Boot features/42.4.3 OutputCapture.md deleted file mode 100644 index f2c31a51..00000000 --- a/IV. Spring Boot features/42.4.3 OutputCapture.md +++ /dev/null @@ -1,20 +0,0 @@ -###42.4.3 OutputCapture - -`OutputCapture`是JUnit的一个`Rule`,用于捕获`System.out`和`System.err`输出,只需简单的将`@Rule`注解capture,然后在断言中调用`toString()`: -```java -import org.junit.Rule; -import org.junit.Test; -import org.springframework.boot.test.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")); -} -} -``` diff --git a/IV. Spring Boot features/42.4.4 TestRestTemplate.md b/IV. Spring Boot features/42.4.4 TestRestTemplate.md deleted file mode 100644 index 48db185b..00000000 --- a/IV. Spring Boot features/42.4.4 TestRestTemplate.md +++ /dev/null @@ -1,50 +0,0 @@ -###42.4.4 TestRestTemplate -在集成测试中,`TestRestTemplate`是Spring `RestTemplate`的便利替代。你可以获取一个普通的或发送基本HTTP认证(使用用户名和密码)的模板,不管哪种情况, -这些模板都对测试友好,对于服务端错误不会抛出异常。推荐使用Apache HTTP Client(4.3.2或更高版本),但不强制这样做,如果相关库在classpath下存在,`TestRestTemplate`将以正确配置的client进行响应。如果你使用Apache的HTTP客户端,一些额外的测试友好的特性将会被启用: - -- 重定向不会被跟踪(所以你可以断言回应的位置) -- Cookies将会被忽略(所以模版是无状态的) - -`TestRestTemplate`能够在你的集成测试中被直接实例化: -```java -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")); - } - -} -``` -或者,如果你正在使用`@SpringBootTest`,且设置了`WebEnvironment.RANDOM_PORT`或`WebEnvironment.DEFINED_PORT`属性,你可以注入一个配置完全的`TestRestTemplate`,并开始使用它。如果有需要,你还可以通过`RestTemplateBuilder` bean进行额外的自定义。任何没有指定主机和端口的URL将会自动连接到内嵌的服务器: -```java -@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(...); - } - - } - -} -``` diff --git a/IV. Spring Boot features/43. Testing.md b/IV. Spring Boot features/43. Testing.md new file mode 100644 index 00000000..1ebd49e0 --- /dev/null +++ b/IV. Spring Boot features/43. Testing.md @@ -0,0 +1,5 @@ +### 43. 测试 + +Spring Boot提供很多有用的工具类和注解用于帮助你测试应用,主要分两个模块:`spring-boot-test`包含核心组件,`spring-boot-test-autoconfigure`为测试提供自动配置。 + +大多数开发者只需要引用`spring-boot-starter-test` “Starter”,它既提供Spring Boot测试模块,也提供JUnit,AssertJ,Hamcrest和很多有用的依赖。 diff --git a/IV. Spring Boot features/43. WebSockets.md b/IV. Spring Boot features/43. WebSockets.md deleted file mode 100644 index 64d7b979..00000000 --- a/IV. Spring Boot features/43. WebSockets.md +++ /dev/null @@ -1,2 +0,0 @@ -### 43. WebSockets -Spring Boot为内嵌的Tomcat(8和7),Jetty 9和Undertow提供WebSockets自动配置。如果你正在将war包部署到独立容器中,Spring Boot将假设该容器会负责配置WebSocket。Spring框架提供[丰富的WebSocket支持](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#websocket),只需要添加`spring-boot-starter-websocket`模块即可。 diff --git a/IV. Spring Boot features/43.1 Test Scope Dependencies.md b/IV. Spring Boot features/43.1 Test Scope Dependencies.md new file mode 100644 index 00000000..f716ae25 --- /dev/null +++ b/IV. Spring Boot features/43.1 Test Scope Dependencies.md @@ -0,0 +1,13 @@ +### 43.1 测试作用域依赖 + +`spring-boot-starter-test`“Starter”(在`test` `scope`内)包含下列库: + +- [JUnit](http://junit.org/):事实上的(de-facto)标准,用于Java应用的单元测试。 +- [Spring Test](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/testing.html#integration-testing) & Spring Boot Test:实用工具以及对Spring应用的集成测试支持。 +- [AssertJ](https://joel-costigliola.github.io/assertj/):一个流式断言库。 +- [Hamcrest](http://hamcrest.org/JavaHamcrest/):一个匹配对象的库(也称为约束或前置条件)。 +- [Mockito](http://mockito.org/):一个Java模拟框架。 +- [JSONassert](https://github.com/skyscreamer/JSONassert):一个针对JSON的断言库。 +- [JsonPath](https://github.com/jayway/JsonPath):用于JSON的XPath。 + +这是写测试用例经常用到的库,如果它们不能满足要求,你可以随意添加其他的依赖。 diff --git a/IV. Spring Boot features/43.2 Testing Spring Applications.md b/IV. Spring Boot features/43.2 Testing Spring Applications.md new file mode 100644 index 00000000..9fe1d611 --- /dev/null +++ b/IV. Spring Boot features/43.2 Testing Spring Applications.md @@ -0,0 +1,7 @@ +### 43.2 测试Spring应用 + +依赖注入主要优势之一就是它能够让你的代码更容易进行单元测试。你只需简单的通过`new`操作符实例化对象,甚至不需要涉及Spring,也可以使用模拟对象替换真正的依赖。 + +你常常需要超出单元测试,开始集成测试(涉及到Spring的`ApplicationContext`)。在执行集成测试时,不需要部署应用或连接到其他基础设施是非常有用的。Spring框架为实现这样的集成测试提供了一个专用的测试模块。通过声明`org.springframework:spring-test`的依赖,或使用`spring-boot-starter-test`“Starter”就可以使用它了。 + +如果以前没有使用过`spring-test`模块,可以查看Spring框架参考文档中的[相关章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/testing.html#testing)。 diff --git a/IV. Spring Boot features/43.3 Testing Spring Boot Applications.md b/IV. Spring Boot features/43.3 Testing Spring Boot Applications.md new file mode 100644 index 00000000..a0e2f731 --- /dev/null +++ b/IV. Spring Boot features/43.3 Testing Spring Boot Applications.md @@ -0,0 +1,23 @@ +### 43.3 测试Spring Boot应用 + +Spring Boot应用只是一个Spring `ApplicationContext`,所以在测试时对它只需要像处理普通Spring context那样即可。 + +**注** 只有使用`SpringApplication`创建上下文时,外部配置、日志和Spring Boot的其他特性才会默认安装在上下文里。 + +Spring Boot提供一个`@SpringBootTest`注解。当你需要Spring Boot特性时,它可以作为标准的`spring-test``@ContextConfiguration`注解的另一种选择。该组件通过`SpringApplication`创建用于测试的`ApplicationContext`。 + +你可以使用`@SpringBootTest`的`webEnvironment`属性定义怎么运行测试: + +* `MOCK`:加载`WebApplicationContext`,并提供一个mock servlet环境,使用该注解时内嵌servlet容器将不会启动。如果classpath下不存在servlet APIs,该模式将创建一个常规的non-web `ApplicationContext`。Can be used in conjunction with @AutoConfigureMockMvc for MockMvc -based testing of your application. + +* `RANDOM_PORT`:加载`ServletWebServerApplicationContext`,并提供一个真实的servlet环境。使用该模式内嵌容器将启动,并监听在一个随机端口。 + +* `DEFINED_PORT`:加载`ServletWebServerApplicationContext`,并提供一个真实的servlet环境。使用该模式内嵌容器将启动,并监听一个定义好的端口(比如`application.properties`中定义的或默认的`8080`端口)。 + +* `NONE`:使用`SpringApplication`加载一个`ApplicationContext`,但不提供任何servlet环境(不管是mock还是其他)。 + +**注** 如果你的测试标注了`@Transactional`,默认的,在每一个测试方法结束时,它将会回滚事务。如果你正是此种情况,而且用了`RANDOM_PORT`或是`DEFINED_PORT`,隐式提供了一个真实的servlet环境。那么,HTTP客户端和服务端跑在不同的线程上,因此在不同的事务里。在这种情况下,任何在服务端初始化的事务不会回滚。 + +**注** 除了`@SpringBootTest`,还有许多另外的注解被提供,用来测试应用的更多特定的部分。你可以在这一章里找到更多细节。 + +**注** 不要忘记在测试用例上添加`@RunWith(SpringRunner.class)`,否则该注解将被忽略。 diff --git a/IV. Spring Boot features/43.3.1 Detecting Web Application Type.md b/IV. Spring Boot features/43.3.1 Detecting Web Application Type.md new file mode 100644 index 00000000..ae2f04c3 --- /dev/null +++ b/IV. Spring Boot features/43.3.1 Detecting Web Application Type.md @@ -0,0 +1,11 @@ +### 43.3.1 检测网络应用类型 + +如果Spring MVC可用,一个常规的基于MVC的应用上下文会被配置好。如果你只有Spring WebFlux,我们会检测并配置一个基于WebFlux的应用上下文。 + +如果两个都有,Spring MVC优先。在这种情况下,如果你想要测试一个响应式的网络应用,你必须设置`spring.main.web-application-type`属性: + +```java +@RunWith(SpringRunner.class) +@SpringBootTest(properties = "spring.main.web-application-type=reactive") +public class MyWebFluxTests { ... } +``` diff --git a/IV. Spring Boot features/43.3.10 Auto-configured Data JPA Tests.md b/IV. Spring Boot features/43.3.10 Auto-configured Data JPA Tests.md new file mode 100644 index 00000000..2472a54f --- /dev/null +++ b/IV. Spring Boot features/43.3.10 Auto-configured Data JPA Tests.md @@ -0,0 +1,61 @@ +### 43.3.10 自动配置的Data JPA测试 + +你可以使用`@DataJpaTest`测试JPA应用。它默认配置一个内存型的内嵌数据库,扫描`@Entity`类,并配置Spring Data JPA仓库。其他常规的`@Component` beans不会加载进`ApplicationContext`。 + +Data JPA测试类是事务型的,默认在每个测试结束时回滚,具体查看Spring参考文档的[相关章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/testing.html#testcontext-tx-enabling-transactions)。如果这不是你想要的结果,你可以按如下方式对一个测试或是整个类禁用事务管理: +```java +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 { + +} +``` + +Data JPA测试类可能会注入一个专为测试设计的[`TestEntityManager`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManager.java)bean以替换标准的JPA `EntityManager`。如果想在`@DataJpaTests`外使用`TestEntityManager`,你可以使用`@AutoConfigureTestEntityManager`注解。如果需要,`JdbcTemplate `也是可用的。下面的例子展示了使用中的`@DataJpaTest`注解: +```java +import org.junit.*; +import org.junit.runner.*; +import org.springframework.boot.test.autoconfigure.orm.jpa.*; + +import static org.assertj.core.api.Assertions.*; + +@RunWith(SpringRunner.class) +@DataJpaTest +public class ExampleRepositoryTests { + + @Autowired + private TestEntityManager entityManager; + + @Autowired + private UserRepository repository; + + @Test + public void testExample() throws Exception { + this.entityManager.persist(new User("sboot", "1234")); + User user = this.repository.findByUsername("sboot"); + assertThat(user.getUsername()).isEqualTo("sboot"); + assertThat(user.getVin()).isEqualTo("1234"); + } + +} +``` +对于测试来说,内存型的内嵌数据库通常是足够的,因为它们既快又不需要任何安装。如果比较喜欢在真实数据库上运行测试,你可以使用`@AutoConfigureTestDatabase`注解。如下所示: +```java +@RunWith(SpringRunner.class) +@DataJpaTest +@AutoConfigureTestDatabase(replace=Replace.NONE) +public class ExampleRepositoryTests { + + // ... + +} +``` +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataJpaTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.11 Auto-configured JDBC Tests.md b/IV. Spring Boot features/43.3.11 Auto-configured JDBC Tests.md new file mode 100644 index 00000000..8dcfe314 --- /dev/null +++ b/IV. Spring Boot features/43.3.11 Auto-configured JDBC Tests.md @@ -0,0 +1,23 @@ +### 43.3.11 自动配置的JDBC测试 + +`@JdbcTest`同`@DataJpaTest`相似,不过是给纯JDBC相关的测试用的。默认的,它将会配置一个内存数据库和一个`JdbcTemplate`。常规的`@Component`bean将不会加载进`ApplicationContext`。 + +JDBC测试类是事务型的,默认在每个测试结束时回滚,具体查看Spring参考文档的[相关章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/testing.html#testcontext-tx-enabling-transactions)。如果这不是你想要的结果,你可以按如下方式对一个测试或是整个类禁用事务管理: +```java +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 { + +} +``` +如果你更喜欢在非真实的数据库上运行你的测试,你可以和`DataJpaTest`一样,使用`@AutoConfigureTestDatabase`注解。(查看[43.3.10 自动配置的Data JPA测试](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test)) + +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@JdbcTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.12 Auto-configured jOOQ Tests.md b/IV. Spring Boot features/43.3.12 Auto-configured jOOQ Tests.md new file mode 100644 index 00000000..161ae3fa --- /dev/null +++ b/IV. Spring Boot features/43.3.12 Auto-configured jOOQ Tests.md @@ -0,0 +1,24 @@ +### 43.3.12 自动配置的jOOQ测试 + +`@JooqTest`的使用方式同`@JdbcTest`相似,不过是给jOOQ相关的测试用的。由于jOOQ严重依靠与数据库模式相对应的基于Java的模式,既存的`DataSource`将会被使用。如果你想要用一个内存数据库代替它,你可以使用`@AutoconfigureTestDatabase`来覆盖那些设置。(在Spring Boot里使用jOOQ的更多信息,请查看[章节 29.5 使用jOOQ](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-jooq)。) + +`@JooqTest`将会配置一个`DSLContext`。常规的`@Component`bean将不会加载进`ApplicationContext`。下面的例子展示了使用中的`@JooqTest`注解: + +```java +import org.jooq.DSLContext; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.jooq.JooqTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@JooqTest +public class ExampleJooqTests { + + @Autowired + private DSLContext dslContext; +} +``` +JOOQ测试类是事务型的,默认在每个测试结束时回滚。如果这不是你想要的结果,你可以按照[JDBC例子中的方式](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-jdbc-test)对一个测试或是整个类禁用事务管理。 + +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@JooqTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.13 Auto-configured Data MongoDB Tests.md b/IV. Spring Boot features/43.3.13 Auto-configured Data MongoDB Tests.md new file mode 100644 index 00000000..7f41c7a2 --- /dev/null +++ b/IV. Spring Boot features/43.3.13 Auto-configured Data MongoDB Tests.md @@ -0,0 +1,36 @@ +### 43.3.13 自动配置的Data MongoDB测试 + +你可以使用`@DataMongoTest`测试MongoDB应用。默认的,它将会配置一个内存MongoDB(如果可用),配置一个`@MongoTemplate`,扫描`@Document`类和配置Spring Data MongoDB仓库。常规的`@Component`bean将不会加载进`ApplicationContext`。(在Spring Boot里使用MongoDB的更多信息,请查看[章节 30.2 MongoDB](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-mongodb)。) + +下面的例子展示了使用中的`@DataMongoTest`注解: +```java +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@DataMongoTest +public class ExampleDataMongoTests { + + @Autowired + private MongoTemplate mongoTemplate; + + // +} +``` +由于内存MongoDB快,而且不需要任何开发者安装,它总体上在测试中工作得很好。但是,如果你更喜欢在一个非真实的MongoDB服务器上运行你的测试,你应当排除内嵌的MongoDB自动配置。如下所示: +```java +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 { + +} +``` +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataMongoTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.14 Auto-configured Data Neo4j Tests.md b/IV. Spring Boot features/43.3.14 Auto-configured Data Neo4j Tests.md new file mode 100644 index 00000000..d77ffef3 --- /dev/null +++ b/IV. Spring Boot features/43.3.14 Auto-configured Data Neo4j Tests.md @@ -0,0 +1,38 @@ +### 43.3.14 自动配置的Data Neo4j测试 + +你可以使用`@DataNeo4jTest`测试Neo4j应用。默认的,它将会配置一个内存Neo4j(如果内嵌的驱动可用),扫描`@NodeEntity`类和配置Spring Data Neo4j仓库。常规的`@Component`bean将不会加载进`ApplicationContext`。(在Spring Boot里使用Neo4J的更多信息,请查看[章节 30.3 Neo4j](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-neo4j)。) + +下面的例子展示了在Spring Boot里使用Neo4J测试的典型设置: +```java +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测试类是事务型的,默认在每个测试结束时回滚,具体查看Spring参考文档的[相关章节](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/htmlsingle#testcontext-tx-enabling-transactions)。如果这不是你想要的结果,你可以按如下方式对一个测试或是整个类禁用事务管理: +```java +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 { + +} +``` +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataNeo4jTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.15 Auto-configured Data Redis Tests.md b/IV. Spring Boot features/43.3.15 Auto-configured Data Redis Tests.md new file mode 100644 index 00000000..b035c104 --- /dev/null +++ b/IV. Spring Boot features/43.3.15 Auto-configured Data Redis Tests.md @@ -0,0 +1,22 @@ +### 43.3.15 自动配置的Data Redis测试 + +你可以使用`@DataRedisTest`测试Redis应用。默认的,它将会扫描`@RedisHash`类和配置Spring Data Redis仓库。常规的`@Component`bean将不会加载进`ApplicationContext`。(在Spring Boot里使用Redis的更多信息,请查看[章节 30.1 Redis](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-redis)。) + +下面的例子展示了使用中的`@DataRedisTest`注解: +```java +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; + + // +} +``` +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataRedisTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.16 Auto-configured Data LDAP Tests.md b/IV. Spring Boot features/43.3.16 Auto-configured Data LDAP Tests.md new file mode 100644 index 00000000..a76a1e1d --- /dev/null +++ b/IV. Spring Boot features/43.3.16 Auto-configured Data LDAP Tests.md @@ -0,0 +1,37 @@ +### 43.3.16 自动配置的Data LDAP测试 + +你可以使用`@DataLdapTest`测试LDAP应用。默认的,它将会配置一个内存LDAP(如果可用)、一个`@LdapTemplate`,扫描`@Entry`类和配置Spring Data LDAP仓库。常规的`@Component`bean将不会加载进`ApplicationContext`。(在Spring Boot里使用LDAP的更多信息,请查看[章节 30.9 LDAP](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-ldap)。) + +下面的例子展示了使用中的`@DataLdapTest`注解: +```java +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自动配置。如下所示: +```java +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 { + +} +``` +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataLdapTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.17 Auto-configured REST Clients.md b/IV. Spring Boot features/43.3.17 Auto-configured REST Clients.md new file mode 100644 index 00000000..d60726a9 --- /dev/null +++ b/IV. Spring Boot features/43.3.17 Auto-configured REST Clients.md @@ -0,0 +1,26 @@ +### 43.3.17 自动配置的REST客户端 + +你可以使用`@RestClientTest`测试REST客户端。它默认会自动配置Jackson、GSON和Jsonb,配置`RestTemplateBuilder`,并添加`MockRestServiceServer`支持。你需要将`@RestClientTest`的`value`或`components`属性值设置为待测试类。如下所示: +```java +@RunWith(SpringRunner.class) +@RestClientTest(RemoteVehicleDetailsService.class) +public class ExampleRestClientTest { + + @Autowired + private RemoteVehicleDetailsService service; + + @Autowired + private MockRestServiceServer server; + + @Test + public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() + throws Exception { + this.server.expect(requestTo("/greet/details")) + .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN)); + String greeting = this.service.callRestService(); + assertThat(greeting).isEqualTo("hello"); + } + +} +``` +在[附录](http://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@RestClientTest`启用的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.18 Auto-configured Spring REST Docs Tests.md b/IV. Spring Boot features/43.3.18 Auto-configured Spring REST Docs Tests.md new file mode 100644 index 00000000..3a477949 --- /dev/null +++ b/IV. Spring Boot features/43.3.18 Auto-configured Spring REST Docs Tests.md @@ -0,0 +1,123 @@ +### 43.3.18 自动配置的Spring REST Docs测试 + +为了在测试里使用[Spring REST Docs](https://projects.spring.io/spring-restdocs/),你可以使用`@AutoConfigureRestDocs`注解。它移除了Spring REST Docs里对JUnit规则的需要。 + +`@AutoConfigureRestDocs`可用于覆盖默认的输出目录(如果你使用Maven,目录是`target/generated-snippets`。如果你使用Gradle,则是`build/generated-snippets`)。它也可以用于配置出现在任何文档化的URI里的主机、方案、端口。 + +**使用Mock MVC的自动配置的Spring REST Docs测试** + +`@AutoConfigureRestDocs`自定义`MockMvc` bean来使用Spring REST Docs。当你使用Mock MVC和Spring REST Docs时,你可以使用`@Autowired`将其注入,好在测试里使用。如下所示: +```java +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`能够用于覆盖默认的输出目录(如果你使用的是Maven,默认的输出目录是`target/generated-snippets`。使用的是Gradle的话,就是`build/generated-snippets`)。`@AutoConfigureRestDocs`也能配置将出现在任何文档化的URLs中的部分,比如host,scheme和port等。如果需要控制更多Spring REST Docs的配置,你可以使用`RestDocsMockMvcConfigurationCustomizer` bean: + +如果你需要控制更多的Spring REST Docs的配置,这些配置超出了`@AutoConfigureRestDocs`属性提供的范围。那么,你可以使用`RestDocsMockMvcConfigurationCustomizer` bean。如下所示: +```java +@TestConfiguration +static class CustomizationConfiguration + implements RestDocsMockMvcConfigurationCustomizer { + + @Override + public void customize(MockMvcRestDocumentationConfigurer configurer) { + configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); + } + +} +``` + +如果想充分利用Spring REST Docs对参数化输出目录的支持,你可以创建一个`RestDocumentationResultHandler` bean,自动配置将使用它调用`alwaysDo`方法,进而促使每个`MockMvc`调用都会自动产生默认片段。下面的例子展示了一个定义好的`RestDocumentationResultHandler`: +```java +@TestConfiguration +static class ResultHandlerConfiguration { + + @Bean + public RestDocumentationResultHandler restDocumentation() { + return MockMvcRestDocumentation.document("{method-name}"); + } + +} +``` + +**使用REST Assured的自动配置的Spring REST Docs测试** + +`@AutoConfigureRestDocs`创建了一个`RequestSpecification` bean,预配置为使用Spring REST Docs。当你使用REST Assured和Spring REST Docs时,你可以使用`@Autowired`将其注入,好在测试里使用。如下所示: + +```java +import io.restassured.specification.RequestSpecification; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@AutoConfigureRestDocs +public class UserDocumentationTests { + + @LocalServerPort + private int port; + + @Autowired + private RequestSpecification documentationSpec; + + @Test + public void listUsers() { + given(this.documentationSpec).filter(document("list-users")).when() + .port(this.port).get("/").then().assertThat().statusCode(is(200)); + } + +} +``` + +如果你需要控制更多的Spring REST Docs的配置,这些配置超出了`@AutoConfigureRestDocs`属性提供的范围。那么,你可以使用`RestDocsRestAssuredConfigurationCustomizer` bean。如下所示: +```java +@TestConfiguration +public static class CustomizationConfiguration + implements RestDocsRestAssuredConfigurationCustomizer { + + @Override + public void customize(RestAssuredRestDocumentationConfigurer configurer) { + configurer.snippets().withTemplateFormat(TemplateFormats.markdown()); + } + +} +``` diff --git a/IV. Spring Boot features/43.3.19 User Configuration and Slicing.md b/IV. Spring Boot features/43.3.19 User Configuration and Slicing.md new file mode 100644 index 00000000..7e37122c --- /dev/null +++ b/IV. Spring Boot features/43.3.19 User Configuration and Slicing.md @@ -0,0 +1,30 @@ +### 43.3.19 用户配置与切片 + +如果你合理地[组织你的代码](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-structuring-your-code),Spring Boot默认会把`@SpringBootApplication`类[当做测试的配置使用](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-detecting-config)。 + +所以,不要把针对特定功能区域的配置放置在应用的主类上。 + +假设你正在使用Spring Batch,并依赖自动配置。你会如下定义你的`@SpringBootApplication`: +```java +@SpringBootApplication +@EnableBatchProcessing +public class SampleApplication { ... } +``` +因为这个类是测试的源配置,任何切片测试实际上都会尝试启动Spring Batch。这肯定不是你想做的。一种推荐的方法是把那个针对特定区域的配置移到一个独立的在应用的同一级上的`@Configuration`类。如下所示: +```java +@Configuration +@EnableBatchProcessing +public class BatchConfiguration { ... } +``` + +**注** 根据应用的复杂度,你可能有一个定义所有配置的`@Configuration`类,或者每个域区域一个类。后面的方法让你在其中的一个测试里启用它。如果需要,加上`@Import`注解。 + +另一个困惑的根源是类路径扫描。假设你合理地组织了代码,你需要扫描一个额外的包。你的应用代码可能是这样的: +```java +@SpringBootApplication +@ComponentScan({ "com.example.app", "org.acme.another" }) +public class SampleApplication { ... } +``` +这样做实际上覆盖了默认的组件扫描指令,产生了不顾所选的切片而扫描那两个包的副作用。比如,`@DataJpaTest`突然扫描了应用的组件和用户配置。同样的,把自定义的指令移到独立的类上是修复此方法的好办法。 + +**注** 如果这不是你的一个选项,你可以在测试的某个层级里创建`@SpringBootConfiguration`。另外,你可以为你的测试指定一个源。这会禁用寻找默认源的行为。 diff --git a/IV. Spring Boot features/43.3.2 Detecting Test Configuration.md b/IV. Spring Boot features/43.3.2 Detecting Test Configuration.md new file mode 100644 index 00000000..7c8fb5ad --- /dev/null +++ b/IV. Spring Boot features/43.3.2 Detecting Test Configuration.md @@ -0,0 +1,13 @@ +### 43.3.2 检测测试配置 + +如果熟悉Spring测试框架,你可能经常通过`@ContextConfiguration(classes=…)`指定加载哪些Spring `@Configuration`,也可能经常在测试类中使用内嵌`@Configuration`类。 + +当测试Spring Boot应用时这些就不需要了,Spring Boot的`@*Test`注解会自动搜索主配置类,即使你没有显式定义它。 + +搜索算法是从包含测试类的包开始搜索,直到发现`@SpringBootApplication`或`@SpringBootConfiguration`注解的类,只要按[恰当的方式组织代码](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-structuring-your-code),通常都会发现主配置类。 + +**注** 如果你使用一个[测试注解来测试你应用的一个更加特定的部分](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-tests),你应当避免添加针对[main方法应用类](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-user-configuration)的特定区域的配置设置。 + +如果想自定义主配置类,你可以使用一个内嵌的`@TestConfiguration`类。不像内嵌的`@Configuration`类(会替换应用主配置类),内嵌的`@TestConfiguration`类是可以跟应用主配置类一块使用的。 + +**注** Spring测试框架在测试过程中会缓存应用上下文,因此,只要你的测试共享相同的配置(不管是怎么发现的),加载上下文的潜在时间消耗都只会发生一次。 diff --git a/IV. Spring Boot features/43.3.20 Using Spock to Test Spring Boot Applications.md b/IV. Spring Boot features/43.3.20 Using Spock to Test Spring Boot Applications.md new file mode 100644 index 00000000..5f68c43c --- /dev/null +++ b/IV. Spring Boot features/43.3.20 Using Spock to Test Spring Boot Applications.md @@ -0,0 +1,3 @@ +### 43.3.20 使用Spock测试Spring Boot应用 + +如果想使用Spock测试Spring Boot应用,你需要为应用添加Spock的`spock-spring`依赖。该依赖已将Spring测试框架集成进Spock。推荐使用Spock 1.1或之后的版本,以便获得关于Spock的Spring框架和Spring Boot的集成的大量改进。详细内容请查看[Spock的Spring模块的文档](http://spockframework.org/spock/docs/1.1/modules.html)。 diff --git a/IV. Spring Boot features/43.3.3 Excluding Test Configuration.md b/IV. Spring Boot features/43.3.3 Excluding Test Configuration.md new file mode 100644 index 00000000..6e8b0106 --- /dev/null +++ b/IV. Spring Boot features/43.3.3 Excluding Test Configuration.md @@ -0,0 +1,19 @@ +### 43.3.3 排除测试配置 + +如果应用使用组件扫描,比如`@SpringBootApplication`或`@ComponentScan`,你可能发现为测试类创建的顶级配置类在任何地方都可能偶然被扫描到。 + +向[上面看到](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-detecting-config)的那样,为了自定义原始的配置,`@TestConfiguration`可以用在一个测试的内部类上。当把`@TestConfiguration`放在顶级类上时,`@TestConfiguration`表明在`src/test/java`中的类扫描无效。你可以在需要的地方,明确地导入那个类: +```java +@RunWith(SpringRunner.class) +@SpringBootTest +@Import(MyTestsConfiguration.class) +public class MyTests { + + @Test + public void exampleTest() { + ... + } + +} +``` +**注** 如果直接使用`@ComponentScan`(比如不通过`@SpringBootApplication`),你需要为它注册`TypeExcludeFilter`,具体参考[Javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/context/TypeExcludeFilter.html)。 diff --git a/IV. Spring Boot features/43.3.4 Testing with a running server.md b/IV. Spring Boot features/43.3.4 Testing with a running server.md new file mode 100644 index 00000000..01477c46 --- /dev/null +++ b/IV. Spring Boot features/43.3.4 Testing with a running server.md @@ -0,0 +1,59 @@ +### 43.3.4 使用运行的服务器测试 + +如果你需要启动一个完整运行的服务器,我们建议你使用随机端口。如果你使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`,每次运行测试都会为你分配一个可用的随机端口。 + +`@LocalServerPort`注解用于[注入测试用例实际使用的端口](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-discover-the-http-port-at-runtime),简单起见,需要发起REST调用到启动服务器的测试可以额外`@Autowire`一个[`WebTestClient`](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/testing.html#webtestclient-tests),它可以解析到运行服务器的相关链接,并且带有验证响应的专用API。如下所示: +```java +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class RandomPortWebTestClientExampleTests { + + @Autowired + private WebTestClient webClient; + + @Test + public void exampleTest() { + this.webClient.get().uri("/").exchange().expectStatus().isOk() + .expectBody(String.class).isEqualTo("Hello World"); + } + +} +``` + +Spring Boot也提供了一个`TestRestTemplate`设施: +```java +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class RandomPortTestRestTemplateExampleTests { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void exampleTest() { + String body = this.restTemplate.getForObject("/", String.class); + assertThat(body).isEqualTo("Hello World"); + } + +} +``` diff --git a/IV. Spring Boot features/43.3.5 Mocking and Spying Beans.md b/IV. Spring Boot features/43.3.5 Mocking and Spying Beans.md new file mode 100644 index 00000000..e9bb1d15 --- /dev/null +++ b/IV. Spring Boot features/43.3.5 Mocking and Spying Beans.md @@ -0,0 +1,47 @@ +### 43.3.5 模拟和监视bean + +有时候需要在运行测试用例时mock一些组件,例如,你可能需要一些远程服务的门面,但在开发期间不可用。Mocking在模拟真实环境很难复现的失败情况时非常有用。 + +Spring Boot提供一个`@MockBean`注解,可用于为`ApplicationContext`中的bean定义一个Mockito mock,你可以使用该注解添加新beans,或替换已存在的bean定义。该注解可直接用于测试类,也可用于测试类的字段,或用于`@Configuration`注解的类和字段。当用于字段时,创建mock的实例也会被注入。Mock bean每次调用完测试方法后会自动重置。 + +**注** 如果你的测试使用了Spring Boot的测试注解(比如`@SpringBootTest`),这个特性会被自动启用。要换一种方式使用这个特性的话,需要明确地添加一个监听器。如下所示: +```java +@TestExecutionListeners(MockitoTestExecutionListener.class) +``` + +下面的示例使用mock实现替换存在的`RemoteService` bean: +```java +import org.junit.*; +import org.junit.runner.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.context.*; +import org.springframework.boot.test.mock.mockito.*; +import org.springframework.test.context.junit4.*; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.BDDMockito.*; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class MyTests { + + @MockBean + private RemoteService remoteService; + + @Autowired + private Reverser reverser; + + @Test + public void exampleTest() { + // RemoteService has been injected into the reverser bean + given(this.remoteService.someCall()).willReturn("mock"); + String reverse = reverser.reverseSomeCall(); + assertThat(reverse).isEqualTo("kcom"); + } + +} +``` + +此外,你可以使用`@SpyBean`,来用Mockito`spy`包装任何已存在的bean。具体参考[Javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/test/mock/mockito/SpyBean.html)。 + +**注** Spring的测试框架会缓存测试之间应用上下文,并为共享相同配置的测试重用上下文。使用`@MockBean`或者`@SpyBean`会影响缓存键,很可能会增加上下文的数量。 diff --git a/IV. Spring Boot features/43.3.6 Auto-configured Tests.md b/IV. Spring Boot features/43.3.6 Auto-configured Tests.md new file mode 100644 index 00000000..5358c860 --- /dev/null +++ b/IV. Spring Boot features/43.3.6 Auto-configured Tests.md @@ -0,0 +1,9 @@ +### 43.3.6 自动配置测试 + +Spring Boot的自动配置系统对应用来说很合适,但用于测试就有点杀鸡用牛刀了,测试时只加载需要的应用片段(slice)通常是有好处的。例如,你可能想测试Spring MVC控制器映射URLs是否正确,且不想在这些测试中涉及到数据库调用。或者,你想测试JPA实体,那测试运行时你可能对web层不感兴趣。 + +`spring-boot-test-autoconfigure`模块包含很多用来自动配置这些片段(slices)的注解,每个工作方式都相似,都是提供一个`@…Test`注解,然后加载`ApplicationContext`,使用一个或多个`@AutoConfigure…`注解自定义设置。 + +**注** 每个部分加载了自动配置类的一个非常受限的集合。如果你需要排除它们中的一个,大部分`@…Test`注解提供了一个`excludeAutoConfiguration`属性。或者,你可以使用`@ImportAutoConfiguration#exclude`。 + +**注** `@AutoConfigure…`注解也可以跟标准的`@SpringBootTest`注解一块使用,如果对应用片段不感兴趣,只是想获取自动配置的一些测试beans,你可以使用该组合。 diff --git a/IV. Spring Boot features/43.3.7 Auto-configured JSON Tests.md b/IV. Spring Boot features/43.3.7 Auto-configured JSON Tests.md new file mode 100644 index 00000000..4fe88c17 --- /dev/null +++ b/IV. Spring Boot features/43.3.7 Auto-configured JSON Tests.md @@ -0,0 +1,54 @@ +### 43.3.7 自动配置的JSON测试 + +你可以使用`@JsonTest`测试对象JSON序列化和反序列化是否工作正常。该注解将自动配置支持JSON映射器的可用库。可以是下列库里的一种: + +- `Jackson ObjectMapper`,任何`@JsonComponent` bean,任何Jackson `模块` +- `Gson` +- `Jsonb` + +使用`@AutoConfigureJsonTesters`可以配置auto-configuration的元素。 + +Spring Boot提供基于AssertJ的帮助类(helpers),可用来配合JSONassert和JsonPath库检测JSON是否和期望的一样。`JacksonTester`、`GsonTester`、`JsonbTester`和`BasicJsonTester`分别用于Jackson、Gson、Jsonb、Strings。当使用`@JsonTest`时,你可以在测试类中`@Autowired`任何helper字段。下面的例子展示了一个用于Jackson的测试类: +```java +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 json; + + @Test + public void testSerialize() throws Exception { + VehicleDetails details = new VehicleDetails("Honda", "Civic"); + // Assert against a `.json` file in the same package as the test + assertThat(this.json.write(details)).isEqualToJson("expected.json"); + // Or use JSON path based assertions + assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); + assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") + .isEqualTo("Honda"); + } + + @Test + public void testDeserialize() throws Exception { + String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; + assertThat(this.json.parse(content)) + .isEqualTo(new VehicleDetails("Ford", "Focus")); + assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); + } + +} +``` + +**注** JSON帮助类可用于标准单元测试类,如果没有使用`@JsonTest`,你需要在`@Before`方法中调用帮助类的`initFields`方法。 + +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@JsonTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/43.3.8 Auto-configured Spring MVC Tests.md b/IV. Spring Boot features/43.3.8 Auto-configured Spring MVC Tests.md new file mode 100644 index 00000000..3e44f9e2 --- /dev/null +++ b/IV. Spring Boot features/43.3.8 Auto-configured Spring MVC Tests.md @@ -0,0 +1,82 @@ +### 43.3.8 自动配置的Spring MVC测试 + +你可以使用`@WebMvcTest`检测Spring MVC控制器是否工作正常。该注解将自动配置Spring MVC设施,并且只扫描注解`@Controller`、`@ControllerAdvice`、`@JsonComponent`、`Converter`、`GenericConverter`、`Filter`、`WebMvcConfigurer`和`HandlerMethodArgumentResolver`的bean。其他常规的`@Component` bean将不会被扫描。 + +**注** 如果你需要注册额外的组件,比如Jackson`模块`,你可以在你的测试上使用`@Import`来导入另外的配置类。 + +通常`@WebMvcTest`只限于单个控制器(controller)使用,并结合`@MockBean`以提供需要的协作者(collaborators)的mock实现。`@WebMvcTest`也会自动配置`MockMvc`,Mock MVC为快速测试MVC控制器提供了一种强大的方式,并且不需要启动一个完整的HTTP服务器。 + +**注** 使用`@AutoConfigureMockMvc`注解一个non-`@WebMvcTest`的类(比如`@SpringBootTest`)也可以自动配置`MockMvc`。下面的例子使用了`MockMvc`: + +```java +import org.junit.*; +import org.junit.runner.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.autoconfigure.web.servlet.*; +import org.springframework.boot.test.mock.mockito.*; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@WebMvcTest(UserVehicleController.class) +public class MyControllerTests { + + @Autowired + private MockMvc mvc; + + @MockBean + private UserVehicleService userVehicleService; + + @Test + public void testExample() throws Exception { + given(this.userVehicleService.getVehicleDetails("sboot")) + .willReturn(new VehicleDetails("Honda", "Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); + } + +} +``` +**注** 如果需要定义自定配置(auto-configuration)的元素(比如什么时候使用servlet filters),你可以使用`@AutoConfigureMockMvc`的属性。 + +如果你使用HtmlUnit或Selenium, 自动配置将提供一个HTMLUnit `WebClient` bean和/或`WebDriver` bean,以下是使用HtmlUnit的示例: +```java +import com.gargoylesoftware.htmlunit.*; +import org.junit.*; +import org.junit.runner.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.autoconfigure.web.servlet.*; +import org.springframework.boot.test.mock.mockito.*; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.BDDMockito.*; + +@RunWith(SpringRunner.class) +@WebMvcTest(UserVehicleController.class) +public class MyHtmlUnitTests { + + @Autowired + private WebClient webClient; + + @MockBean + private UserVehicleService userVehicleService; + + @Test + public void testExample() throws Exception { + given(this.userVehicleService.getVehicleDetails("sboot")) + .willReturn(new VehicleDetails("Honda", "Civic")); + HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); + assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); + } + +} +``` + +**注** 默认地,为了确保驱动器在每个测试后退出,而且一个新的实例被注入,Spring Boot将会把`WebDriver`bean放在一个特殊的“作用域”里。如果你不想要这个行为,你可以在你的`WebDriver``@Bean`定义上加上`@Scope("singleton")`。 + +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@WebMvcTest`开启的自动配置列表。 + +**注** 有时,光光编写Spring MVC测试是不够的。Spring Boot可以帮助你[在实际的服务器上运行完整的端到端的测试](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-running-server)。 diff --git a/IV. Spring Boot features/43.3.9 Auto-configured Spring WebFlux Tests.md b/IV. Spring Boot features/43.3.9 Auto-configured Spring WebFlux Tests.md new file mode 100644 index 00000000..293a48cf --- /dev/null +++ b/IV. Spring Boot features/43.3.9 Auto-configured Spring WebFlux Tests.md @@ -0,0 +1,48 @@ +### 43.3.9 自动配置的Spring WebFlux测试 + +你可以使用`@WebFluxTest`检测[Spring WebFlux](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference//web-reactive.html)控制器是否工作正常。该注解将自动配置Spring WebFlux设施,并且只扫描注解`@Controller`、`@ControllerAdvice`、`@JsonComponent`、`Converter`、`GenericConverter`、`Filter`和`WebFluxConfigurer`的bean。其他常规的`@Component` bean将不会被扫描。 + +**注** 如果你需要注册额外的组件,比如Jackson`模块`,你可以在你的测试上使用`@Import`来导入另外的配置类。 + +通常`@WebFluxTest`只限于单个控制器(controller)使用,并结合`@MockBean`以提供需要的协作者(collaborators)的mock实现。 + +`@WebFluxTest`也会自动配置[`WebTestClient`](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/testing.html#webtestclient)。WebTestClient为快速测试WebFlux控制器提供了一种强大的方式,并且不需要启动一个完整的HTTP服务器。 + +**注** 使用`@AutoConfigureWebTestClient`注解一个non-`@WebFluxTest`的类(比如`@SpringBootTest`)也可以自动配置`WebTestClient`。下面的例子展示了一个同时使用`@WebFluxTest`和`WebTestClient`的类: + +```java +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@WebFluxTest(UserVehicleController.class) +public class MyControllerTests { + + @Autowired + private WebTestClient webClient; + + @MockBean + private UserVehicleService userVehicleService; + + @Test + public void testExample() throws Exception { + given(this.userVehicleService.getVehicleDetails("sboot")) + .willReturn(new VehicleDetails("Honda", "Civic")); + this.webClient.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo("Honda Civic"); + } + +} +``` + +在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@WebFluxTest`开启的自动配置列表。 + +**注** 有时,光光编写Spring MVC测试是不够的。Spring Boot可以帮助你[在实际的服务器上运行完整的端到端的测试](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-running-server)。 diff --git a/IV. Spring Boot features/43.4 Test Utilities.md b/IV. Spring Boot features/43.4 Test Utilities.md new file mode 100644 index 00000000..ecb015a7 --- /dev/null +++ b/IV. Spring Boot features/43.4 Test Utilities.md @@ -0,0 +1,3 @@ +### 43.4 测试工具类 + +一些测试工具类也打包进了`spring-boot`,在测试时使用它们会有很大帮助。 diff --git a/IV. Spring Boot features/43.4.1 ConfigFileApplicationContextInitializer.md b/IV. Spring Boot features/43.4.1 ConfigFileApplicationContextInitializer.md new file mode 100644 index 00000000..aae8889c --- /dev/null +++ b/IV. Spring Boot features/43.4.1 ConfigFileApplicationContextInitializer.md @@ -0,0 +1,8 @@ +### 43.4.1 ConfigFileApplicationContextInitializer + +`ConfigFileApplicationContextInitializer`是一个`ApplicationContextInitializer`,可在测试类中用于加载Spring Boot的`application.properties`文件。当不需要使用`@SpringBootTest`提供的全部特性时,你可以使用它。如下所示: +```java +@ContextConfiguration(classes = Config.class,initializers = ConfigFileApplicationContextInitializer.class) +``` + +**注** 单独使用`ConfigFileApplicationContextInitializer`不会提供`@Value("${…}")`注入支持,它只负责确保`application.properties`文件加载进Spring的`Environment`。为了`@Value`支持,你需要额外配置一个`PropertySourcesPlaceholderConfigurer`或使用`@SpringBootTest`为你自动配置一个。 diff --git a/IV. Spring Boot features/43.4.2 EnvironmentTestUtils.md b/IV. Spring Boot features/43.4.2 EnvironmentTestUtils.md new file mode 100644 index 00000000..8689fca6 --- /dev/null +++ b/IV. Spring Boot features/43.4.2 EnvironmentTestUtils.md @@ -0,0 +1,6 @@ +### 43.4.2 EnvironmentTestUtils + +使用简单的`key=value`字符串调用`EnvironmentTestUtils`就可以快速添加属性到`ConfigurableEnvironment`或`ConfigurableApplicationContext`: +```java +EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot"); +``` diff --git a/IV. Spring Boot features/43.4.3 OutputCapture.md b/IV. Spring Boot features/43.4.3 OutputCapture.md new file mode 100644 index 00000000..ec2f1f25 --- /dev/null +++ b/IV. Spring Boot features/43.4.3 OutputCapture.md @@ -0,0 +1,24 @@ +### 43.4.3 OutputCapture + +`OutputCapture`是JUnit的一个`Rule`,用于捕获`System.out`和`System.err`输出。你可以将`@Rule`注解capture,然后在断言中调用`toString()`。如下所示: +```java +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")); + } + +} +``` diff --git a/IV. Spring Boot features/43.4.4 TestRestTemplate.md b/IV. Spring Boot features/43.4.4 TestRestTemplate.md new file mode 100644 index 00000000..e6a9fb9f --- /dev/null +++ b/IV. Spring Boot features/43.4.4 TestRestTemplate.md @@ -0,0 +1,52 @@ +### 43.4.4 TestRestTemplate + +**注** Spring Framework 5.0提供了一个新的`WebTestClient`。它服务于[WebFlux集成测试](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-webflux-tests)与[WebFlux与MVC端到端测试](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-running-server)。不像`TestRestTemplate`,它为断言提供了流畅的API。 + +在集成测试中,`TestRestTemplate`是Spring `RestTemplate`的便利替代。你可以获取一个普通的或发送基本HTTP认证(使用用户名和密码)的模板。不管哪种情况,这些模板都对测试友好,对于服务端错误不会抛出异常。推荐使用Apache HTTP Client(4.3.2或更高版本),但不强制这样做。如果相关库在classpath下存在,`TestRestTemplate`将以正确配置的client进行响应。如果你使用Apache的HTTP客户端,一些额外的测试友好的特性将会被启用: + +- 重定向不会被跟踪(所以你可以断言回应的位置) +- Cookies将会被忽略(所以模版是无状态的) + +`TestRestTemplate`能够在你的集成测试中被直接实例化: +```java +public class MyTest { + + private TestRestTemplate template = new TestRestTemplate(); + + @Test + public void testRequest() throws Exception { + HttpHeaders headers = this.template.getForEntity( + "http://myhost.example.com/example", String.class).getHeaders(); + assertThat(headers.getLocation()).hasHost("other.example.com"); + } + +} +``` +或者,如果你正在使用`@SpringBootTest`,且设置了`WebEnvironment.RANDOM_PORT`或`WebEnvironment.DEFINED_PORT`属性,你可以注入一个配置完全的`TestRestTemplate`,并开始使用它。如果有需要,你还可以通过`RestTemplateBuilder` bean进行额外的自定义。任何没有指定主机和端口的URL将会自动连接到内嵌的服务器: +```java +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SampleWebClientTests { + + @Autowired + private TestRestTemplate template; + + @Test + public void testRequest() { + HttpHeaders headers = this.template.getForEntity("/example", String.class) + .getHeaders(); + assertThat(headers.getLocation()).hasHost("other.example.com"); + } + + @TestConfiguration + static class Config { + + @Bean + public RestTemplateBuilder restTemplateBuilder() { + return new RestTemplateBuilder().setConnectTimeout(1000).setReadTimeout(1000); + } + + } + +} +``` diff --git a/IV. Spring Boot features/44. Web Services.md b/IV. Spring Boot features/44. Web Services.md deleted file mode 100644 index b901dfe0..00000000 --- a/IV. Spring Boot features/44. Web Services.md +++ /dev/null @@ -1,2 +0,0 @@ -###44. Web Services -Spring Boot提供Web Services自动配置,你需要的就是定义`Endpoints`。通过添加`spring-boot-starter-webservices`模块可以获取[Spring Web Services特性](http://docs.spring.io/spring-ws/docs/2.3.0.RELEASE/reference/htmlsingle)。 diff --git a/IV. Spring Boot features/44. WebSockets.md b/IV. Spring Boot features/44. WebSockets.md new file mode 100644 index 00000000..654350d0 --- /dev/null +++ b/IV. Spring Boot features/44. WebSockets.md @@ -0,0 +1,3 @@ +### 44. WebSockets + +Spring Boot为内嵌的Tomcat 8.5、Jetty 9和Undertow提供WebSockets自动配置。如果你正在将war包部署到独立容器中,Spring Boot将假设该容器会负责配置WebSocket。Spring框架提供[丰富的WebSocket支持](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#websocket),只需要添加`spring-boot-starter-websocket`模块即可。 diff --git a/IV. Spring Boot features/45. Creating your own auto-configuration.md b/IV. Spring Boot features/45. Creating your own auto-configuration.md deleted file mode 100644 index 917591be..00000000 --- a/IV. Spring Boot features/45. Creating your own auto-configuration.md +++ /dev/null @@ -1,4 +0,0 @@ -###45. 创建自己的auto-configuration -如果你在公司里开发共享libraries,或者正在开发一个开源或商业library,你可能想开发自己的自动配置(auto-configuration)。自动配置类可以打包到外部jars,并且依旧可以被Spring Boot识别。自动配置可以关联一个"starter",用于提供auto-configuration的代码及需要引用的libraries。我们首先讲解构建自己的auto-configuration需要知道哪些内容,然后讲解[创建自定义starter的常见步骤](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-custom-starter)。 - -**注** 可参考[demo工程](https://github.com/snicoll-demos/spring-boot-master-auto-configuration)了解如何一步步创建一个starter。 diff --git a/IV. Spring Boot features/45. Web Services.md b/IV. Spring Boot features/45. Web Services.md new file mode 100644 index 00000000..28094c52 --- /dev/null +++ b/IV. Spring Boot features/45. Web Services.md @@ -0,0 +1,8 @@ +### 45. Web Services + +Spring Boot提供Web Services自动配置,你需要的就是定义`Endpoints`。通过添加`spring-boot-starter-webservices`模块可以获取[Spring Web Services特性](https://docs.spring.io/spring-ws/docs/3.0.0.RELEASE/reference/)。 + +Spring Boot会自动为你的WSDL和XSD各自创建`SimpleWsdl11Definition`和`SimpleXsdSchema` bean。如下,配置它们的位置: +```properties +spring.webservices.wsdl-locations=classpath:/wsdl +``` diff --git a/IV. Spring Boot features/45.1 Understanding auto-configured beans.md b/IV. Spring Boot features/45.1 Understanding auto-configured beans.md deleted file mode 100644 index c377c411..00000000 --- a/IV. Spring Boot features/45.1 Understanding auto-configured beans.md +++ /dev/null @@ -1,2 +0,0 @@ -###45.1 理解自动配置的beans -从底层来讲,自动配置(auto-configuration)是通过标准的`@Configuration`类实现的。此外,`@Conditional`注解用来约束自动配置生效的条件。通常自动配置类需要使用`@ConditionalOnClass`和`@ConditionalOnMissingBean`注解,这是为了确保只有在相关的类被发现及没有声明自定义的`@Configuration`时才应用自动配置,具体查看[`spring-boot-autoconfigure`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure)源码中的`@Configuration`类(`META-INF/spring.factories`文件)。 diff --git a/IV. Spring Boot features/45.2 Locating auto-configuration candidates.md b/IV. Spring Boot features/45.2 Locating auto-configuration candidates.md deleted file mode 100644 index a72bac0c..00000000 --- a/IV. Spring Boot features/45.2 Locating auto-configuration candidates.md +++ /dev/null @@ -1,12 +0,0 @@ -###45.2 定位自动配置候选者 -Spring Boot会检查你发布的jar中是否存在`META-INF/spring.factories`文件,该文件中以`EnableAutoConfiguration`为key的属性应该列出你的配置类: -```java -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\ -com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration -``` -你可以使用[`@AutoConfigureAfter`](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigureAfter.java)或[`@AutoConfigureBefore`](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigureBefore.java)注解为配置类指定特定的顺序。例如,如果你提供web-specific配置,你的类就需要应用在`WebMvcAutoConfiguration`后面。 - -你也可以使用`@AutoconfigureOrder`注解为那些相互不知道存在的自动配置类提供排序,该注解语义跟常规的`@Order`注解相同,但专为自动配置类提供顺序。 - -**注** 自动配置类只能通过这种方式加载,确保它们定义在一个特殊的package中,特别是不能成为组件扫描的目标。 diff --git a/IV. Spring Boot features/45.3 Condition annotations.md b/IV. Spring Boot features/45.3 Condition annotations.md deleted file mode 100644 index 0c2cd03c..00000000 --- a/IV. Spring Boot features/45.3 Condition annotations.md +++ /dev/null @@ -1,5 +0,0 @@ -### 45.3 条件注解 - -你几乎总是需要在自己的自动配置类里添加一个或更多的`@Conditional`注解。`@ConditionalOnMissingBean`注解是一个常见的示例,开发者可以用它覆盖自动配置类提供的默认行为。 - -Spring Boot包含很多`@Conditional`注解,你可以在自己的代码中通过注解`@Configuration`类或单独的`@Bean`方法来重用它们。 diff --git a/IV. Spring Boot features/45.3.1 Class conditions.md b/IV. Spring Boot features/45.3.1 Class conditions.md deleted file mode 100644 index 11352520..00000000 --- a/IV. Spring Boot features/45.3.1 Class conditions.md +++ /dev/null @@ -1,5 +0,0 @@ -### 45.3.1 Class条件 - -`@ConditionalOnClass`和`@ConditionalOnMissingClass`注解可以根据特定类是否出现来决定配置的包含,由于注解元数据是使用[ASM](http://asm.ow2.org/)来解析的,所以你可以使用`value`属性来引用真正的类,即使该类没有出现在运行应用的classpath下,也可以使用`name`属性如果你倾向于使用字符串作为类名。 - -**提示** 如果你正在使用`@ConditionalOnClass`或者`@ConditionalOnMissingClass`,作为元注解的一部分来构成你自己的注解,你必须使用`name`。因为在这种情况下指向class没有被处理。 diff --git a/IV. Spring Boot features/45.3.2 Bean conditions.md b/IV. Spring Boot features/45.3.2 Bean conditions.md deleted file mode 100644 index b5d8c3d9..00000000 --- a/IV. Spring Boot features/45.3.2 Bean conditions.md +++ /dev/null @@ -1,20 +0,0 @@ -### 45.3.2 Bean条件 - -`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解可以根据特定类是否存在决定bean的包含,你可以使用`value`属性指定beans(by type),也可以使用`name`定义beans(by name),`search`属性用于限制搜索beans时需要考虑的`ApplicationContext`层次。 - -当被放置在一个`@Bean`方法时,目标类型默认为方法的返回类型,例如: -```java -@Configuration -public class MyAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - public MyService myService() { ... } - -} -``` -在上面的例子中,如果`ApplicationContext`里没有类型为`MyService`的bean,那么`myService`bean将会被创建。 - -**注** 你需要注意bean定义添加的顺序,因为这些条件的计算是基于目前处理内容的。出于这个原因,我们推荐在自动配置类上只使用`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解(即使保证它们在其他用户定义的beans后加载)。 - -**注** `@ConditionalOnBean`和`@ConditionalOnMissingBean`不会阻止`@Configuration`类的创建,在类级别使用那些conditions跟使用注解标记每个`@Bean`方法是等价的。 diff --git a/IV. Spring Boot features/45.3.3 Property conditions.md b/IV. Spring Boot features/45.3.3 Property conditions.md deleted file mode 100644 index c5f3b23a..00000000 --- a/IV. Spring Boot features/45.3.3 Property conditions.md +++ /dev/null @@ -1,2 +0,0 @@ -###45.3.3 Property条件 -`@ConditionalOnProperty`注解可以根据一个Spring `Environment`属性来决定是否包含配置,使用`prefix`和`name`属性指定要检查的配置。默认情况下,任何存在的只要不是`false`的属性都会匹配,你也可以使用`havingValue`和`matchIfMissing`属性创建更高级的检测。 diff --git a/IV. Spring Boot features/45.3.4 Resource conditions.md b/IV. Spring Boot features/45.3.4 Resource conditions.md deleted file mode 100644 index e73bdd98..00000000 --- a/IV. Spring Boot features/45.3.4 Resource conditions.md +++ /dev/null @@ -1,2 +0,0 @@ -###45.3.4 Resource条件 -`@ConditionalOnResource`注解只在特定资源出现时才会包含配置,可以使用常见的Spring约定命名资源,例如`file:/home/user/test.dat`。 diff --git a/IV. Spring Boot features/45.3.5 Web Application Conditions.md b/IV. Spring Boot features/45.3.5 Web Application Conditions.md deleted file mode 100644 index 1fd1e46f..00000000 --- a/IV. Spring Boot features/45.3.5 Web Application Conditions.md +++ /dev/null @@ -1,2 +0,0 @@ -###45.3.5 Web Application条件 -`@ConditionalOnWebApplication`和`@ConditionalOnNotWebApplication`注解可以根据应用是否为'web应用'来决定是否包含配置,web应用是任何使用Spring `WebApplicationContext`,定义一个`session`作用域,或有一个`StandardServletEnvironment`的应用。 diff --git a/IV. Spring Boot features/45.3.6 SpEL expression conditions.md b/IV. Spring Boot features/45.3.6 SpEL expression conditions.md deleted file mode 100644 index 36bf6edd..00000000 --- a/IV. Spring Boot features/45.3.6 SpEL expression conditions.md +++ /dev/null @@ -1,2 +0,0 @@ -###45.3.6 SpEL表达式条件 -`@ConditionalOnExpression`注解可以根据[SpEL表达式](https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/htmlsingle/#expressions)结果来决定是否包含配置。 diff --git a/IV. Spring Boot features/45.4 Creating your own starter.md b/IV. Spring Boot features/45.4 Creating your own starter.md deleted file mode 100644 index 421b3b9b..00000000 --- a/IV. Spring Boot features/45.4 Creating your own starter.md +++ /dev/null @@ -1,7 +0,0 @@ -###45.4 创建自己的starter -一个完整的Spring Boot starter可能包含以下组件: - -* `autoconfigure`模块,包含自动配置类的代码。 -* `starter`模块,提供自动配置模块及其他有用的依赖,简而言之,添加本starter就能开始使用该library。 - -**注** 如果不需要将它们分离开来,你可以将自动配置代码和依赖管理放到一个单一模块中。 diff --git a/IV. Spring Boot features/45.4.1 Naming.md b/IV. Spring Boot features/45.4.1 Naming.md deleted file mode 100644 index 59b68797..00000000 --- a/IV. Spring Boot features/45.4.1 Naming.md +++ /dev/null @@ -1,8 +0,0 @@ -###45.4.1 命名 -确保为你的starter提供一个合适的命名空间(namespace),模块名不要以`spring-boot`作为开头,尽管使用一个不同的Maven groupId,未来我们可能会为你正在做的自动配置提供官方支持。 - -这里是经验之谈,假设你正在为“acme”创建一个starter,命名自动配置模块为`acme-spring-boot-autoconfigure`,命名starter为`acme-spring-boot-starter`,如果只有一个模块结合它们,通常会使用`acme-spring-boot-starter`。 - -此外,如果你的starter提供配置keys,需要为它们提供一个合适的命名空间,特别是不要使用Spring Boot的命名空间(比如,`server`,`management`,`spring`等),这些是属于Spring Boot的,我们可能会在将来以相同方式提高/修改它们,这可能会破坏你的东西。 - -确保[触发meta-data生成](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#configuration-metadata-annotation-processor),这样IDE辅助也就可以用于你的keys了,你可能想检查生成的元数据(`META-INF/spring-configuration-metadata.json`)以确保keys被正确的文档化。 diff --git a/IV. Spring Boot features/45.4.2 Autoconfigure module.md b/IV. Spring Boot features/45.4.2 Autoconfigure module.md deleted file mode 100644 index de0ffcea..00000000 --- a/IV. Spring Boot features/45.4.2 Autoconfigure module.md +++ /dev/null @@ -1,4 +0,0 @@ -###45.4.2 自动配置模块 -自动配置模块包含了使用该library需要的任何东西,它可能还包含配置的keys定义(`@ConfigurationProperties`)和用于定义组件如何初始化的回调接口。 - -**注** 你需要将对该library的依赖标记为可选的,这样在项目中添加该自动配置模块就更容易了。如果你这样做,该library将不会提供,Spring Boot会回退到默认设置。 diff --git a/IV. Spring Boot features/45.4.3 Starter module.md b/IV. Spring Boot features/45.4.3 Starter module.md deleted file mode 100644 index 099b1e1b..00000000 --- a/IV. Spring Boot features/45.4.3 Starter module.md +++ /dev/null @@ -1,2 +0,0 @@ -###45.4.3 Starter模块 -starter模块实际是一个空jar,它的目的是提供使用该library所需的必要依赖。不要对添加你的starter的项目做任何假设,如果你正在自动配置的library需要其他starters,一定要提到它。提供一个合适的默认依赖集可能比较困难,特别是存在大量可选依赖时,你应该避免引入任何非必需的依赖。 diff --git a/IV. Spring Boot features/46. Creating Your Own Auto-configuration.md b/IV. Spring Boot features/46. Creating Your Own Auto-configuration.md new file mode 100644 index 00000000..a9cdf0f0 --- /dev/null +++ b/IV. Spring Boot features/46. Creating Your Own Auto-configuration.md @@ -0,0 +1,5 @@ +### 46. 创建自己的自动配置 + +如果你在公司里开发共享库,或者正在开发一个开源或商业库,你可能想开发自己的自动配置(auto-configuration)。自动配置类可以打包到外部jars,并且依旧可以被Spring Boot识别。自动配置可以关联一个“starter”,用于提供自动配置的代码及需要引用的libraries。我们首先讲解构建自己的自动配置需要知道哪些内容,然后讲解[创建自定义starter的常见步骤](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-custom-starter)。 + +**注** 可参考[demo工程](https://github.com/snicoll-demos/spring-boot-master-auto-configuration)了解如何一步步创建一个starter。 diff --git a/IV. Spring Boot features/46. What to read next.md b/IV. Spring Boot features/46. What to read next.md deleted file mode 100644 index bd871fa6..00000000 --- a/IV. Spring Boot features/46. What to read next.md +++ /dev/null @@ -1,4 +0,0 @@ -### 46. 接下来阅读什么 -如果想了解本章节讨论类的更多内容,你可以查看[Spring Boot API文档](http://docs.spring.io/spring-boot/docs/2.0.0.M5/api),或直接浏览[源码](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5)。如果有特别问题,可以参考[how-to](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto)章节。 - -如果已熟悉Spring Boot的核心特性,你可以继续并查看[production-ready特性](http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#production-ready)。 diff --git a/IV. Spring Boot features/46.1 Understanding Auto-configured Beans.md b/IV. Spring Boot features/46.1 Understanding Auto-configured Beans.md new file mode 100644 index 00000000..8928a33e --- /dev/null +++ b/IV. Spring Boot features/46.1 Understanding Auto-configured Beans.md @@ -0,0 +1,3 @@ +### 46.1 理解自动配置的bean + +从底层来讲,自动配置(auto-configuration)是通过标准的`@Configuration`类实现的。此外,`@Conditional`注解用来约束自动配置生效的条件。通常自动配置类需要使用`@ConditionalOnClass`和`@ConditionalOnMissingBean`注解,这是为了确保只有在相关的类被发现及没有声明自定义的`@Configuration`时才应用自动配置,具体查看[`spring-boot-autoconfigure`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure)源码中的`@Configuration`类([`META-INF/spring.factories`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories)文件)。 diff --git a/IV. Spring Boot features/46.2 Locating Auto-configuration Candidates.md b/IV. Spring Boot features/46.2 Locating Auto-configuration Candidates.md new file mode 100644 index 00000000..bef18013 --- /dev/null +++ b/IV. Spring Boot features/46.2 Locating Auto-configuration Candidates.md @@ -0,0 +1,13 @@ +### 46.2 定位自动配置候选者 + +Spring Boot会检查你发布的jar中是否存在`META-INF/spring.factories`文件,该文件中以`EnableAutoConfiguration`为key的属性应该列出你的配置类。如下所示: +```java +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.mycorp.libx.autoconfigure.LibXAutoConfiguration,\ +com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration +``` +你可以使用[`@AutoConfigureAfter`](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigureAfter.java)或[`@AutoConfigureBefore`](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigureBefore.java)注解为配置类指定特定的顺序。例如,如果你提供web-specific配置,你的类就需要应用在`WebMvcAutoConfiguration`后面。 + +你也可以使用`@AutoConfigureOrder`注解为那些相互不知道存在的自动配置类提供排序,该注解语义跟常规的`@Order`注解相同,但专为自动配置类提供顺序。 + +**注** 自动配置类只能通过这种方式加载,确保它们定义在一个特殊的package中,特别是不能成为组件扫描的目标。 diff --git a/IV. Spring Boot features/46.3 Condition Annotations.md b/IV. Spring Boot features/46.3 Condition Annotations.md new file mode 100644 index 00000000..572fcc03 --- /dev/null +++ b/IV. Spring Boot features/46.3 Condition Annotations.md @@ -0,0 +1,12 @@ +### 46.3 条件注解 + +你几乎总是需要在自己的自动配置类里添加一个或更多的`@Conditional`注解。`@ConditionalOnMissingBean`注解是一个常见的示例,开发者可以用它覆盖自动配置类提供的默认行为。 + +Spring Boot包含很多`@Conditional`注解,你可以在自己的代码中通过注解`@Configuration`类或单独的`@Bean`方法来重用它们。这些注解包括: + +- [46.3.1 Class条件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-class-conditions) +- [46.3.2 Bean条件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-bean-conditions) +- [46.3.3 Property条件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-property-conditions) +- [46.3.4 Resource条件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-resource-conditions) +- [46.3.5 Web Application条件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-web-application-conditions) +- [46.3.6 SpEL表达式条件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-spel-conditions) diff --git a/IV. Spring Boot features/46.3.1 Class Conditions.md b/IV. Spring Boot features/46.3.1 Class Conditions.md new file mode 100644 index 00000000..42e1af88 --- /dev/null +++ b/IV. Spring Boot features/46.3.1 Class Conditions.md @@ -0,0 +1,5 @@ +### 46.3.1 Class条件 + +`@ConditionalOnClass`和`@ConditionalOnMissingClass`注解可以根据特定类是否出现来决定配置的包含。由于注解元数据是使用[ASM](http://asm.ow2.org/)来解析的,所以你可以使用`value`属性来引用真正的类。即使该类没有出现在运行应用的classpath下,也可以使用`name`属性如果你倾向于使用字符串作为类名。 + +**提示** 如果你正在使用`@ConditionalOnClass`或者`@ConditionalOnMissingClass`,作为元注解的一部分来构成你自己的注解,你必须使用`name`。因为在这种情况下指向class没有被处理。 diff --git a/IV. Spring Boot features/46.3.2 Bean Conditions.md b/IV. Spring Boot features/46.3.2 Bean Conditions.md new file mode 100644 index 00000000..60f76469 --- /dev/null +++ b/IV. Spring Boot features/46.3.2 Bean Conditions.md @@ -0,0 +1,20 @@ +### 46.3.2 Bean条件 + +`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解可以根据特定类是否存在决定bean的包含,你可以使用`value`属性指定beans(by type),也可以使用`name`定义beans(by name),`search`属性用于限制搜索beans时需要考虑的`ApplicationContext`层次。 + +当被放置在一个`@Bean`方法时,目标类型默认为方法的返回类型,例如: +```java +@Configuration +public class MyAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public MyService myService() { ... } + +} +``` +在上面的例子中,如果`ApplicationContext`里没有类型为`MyService`的bean,那么`myService`bean将会被创建。 + +**注** 你需要注意bean定义添加的顺序,因为这些条件的计算是基于目前处理内容的。出于这个原因,我们推荐在自动配置类上只使用`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解(即使保证它们在其他用户定义的beans后加载)。 + +**注** `@ConditionalOnBean`和`@ConditionalOnMissingBean`不会阻止`@Configuration`类的创建,在类级别使用那些conditions跟使用注解标记每个`@Bean`方法是等价的。 diff --git a/IV. Spring Boot features/46.3.3 Property Conditions.md b/IV. Spring Boot features/46.3.3 Property Conditions.md new file mode 100644 index 00000000..2da008a0 --- /dev/null +++ b/IV. Spring Boot features/46.3.3 Property Conditions.md @@ -0,0 +1,3 @@ +### 46.3.3 Property条件 + +`@ConditionalOnProperty`注解可以根据一个Spring `Environment`属性来决定是否包含配置,使用`prefix`和`name`属性指定要检查的配置。默认情况下,任何存在的只要不是`false`的属性都会匹配,你也可以使用`havingValue`和`matchIfMissing`属性创建更高级的检测。 diff --git a/IV. Spring Boot features/46.3.4 Resource Conditions.md b/IV. Spring Boot features/46.3.4 Resource Conditions.md new file mode 100644 index 00000000..901b3a3a --- /dev/null +++ b/IV. Spring Boot features/46.3.4 Resource Conditions.md @@ -0,0 +1,3 @@ +### 46.3.4 Resource条件 + +`@ConditionalOnResource`注解只在特定资源出现时才会包含配置,可以使用常见的Spring约定命名资源,例如`file:/home/user/test.dat`。 diff --git a/IV. Spring Boot features/46.3.5 Web Application Conditions.md b/IV. Spring Boot features/46.3.5 Web Application Conditions.md new file mode 100644 index 00000000..656a9430 --- /dev/null +++ b/IV. Spring Boot features/46.3.5 Web Application Conditions.md @@ -0,0 +1,3 @@ +### 46.3.5 Web Application条件 + +`@ConditionalOnWebApplication`和`@ConditionalOnNotWebApplication`注解可以根据应用是否为“web应用”来决定是否包含配置。web应用是任何使用Spring `WebApplicationContext`,定义一个`session`作用域,或有一个`StandardServletEnvironment`的应用。 diff --git a/IV. Spring Boot features/46.3.6 SpEL Expression Conditions.md b/IV. Spring Boot features/46.3.6 SpEL Expression Conditions.md new file mode 100644 index 00000000..18b23b3a --- /dev/null +++ b/IV. Spring Boot features/46.3.6 SpEL Expression Conditions.md @@ -0,0 +1,3 @@ +### 46.3.6 SpEL表达式条件 + +`@ConditionalOnExpression`注解可以根据[SpEL表达式](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/core.html#expressions)结果来决定是否包含配置。 diff --git a/IV. Spring Boot features/46.4 Testing your Auto-configuration.md b/IV. Spring Boot features/46.4 Testing your Auto-configuration.md new file mode 100644 index 00000000..08d31bdb --- /dev/null +++ b/IV. Spring Boot features/46.4 Testing your Auto-configuration.md @@ -0,0 +1,45 @@ +### 46.4 测试你的自动配置 + +自动配置会受很多因素影响:用户配置(`@Bean`定义与`Environment`自定义)、状况评估(存在特定库)等。具体地,每个测试应当创建一个定义良好的`ApplicationContext`。它代表了那些自定义的结合。`ApplicationContextRunner`提供了达成这种目标的好办法。 + +`ApplicationContextRunner`经常会定义成测试类的实例变量,用来收集基础的、普遍的配置。下面的例子确保了`UserServiceAutoConfiguration`总是会被调用: +```java +private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(UserServiceAutoConfiguration.class)); +``` + +**注** 如果不得不定义多个自动配置,不需要对它们的声明排序,因为会和应用运行时完全相同的顺序调用它们。 + +每个测试可以使用runner代表一个特殊的使用案例。例如,下面的样本调用了一个用户配置(`UserConfiguration`),并且检查自动配置是否没有采用。调用`run`方法提供了一个回调上下文。它可以与`Assert4J`一起使用。 +```java +@Test +public void defaultServiceBacksOff() { + this.contextRunner.withUserConfiguration(UserConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(UserService.class); + assertThat(context.getBean(UserService.class)).isSameAs( + context.getBean(UserConfiguration.class).myUserService()); + }); +} + +@Configuration +static class UserConfiguration { + + @Bean + public UserService myUserService() { + return new UserService("mine"); + } + +} +``` + +也可以很容易地自定义`Environment`。如下所示: +```java +@Test +public void serviceNameCanBeConfigured() { + this.contextRunner.withPropertyValues("user.name=test123").run((context) -> { + assertThat(context).hasSingleBean(UserService.class); + assertThat(context.getBean(UserService.class).getName()).isEqualTo("test123"); + }); +} +``` diff --git a/IV. Spring Boot features/46.4.1 Simulating a Web Context.md b/IV. Spring Boot features/46.4.1 Simulating a Web Context.md new file mode 100644 index 00000000..204451ec --- /dev/null +++ b/IV. Spring Boot features/46.4.1 Simulating a Web Context.md @@ -0,0 +1,3 @@ +### 46.4.1 模拟网络上下文 + +如果你需要测试一个只在Servlet和Reactive网络应用上下文里操作的自动配置,分别使用`WebApplicationContextRunner`和`ReactiveWebApplicationContextRunner`。 diff --git a/IV. Spring Boot features/46.4.2 Overriding the Classpath.md b/IV. Spring Boot features/46.4.2 Overriding the Classpath.md new file mode 100644 index 00000000..05690db4 --- /dev/null +++ b/IV. Spring Boot features/46.4.2 Overriding the Classpath.md @@ -0,0 +1,10 @@ +### 46.4.2 覆盖类路径 + +测试当一个特殊的类或者包在运行时不存在的时候会发生什么也是可能的。Spring Boot提供了`FilteredClassLoader`。runner可以容易的使用它。在下面的例子里,我们断言如果`UserService`不存在,自动配置会正确地禁用: +```java +@Test +public void serviceIsIgnoredIfLibraryIsNotPresent() { + this.contextRunner.withClassLoader(new FilteredClassLoader(UserService.class)) + .run((context) -> assertThat(context).doesNotHaveBean("userService")); +} +``` diff --git a/IV. Spring Boot features/46.5 Creating Your Own Starter.md b/IV. Spring Boot features/46.5 Creating Your Own Starter.md new file mode 100644 index 00000000..dc88d4dd --- /dev/null +++ b/IV. Spring Boot features/46.5 Creating Your Own Starter.md @@ -0,0 +1,8 @@ +### 46.5 创建自己的starter + +一个完整的Spring Boot starter可能包含以下组件: + +* `autoconfigure`模块,包含自动配置类的代码。 +* `starter`模块,提供自动配置模块及其他有用的依赖,简而言之,添加本starter就能开始使用该library。 + +**注** 如果不需要将它们分离开来,你可以将自动配置代码和依赖管理放到一个单一模块中。 diff --git a/IV. Spring Boot features/46.5.1 Naming.md b/IV. Spring Boot features/46.5.1 Naming.md new file mode 100644 index 00000000..91c643ce --- /dev/null +++ b/IV. Spring Boot features/46.5.1 Naming.md @@ -0,0 +1,9 @@ +### 46.5.1 命名 + +你应该确保为你的starter提供一个合适的命名空间。即使使用一个不同的Maven groupId,模块名也不要以`spring-boot`作为开头。未来我们可能会为你正在做的自动配置提供官方支持。 + +这里是经验之谈:你应该在starter之后命名一个组合模块。例如,假设你正在为“acme”创建一个starter,命名自动配置模块为`acme-spring-boot-autoconfigure`,命名starter为`acme-spring-boot-starter`。如果只有一个模块结合它们,通常会使用`acme-spring-boot-starter`。 + +此外,如果你的starter提供配置key,需要为它们提供一个唯一的命名空间,特别是不要使用Spring Boot的命名空间(比如,`server`、`management`、`spring`等)。我们可能会在将来修改它们。如果你使用相同的命名空间,这可能会破坏你的模块。 + +确保[触发meta-data生成](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#configuration-metadata-annotation-processor),这样IDE辅助也就可以用于你的key了。你可能想检查生成的元数据(`META-INF/spring-configuration-metadata.json`)以确保key被正确的文档化。 diff --git a/IV. Spring Boot features/46.5.2 Autoconfigure Module.md b/IV. Spring Boot features/46.5.2 Autoconfigure Module.md new file mode 100644 index 00000000..d5423cfd --- /dev/null +++ b/IV. Spring Boot features/46.5.2 Autoconfigure Module.md @@ -0,0 +1,5 @@ +### 46.5.2 自动配置模块 + +自动配置模块包含了使用该library需要的任何东西,它可能还包含配置的key定义(例如`@ConfigurationProperties`)和用于定义组件如何初始化的回调接口。 + +**注** 你需要将对该library的依赖标记为可选的,这样在项目中添加该自动配置模块就更容易了。如果你这样做,该library将不会提供,Spring Boot会回退到默认设置。 diff --git a/IV. Spring Boot features/46.5.3 Starter Module.md b/IV. Spring Boot features/46.5.3 Starter Module.md new file mode 100644 index 00000000..f5865571 --- /dev/null +++ b/IV. Spring Boot features/46.5.3 Starter Module.md @@ -0,0 +1,7 @@ +### 46.5.3 Starter模块 + +starter模块实际是一个空jar。它的目的是提供使用该library所需的必要依赖。 + +不要对添加你的starter的项目做任何假设。如果你正在自动配置的library需要其他starter,一定要提到它。提供一个合适的默认依赖集可能比较困难,特别是存在大量可选依赖时,你应该避免引入任何非必需的依赖。换句话说,不应当包含可选的依赖。 + +**注** 无论哪种方式,你的starter必须直接或间接(如果你的starter依赖另外的starter,就不需要添加)地引用核心的Spring Boot starter(`spring-boot-starter`)。 如果一个项目只用你自定义的starter创建,Spring Boot的核心特性会因为核心starter的存在而启用。 diff --git a/IV. Spring Boot features/47. Kotlin support.md b/IV. Spring Boot features/47. Kotlin support.md new file mode 100644 index 00000000..edd7cfcb --- /dev/null +++ b/IV. Spring Boot features/47. Kotlin support.md @@ -0,0 +1,7 @@ +### 47. Kotlin支持 + +[Kotlin](https://kotlinlang.org/)是一种面向JVM(以及其它平台)的静态类型语言。它允许编写简洁优雅的代码,并且提供了与既存Java库的[互操作性](https://kotlinlang.org/docs/reference/java-interop.html)。 + +Spring Boot通过利用Spring Framework、Spring Data和Reactor等其它Spring项目中的支持来提供Kotlin支持。更多信息请查看[Spring框架Kotlin支持文档](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/languages.html#kotlin)。 + +通过[start.spring.io](https://start.spring.io/#!language=kotlin)创建项目是开始使用Spring Boot与Kotlin的最简单方式。如果你需要帮助,欢迎加入[Kotlin Slack](http://slack.kotlinlang.org/)的#spring频道。或者在[Stack Overflow](https://stackoverflow.com/questions/tagged/spring+kotlin)上带上`spring`与`kotlin`标签问问题。 diff --git a/IV. Spring Boot features/47.1 Requirements.md b/IV. Spring Boot features/47.1 Requirements.md new file mode 100644 index 00000000..1128c007 --- /dev/null +++ b/IV. Spring Boot features/47.1 Requirements.md @@ -0,0 +1,9 @@ +### 47.1 要求 + +Spring Boot支持Kotlin 1.2.x。要使用Kotlin的话,类路径上必须存在`org.jetbrains.kotlin:kotlin-stdlib`和`org.jetbrains.kotlin:kotlin-reflect`。也可以使用`kotlin-stdlib`的变体`kotlin-stdlib-jdk7`与`kotlin-stdlib-jdk8`。 + +由于[Kotlin类默认是final的](https://discuss.kotlinlang.org/t/classes-final-by-default/166),你可能想要配置[kotlin-spring](https://kotlinlang.org/docs/reference/compiler-plugins.html#spring-support)插件,好自动打开Spring注解的类。这样,它们就能被代理了。 + +在Kotlin里序列化/反序列化JSON数据需要[Jackson’s Kotlin模块](https://github.com/FasterXML/jackson-module-kotlin)。类路径上存在时,它会被自动注册。如果存在Jackson和Kotlin,却没有Jackson Kotlin模块,会打印出一条警告信息。 + +**注** 如果你使用[start.spring.io](https://start.spring.io/#!language=kotlin)开始你的Kotlin项目,默认会提供这些依赖和插件。 diff --git a/IV. Spring Boot features/47.2 Null-safety.md b/IV. Spring Boot features/47.2 Null-safety.md new file mode 100644 index 00000000..1646a5f5 --- /dev/null +++ b/IV. Spring Boot features/47.2 Null-safety.md @@ -0,0 +1,9 @@ +### 47.2 空安全 + +[空安全](https://kotlinlang.org/docs/reference/null-safety.html)是Kotlin的关键特性之一。它会在编译时处理`null`值,而不是等到运行时才处理然后不幸遇到了`NullPointerException`。这有助于消除一个普遍的bug源头,并且不需要花费包装器的开销,比如`Optional`。Kotlin也允许使用带有可空值的函数式的构造器。就像[Kotlin里空安全的全面指南](http://www.baeldung.com/kotlin-null-safety)里描述的那样。 + +尽管Java不允许在它的类型系统里表达空安全,Spring框架、Spring Data和Reactor现在通过工具友好的注解,提供了它们API的空安全。默认的,Kotlin里使用的来自Java API的类型被认为是[平台类型](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types)。平台类型的null检查是宽松的。[对JSR 305注解的Kotlin支持](https://kotlinlang.org/docs/reference/java-interop.html#jsr-305-support)连同为空性注解,提供了Kotlin里相关Spring API的空安全。 + +JSR 305检查可以通过添加`-Xjsr305`编译器标记配置。该标识可以是以下选项:`-Xjsr305={strict|warn|ignore}`。默认行为与`-Xjsr305=warn`相同。由Spring API推断来的Kotlin类型考虑空安全需要`strict`值。但是应当在具备以下认识的情况下使用:Spring API可空性声明甚至会在小版本发布之间进化,并且可能会在未来加入更多的检查。 + +**警告** 泛型参数、可变参数和数组元素的可空性还不被支持。最新信息请查看[SPR-15942](https://jira.spring.io/browse/SPR-15942)。Spring Boot自己的API[也还没有被注解](https://github.com/spring-projects/spring-boot/issues/10712). diff --git a/IV. Spring Boot features/47.3.1 runApplication.md b/IV. Spring Boot features/47.3.1 runApplication.md new file mode 100644 index 00000000..ffc62b95 --- /dev/null +++ b/IV. Spring Boot features/47.3.1 runApplication.md @@ -0,0 +1,20 @@ +### 47.3.1 runApplication + +Spring Boot提供了用`runApplication(*args)`运行应用的惯用方式。如下所示: +```java +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class FooApplication + +fun main(args: Array) { + runApplication(*args) +} +``` +这是`SpringApplication.run(FooApplication::class.java, *args)`的替代品。它也允许自定义应用。如下所示: +```java +runApplication(*args) { + setBannerMode(OFF) +} +``` diff --git a/IV. Spring Boot features/47.3.2 Extensions.md b/IV. Spring Boot features/47.3.2 Extensions.md new file mode 100644 index 00000000..9296f918 --- /dev/null +++ b/IV. Spring Boot features/47.3.2 Extensions.md @@ -0,0 +1,5 @@ +### 47.3.2 扩展 + +Kotlin[扩展](https://kotlinlang.org/docs/reference/extensions.html)提供了既存类扩展额外功能的能力。Spring Boot Kotlin API使用这些扩展给既存的API添加新的Kotlin特定的便利。 + +提供了`TestRestTemplate`扩展。它类似于Spring框架提供的`RestOperations`。此外,扩展能够发挥Kotlin具体化参数类型的优势。 diff --git a/IV. Spring Boot features/47.4 Dependency management.md b/IV. Spring Boot features/47.4 Dependency management.md new file mode 100644 index 00000000..909e4af7 --- /dev/null +++ b/IV. Spring Boot features/47.4 Dependency management.md @@ -0,0 +1,13 @@ +### 47.4 依赖管理 + +为了避免混淆类路径上Kotlin依赖的不同版本,Spring Boot提供了下列Kotlin依赖的依赖管理。 + +- `kotlin-reflect` +- `kotlin-runtime` +- `kotlin-stdlib` +- `kotlin-stdlib-jdk7` +- `kotlin-stdlib-jdk8` +- `kotlin-stdlib-jre7` +- `kotlin-stdlib-jre8` + +如果你用的是Maven,Kotlin版本可以通过`kotlin.version`属性自定义。并且,Maven为`kotlin-maven-plugin`提供了插件管理。如果你用的是Gradle,Spring Boot插件会自动把`kotlin.version`定义为Kotlin插件的版本。 diff --git a/IV. Spring Boot features/47.5 @ConfigurationProperties.md b/IV. Spring Boot features/47.5 @ConfigurationProperties.md new file mode 100644 index 00000000..d1ce2e10 --- /dev/null +++ b/IV. Spring Boot features/47.5 @ConfigurationProperties.md @@ -0,0 +1,23 @@ +### 47.5 @ConfigurationProperties + +`@ConfigurationProperties`目前只对`lateinit`或者可为空的`var`属性(推荐前者)生效。由于不可变类由构造器初始化,所以[还不被支持](https://github.com/spring-projects/spring-boot/issues/8762)。 +```java +@ConfigurationProperties("example.kotlin") +class KotlinExampleProperties { + + lateinit var foo1: String + + lateinit var foo2: String + + lateinit val bar = Bar() + + class Bar { + + lateinit var bar1: String + + lateinit var bar2: String + + } + +} +``` diff --git a/IV. Spring Boot features/47.6 Testing.md b/IV. Spring Boot features/47.6 Testing.md new file mode 100644 index 00000000..f98cd191 --- /dev/null +++ b/IV. Spring Boot features/47.6 Testing.md @@ -0,0 +1,5 @@ +### 47.6 测试 + +虽然可以使用JUnit 4(`spring-boot-starter-test`提供的默认版本)测试Kotlin代码,但是推荐JUnit 5。JUnit 5使一个测试类可以被实例化,然后被这个类的所有测试重复使用。这使它可以在非静态方法上使用`@BeforeAll`和`@AfterAll`注解,非常适合Kotlin。 + +使用JUnit 5,需要从`spring-boot-starter-test`里排除`junit:junit`依赖,添加JUnit 5依赖,并且相应地配置Maven或者Gradle插件。更多详情请查看[JUnit 5文档](https://junit.org/junit5/docs/current/user-guide/#dependency-metadata-junit-jupiter-samples)。你也需要[将测试实例的生命周期切换到“每个类”](https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle-changing-default)。 diff --git a/IV. Spring Boot features/47.7.1 Further reading.md b/IV. Spring Boot features/47.7.1 Further reading.md new file mode 100644 index 00000000..0a4134fe --- /dev/null +++ b/IV. Spring Boot features/47.7.1 Further reading.md @@ -0,0 +1,12 @@ +### 47.7.1 延伸阅读 + +- [Kotlin语言参考](https://kotlinlang.org/docs/reference/) +- [Kotlin Slack](http://slack.kotlinlang.org/)(专用的#spring频道) +- [Stackoverflow,带上`spring`与`kotlin`标签](https://stackoverflow.com/questions/tagged/spring+kotlin) +- [在你的浏览器里尝试Kotlin](https://try.kotlinlang.org/) +- [Kotlin博客](https://blog.jetbrains.com/kotlin/) +- [牛逼的Kotlin](https://kotlin.link/) +- [用Kotlin开发Spring Boot应用](https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin) +- [用Kotlin、Spring Boot和PostgreSQL开发地理空间信使](https://spring.io/blog/2016/03/20/a-geospatial-messenger-with-kotlin-spring-boot-and-postgresql) +- [介绍Spring框架5.0里的Kotlin支持](https://spring.io/blog/2017/01/04/introducing-kotlin-support-in-spring-framework-5-0) +- [Spring Framework 5 Kotlin API,函数式方式](https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way) diff --git a/IV. Spring Boot features/47.7.2 Examples.md b/IV. Spring Boot features/47.7.2 Examples.md new file mode 100644 index 00000000..b8eb5957 --- /dev/null +++ b/IV. Spring Boot features/47.7.2 Examples.md @@ -0,0 +1,7 @@ +### 47.7.2 示例 + +- [spring-boot-kotlin-demo](https://github.com/sdeleuze/spring-boot-kotlin-demo):常规的Spring Boot + Spring Data JPA项目 +- [mixit](https://github.com/mixitconf/mixit):Spring Boot 2 + WebFlux + Reactive Spring Data MongoDB +- [spring-kotlin-fullstack](https://github.com/sdeleuze/spring-kotlin-fullstack):WebFlux Kotlin全栈示例,前端使用Kotlin2js代替JavaScript或者TypeScript +- [spring-petclinic-kotlin](https://github.com/spring-petclinic/spring-petclinic-kotlin):Kotlin版本的Spring PetClinic示例应用 +- [spring-kotlin-deepdive](https://github.com/sdeleuze/spring-kotlin-deepdive):从Boot 1.0 + Java逐步迁移到Boot 2.0 + Kotlin diff --git a/IV. Spring Boot features/48. What to Read Next.md b/IV. Spring Boot features/48. What to Read Next.md new file mode 100644 index 00000000..8e870b16 --- /dev/null +++ b/IV. Spring Boot features/48. What to Read Next.md @@ -0,0 +1,5 @@ +### 48. 接下来阅读什么 + +如果想了解本章节讨论类的更多内容,你可以查看[Spring Boot API文档](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api),或直接浏览[源码](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE)。如果有特别问题,可以参考[how-to](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto)章节。 + +如果已熟悉Spring Boot的核心特性,你可以继续并查看[production-ready特性](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready)。 diff --git a/IV. Spring Boot features/README.md b/IV. Spring Boot features/README.md index 6a36e0cc..2b3ff6d6 100644 --- a/IV. Spring Boot features/README.md +++ b/IV. Spring Boot features/README.md @@ -1,3 +1,3 @@ ### Spring Boot特性 -本章节将深入详细的介绍Spring Boot,通过阅读本节你可以了解到需要使用和定制的核心特性。如果没做好准备,你可以先阅读[Part II. Getting started](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#getting-started)和[Part III, “Using Spring Boot” ](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#using-boot)章节,以对Spring Boot有个良好的基本认识。 +本章节将深入详细的介绍Spring Boot,通过阅读本节你可以了解到需要使用和定制的核心特性。如果没做好准备,你可以先阅读[Part II. Getting started](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#getting-started)和[Part III, “Using Spring Boot” ](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot)章节,以对Spring Boot有个良好的基本认识。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71. Spring Boot application.md" "b/IX. \342\200\230How-to\342\200\231 guides/71. Spring Boot application.md" deleted file mode 100644 index 22c3ab58..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71. Spring Boot application.md" +++ /dev/null @@ -1 +0,0 @@ -### 71. Spring Boot应用 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.1 Create your own FailureAnalyzer.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.1 Create your own FailureAnalyzer.md" deleted file mode 100644 index ef44f344..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.1 Create your own FailureAnalyzer.md" +++ /dev/null @@ -1,10 +0,0 @@ -###71.1 创建自己的FailureAnalyzer -[`FailureAnalyzer`](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/diagnostics/FailureAnalyzer.html)是拦截启动时的异常并将它转换为可读消息的很好方式(包装进[`FailureAnalysis`](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/diagnostics/FailureAnalysis.html))。Spring Boot为应用上下文相关异常, JSR-303校验等提供分析器,实际上创建你自己的分析器也相当简单。 - -`AbstractFailureAnalyzer`是`FailureAnalyzer`的一个方便扩展,根据指定类型的异常是否出现来进行处理。你可以继承它,这样就可以处理实际出现的异常。如果出于某些原因,不能处理该异常,那就返回`null`让其他实现处理。 - -`FailureAnalyzer`的实现需要注册到`META-INF/spring.factories`,以下注册了`ProjectConstraintViolationFailureAnalyzer`: -```properties -org.springframework.boot.diagnostics.FailureAnalyzer=\ -com.example.ProjectConstraintViolationFailureAnalyzer -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.2 Troubleshoot auto-configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.2 Troubleshoot auto-configuration.md" deleted file mode 100644 index 9fd161a4..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.2 Troubleshoot auto-configuration.md" +++ /dev/null @@ -1,15 +0,0 @@ -### 71.2 解决自动配置问题 - -Spring Boot自动配置总是尝试尽最大努力去做正确的事,但有时候会失败并且很难说出失败原因。 - -在每个Spring Boot `ApplicationContext`中都存在一个相当有用的`ConditionEvaluationReport`。如果开启`DEBUG`日志输出,你将会看到它。如果你使用`spring-boot-actuator`,则会有一个`autoconfig`的端点,它将以JSON形式渲染该报告。你还可以使用它调试应用程序,并能查看Spring Boot运行时都添加了哪些特性(及哪些没添加)。 - -通过查看源码和javadoc可以获取更多问题的答案,以下是一些经验: - -* 查找名为`*AutoConfiguration`的类并阅读源码,特别是`@Conditional*`注解,这可以帮你找出它们启用哪些特性及何时启用。 -将`--debug`添加到命令行或添加系统属性`-Ddebug`可以在控制台查看日志,该日志会记录你的应用中所有自动配置的决策。在运行Actuator的app中,通过查看`autoconfig`端点(`/autoconfig`或等效的JMX)可以获取相同信息。 -* 查找`@ConfigurationProperties`的类(比如[ServerProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java))并看下有哪些可用的外部配置选项。`@ConfigurationProperties`类有一个用于充当外部配置前缀的`name`属性,因此`ServerProperties`的`prefix="server"`,它的配置属性有`server.port`,`server.address`等。在运行Actuator的应用中可以查看`configprops`端点。 -* 查看`RelaxedPropertyResolver`明确地将配置从`Environment`暴露出去,它经常会使用前缀。 -* 查看`@Value`注解,它直接绑定到`Environment`。相比`RelaxedPropertyResolver`,这种方式稍微缺乏灵活性,但它也允许松散的绑定,特别是OS环境变量(所以`CAPITALS_AND_UNDERSCORES`是`period.separated`的同义词)。 -* 查看`@ConditionalOnExpression`注解,它根据SpEL表达式的结果来开启或关闭特性,通常使用解析自`Environment`的占位符进行计算。 - diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.3 Customize the Environment or ApplicationContext before it starts.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.3 Customize the Environment or ApplicationContext before it starts.md" deleted file mode 100644 index fe8cb9af..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.3 Customize the Environment or ApplicationContext before it starts.md" +++ /dev/null @@ -1,14 +0,0 @@ -### 71.3 启动前自定义Environment或ApplicationContext - -每个`SpringApplication`都有`ApplicationListeners`和`ApplicationContextInitializers`,用于自定义上下文(context)或环境(environment)。Spring Boot从`META-INF/spring.factories`下加载很多这样的内部使用的自定义,有很多方法可以注册其他的自定义: - -* 以编程方式为每个应用注册自定义,通过在`SpringApplication`运行前调用它的`addListeners`和`addInitializers`方法来实现。 -* 以声明方式为每个应用注册自定义,通过设置`context.initializer.classes`或`context.listener.classes`来实现。 -* 以声明方式为所有应用注册自定义,通过添加一个`META-INF/spring.factories`并打包成一个jar文件(该应用将它作为一个库)来实现。 - -`SpringApplication`会给监听器(即使是在上下文被创建之前就存在的)发送一些特定的`ApplicationEvents`,然后也会注册监听`ApplicationContext`发布的事件的监听器,查看Spring Boot特性章节中的[Section 23.5, “Application events and listeners” ](../IV. Spring Boot features/23.5. Application events and listeners.md)可以获取完整列表。 - -在应用上下文刷新前使用`EnvironmentPostProcessor`自定义`Environment`是可能的,每个实现都需要注册到`META-INF/spring.factories`: -```properties -org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.4 Build an ApplicationContext hierarchy\357\274\210adding a parent or root context\357\274\211.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.4 Build an ApplicationContext hierarchy\357\274\210adding a parent or root context\357\274\211.md" deleted file mode 100644 index b04fbca5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.4 Build an ApplicationContext hierarchy\357\274\210adding a parent or root context\357\274\211.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 71.4 构建ApplicationContext层次结构(添加父或根上下文) - -你可以使用`ApplicationBuilder`类创建parent/child `ApplicationContext`层次结构,查看'Spring Boot特性'章节的[Section 23.4, “Fluent builder API” ](../IV. Spring Boot features/23.4. Fluent builder API.md)获取更多信息。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.5 Create a non-web application.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.5 Create a non-web application.md" deleted file mode 100644 index 308d3c8f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.5 Create a non-web application.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 71.5 创建no-web应用 - -不是所有的Spring应用都必须是web应用(或web服务)。如果你想在`main`方法中执行一些代码,但需要启动一个Spring应用去设置需要的底层设施,那使用Spring Boot的`SpringApplication`特性可以很容易实现。`SpringApplication`会根据它是否需要一个web应用来改变它的`ApplicationContext`类,首先你需要做的是去掉servlet API依赖,如果不能这样做(比如基于相同的代码运行两个应用),那你可以明确地调用`SpringApplication.setWebEnvironment(false)`或设置`applicationContextClass`属性(通过Java API或使用外部配置)。你想运行的,作为业务逻辑的应用代码可以实现为一个`CommandLineRunner`,并将上下文降级为一个`@Bean`定义。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72. Properties & configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/72. Properties & configuration.md" deleted file mode 100644 index 3171572a..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72. Properties & configuration.md" +++ /dev/null @@ -1 +0,0 @@ -### 72. 属性&配置 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.1. Automatically expand properties at build time.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.1. Automatically expand properties at build time.md" deleted file mode 100644 index 4d9dce34..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.1. Automatically expand properties at build time.md" +++ /dev/null @@ -1,3 +0,0 @@ -###72.1. 运行时暴露属性 - -相对于在项目构建配置中硬编码某些配置,你可以使用已存在的构建配置自动暴露它们,Maven和Gradle都支持。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.1.1. Automatic property expansion using Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.1.1. Automatic property expansion using Maven.md" deleted file mode 100644 index 52ad89d5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.1.1. Automatic property expansion using Maven.md" +++ /dev/null @@ -1,34 +0,0 @@ -###72.1.1. 使用Maven自动暴露属性 - -你可以使用Maven的资源过滤(resource filter)自动暴露来自Maven项目的属性,如果使用`spring-boot-starter-parent`,你可以通过`@..@`占位符引用Maven项目的属性,例如: -```properties -app.encoding=@project.build.sourceEncoding@ -app.java.version=@java.version@ -``` -**注** 如果启用`addResources`标识,`spring-boot:run`可以将`src/main/resources`直接添加到classpath(出于热加载目的),这就绕过了资源过滤和本特性。你可以使用`exec:java`目标进行替代,或自定义该插件的配置,具体查看[插件使用页面](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin//usage.html)。 - -如果不使用starter parent,你需要将以下片段添加到`pom.xml`中(``元素内): -```xml - - - src/main/resources - true - - -``` -和(``元素内): -```xml - - org.apache.maven.plugins - maven-resources-plugin - 2.7 - - - @ - - false - - -``` - -**注** 如果你在配置中使用标准的Spring占位符(比如`${foo}`)且没有将`useDefaultDelimiters`属性设置为`false`,那构建时这些属性将被暴露出去。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.1.2. Automatic property expansion using Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.1.2. Automatic property expansion using Gradle.md" deleted file mode 100644 index bd8a97a8..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.1.2. Automatic property expansion using Gradle.md" +++ /dev/null @@ -1,15 +0,0 @@ -###72.1.2. 使用Gradle自动暴露属性 - -你可以通过配置Java插件的`processResources`任务自动暴露来自Gradle项目的属性: -```gradle -processResources { - expand(project.properties) -} -``` -然后你可以通过占位符引用Gradle项目的属性: -```properties -app.name=${name} -app.description=${description} -``` - -**注** Gradle的`expand`方法使用Groovy的`SimpleTemplateEngine`转换`${..}`占位符,`${..}`这种格式跟Spring自身的属性占位符机制冲突,想要自动暴露Spring属性占位符,你需要将其进行编码,比如`\${..}`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.2. Externalize the configuration of SpringApplication.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.2. Externalize the configuration of SpringApplication.md" deleted file mode 100644 index 27d9dcb1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.2. Externalize the configuration of SpringApplication.md" +++ /dev/null @@ -1,24 +0,0 @@ -### 72.2. 外部化SpringApplication配置 - -SpringApplication已经被属性化(主要是setters),所以你可以在创建应用时使用它的Java API修改其行为,或者使用以`spring.main.*`为key的属性来外部化这些配置。比如,在`application.properties`中可能会有以下内容: -```java -spring.main.web-environment=false -spring.main.banner-mode=off -``` -这样,Spring Boot在启动时将不会显示banner,并且该应用也不是一个web应用。 - -**注** 以上示例也展示在属性名中使用下划线(`_`)和中划线(`-`)的灵活绑定。 - -外部配置定义的属性会覆盖创建`ApplicationContext`时通过Java API指定的值,让我们看如下应用: -```java -new SpringApplicationBuilder() - .bannerMode(Banner.Mode.OFF) - .sources(demo.MyApp.class) - .run(args); -``` -并使用以下配置: -```properties -spring.main.sources=com.acme.Config,com.acme.ExtraConfig -spring.main.banner-mode=console -``` -实际的应用将显示banner(被配置覆盖),并为`ApplicationContext`指定3个sources,依次为:`demo.MyApp`,`com.acme.Config`,`com.acme.ExtraConfig`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.3 Change the location of external properties of an application.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.3 Change the location of external properties of an application.md" deleted file mode 100644 index 8f2a41e5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.3 Change the location of external properties of an application.md" +++ /dev/null @@ -1,12 +0,0 @@ -### 72.3 改变应用程序外部配置文件的位置 - -默认情况下,来自不同源的属性以一个定义好的顺序添加到Spring的`Environment`中(精确顺序可查看'Sprin Boot特性'章节的[Chapter 24, Externalized Configuration](../IV. Spring Boot features/24. Externalized Configuration.md))。 - -为应用程序源添加`@PropertySource`注解是一种很好的添加和修改源顺序的方法。传递给`SpringApplication`静态便利设施(convenience)方法的类和使用`setSources()`添加的类都会被检查,以查看它们是否有`@PropertySources`,如果有,这些属性会被尽可能早的添加到`Environment`里,以确保`ApplicationContext`生命周期的所有阶段都能使用。以这种方式添加的属性优先级低于任何使用默认位置(比如`application.properties`)添加的属性,系统属性,环境变量或命令行参数。 - -你也可以提供系统属性(或环境变量)来改变该行为: - -* `spring.config.name`(`SPRING_CONFIG_NAME`)是根文件名,默认为`application`。 -* `spring.config.location`(`SPRING_CONFIG_LOCATION`)是要加载的文件(例如,一个classpath资源或URL)。Spring Boot为该文档设置一个单独的`Environment`属性,它可以被系统属性,环境变量或命令行参数覆盖。 - -不管你在environment设置什么,Spring Boot都将加载上面讨论过的`application.properties`。如果使用YAML,那具有`.yml`扩展的文件默认也会被添加到该列表,详情参考[ConfigFileApplicationListener](http://github.com/spring-projects/spring-boot/tree/master/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java) diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.4 Use \342\200\230short\342\200\231 command line arguments.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.4 Use \342\200\230short\342\200\231 command line arguments.md" deleted file mode 100644 index 3e9415b1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.4 Use \342\200\230short\342\200\231 command line arguments.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 72.4 使用'short'命令行参数 - -有些人喜欢使用(例如)`--port=9000`代替`--server.port=9000`来设置命令行配置属性。你可以通过在`application.properties`中使用占位符来启用该功能,比如: -```properties -server.port=${port:8080} -``` -**注** 如果你继承自`spring-boot-starter-parent` POM,为了防止和Spring格式的占位符产生冲突,`maven-resources-plugins`默认的过滤令牌(filter token)已经从`${*}`变为`@`(即`@maven.token@`代替`${maven.token}`)。如果直接启用maven对`application.properties`的过滤,你可能想使用[其他的分隔符](http://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html#delimiters)替换默认的过滤令牌。 - -**注** 在这种特殊的情况下,端口绑定能够在一个PaaS环境下工作,比如Heroku和Cloud Foundry,因为在这两个平台中`PORT`环境变量是自动设置的,并且Spring能够绑定`Environment`属性的大写同义词。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.5 Use YAML for external properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.5 Use YAML for external properties.md" deleted file mode 100644 index 4ea77dc5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.5 Use YAML for external properties.md" +++ /dev/null @@ -1,22 +0,0 @@ -###72.5 使用YAML配置外部属性 - -YAML是JSON的一个超集,可以非常方便的将外部配置以层次结构形式存储起来,比如: -```json -spring: - application: - name: cruncher - datasource: - driverClassName: com.mysql.jdbc.Driver - url: jdbc:mysql://localhost/test -server: - port: 9000 -``` -创建一个`application.yml`文件,将它放到classpath的根目录下,并添加`snakeyaml`依赖(Maven坐标为`org.yaml:snakeyaml`,如果你使用`spring-boot-starter`那就已经包含了)。一个YAML文件会被解析为一个Java `Map`(和一个JSON对象类似),Spring Boot会平伸该map,这样它就只有1级深度,并且有period-separated的keys,跟人们在Java中经常使用的`Properties`文件非常类似。 -上面的YAML示例对应于下面的`application.properties`文件: -```java -spring.application.name=cruncher -spring.datasource.driverClassName=com.mysql.jdbc.Driver -spring.datasource.url=jdbc:mysql://localhost/test -server.port=9000 -``` -查看'Spring Boot特性'章节的[Section 24.6, “Using YAML instead of Properties”](../IV. Spring Boot features/24.6. Using YAML instead of Properties.md)可以获取更多关于YAML的信息。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.6 Set the active Spring profiles.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.6 Set the active Spring profiles.md" deleted file mode 100644 index a9bff5ef..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.6 Set the active Spring profiles.md" +++ /dev/null @@ -1,13 +0,0 @@ -### 72.6 设置生效的Spring profiles - -Spring `Environment`有一个API可以设置生效的profiles,但通常你会通过系统属性(`spring.profiles.active`)或OS环境变量(`SPRING_PROFILES_ACTIVE`)设置。比如,使用一个`-D`参数启动应用程序(记着把它放到`main`类或jar文件之前): -```shell -$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar -``` -在Spring Boot中,你也可以在`application.properties`里设置生效的profile,例如: -```java -spring.profiles.active=production -``` -通过这种方式设置的值会被系统属性或环境变量替换,但不会被`SpringApplicationBuilder.profiles()`方法替换。因此,后面的Java API可用来在不改变默认设置的情况下增加profiles。 - -想要获取更多信息可查看'Spring Boot特性'章节的[Chapter 25, Profiles](..//IV. Spring Boot features/25. Profiles.md)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.7 Change configuration depending on the environment.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.7 Change configuration depending on the environment.md" deleted file mode 100644 index 3e70cbfc..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.7 Change configuration depending on the environment.md" +++ /dev/null @@ -1,29 +0,0 @@ -### 72.7 根据环境改变配置 - -一个YAML文件实际上是一系列以`---`线分割的文档,每个文档都被单独解析为一个平坦的(flattened)map。 - -如果一个YAML文档包含一个`spring.profiles`关键字,那profiles的值(以逗号分割的profiles列表)将被传入Spring的`Environment.acceptsProfiles()`方法,并且如果这些profiles的任何一个被激活,对应的文档被包含到最终的合并中(否则不会)。 - -示例: -```json -server: - port: 9000 ---- - -spring: - profiles: development -server: - port: 9001 - ---- - -spring: - profiles: production -server: - port: 0 -``` -在这个示例中,默认的端口是`9000`,但如果Spring profile `development`生效则该端口是`9001`,如果`production`生效则它是`0`。 - -YAML文档以它们出现的顺序合并,所以后面的值会覆盖前面的值。 - -想要使用profiles文件完成同样的操作,你可以使用`application-${profile}.properties`指定特殊的,profile相关的值。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.8 Discover built-in options for external properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.8 Discover built-in options for external properties.md" deleted file mode 100644 index d8d5629f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.8 Discover built-in options for external properties.md" +++ /dev/null @@ -1,8 +0,0 @@ - -### 72.8 发现外部属性的内置选项 - -Spring Boot在运行时会将来自`application.properties`(或`.yml`)的外部属性绑定到应用,因为不可能将所有支持的属性放到一个地方,classpath下的其他jar也有支持的属性。 - -每个运行中且有Actuator特性的应用都会有一个`configprops`端点,它能够展示所有边界和可通过`@ConfigurationProperties`绑定的属性。 - -附录中包含一个[application.properties](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#common-application-properties)示例,它列举了Spring Boot支持的大多数常用属性,查看`@ConfigurationProperties`,`@Value`,还有不经常使用的`RelaxedEnvironment`的源码可获取最权威的属性列表。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73. Embedded servlet containers.md" "b/IX. \342\200\230How-to\342\200\231 guides/73. Embedded servlet containers.md" deleted file mode 100644 index 8d700256..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73. Embedded servlet containers.md" +++ /dev/null @@ -1 +0,0 @@ -### 73. 内嵌servlet容器 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73. Spring Boot Application.md" "b/IX. \342\200\230How-to\342\200\231 guides/73. Spring Boot Application.md" new file mode 100644 index 00000000..4963ac67 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73. Spring Boot Application.md" @@ -0,0 +1,3 @@ +### 73. Spring Boot应用 + +本节包含与Spring Boot应用直接相关的主题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.1 Add a Servlet, Filter or ServletContextListener to an application.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.1 Add a Servlet, Filter or ServletContextListener to an application.md" deleted file mode 100644 index 447148cf..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.1 Add a Servlet, Filter or ServletContextListener to an application.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.1 为应用添加Servlet,Filter或Listener - -这里有两种方式可以为应用添加`Servlet`,`Filter`,`ServletContextListener`和其他Servlet支持的特定listeners。你既可以为它们提供Spring beans,也可以为Servlet组件启用扫描(package scan)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.1 Create Your Own FailureAnalyzer.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.1 Create Your Own FailureAnalyzer.md" new file mode 100644 index 00000000..effd4b53 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.1 Create Your Own FailureAnalyzer.md" @@ -0,0 +1,13 @@ +### 73.1 创建自己的FailureAnalyzer + +[`FailureAnalyzer`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/diagnostics/FailureAnalyzer.html)是拦截启动时的异常并将它转换为可读消息的很好方式(包装进[`FailureAnalysis`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/diagnostics/FailureAnalysis.html))。Spring Boot为应用上下文相关异常,JSR-303校验等提供分析器。实际上创建你自己的分析器也相当简单。 + +`AbstractFailureAnalyzer`是`FailureAnalyzer`的一个方便扩展,根据指定类型的异常是否出现来进行处理。你可以继承它,这样就可以处理实际出现的异常。如果出于某些原因,不能处理该异常,那就返回`null`让其他实现处理。 + +`FailureAnalyzer`的实现必须注册到`META-INF/spring.factories`。以下注册了`ProjectConstraintViolationFailureAnalyzer`: +```properties +org.springframework.boot.diagnostics.FailureAnalyzer=\ +com.example.ProjectConstraintViolationFailureAnalyzer +``` + +**注** 如果你需要访问`BeanFactory`或`Environment`,你的`FailureAnalyzer`可以简单地分别实现`BeanFactoryAware`或`EnvironmentAware`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.1.1 Add a Servlet, Filter or Listener using a Spring bean.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.1.1 Add a Servlet, Filter or Listener using a Spring bean.md" deleted file mode 100644 index 34a8821f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.1.1 Add a Servlet, Filter or Listener using a Spring bean.md" +++ /dev/null @@ -1,29 +0,0 @@ -###73.1.1 使用Spring bean添加Servlet, Filter或Listener - -想要添加`Servlet`,`Filter`或Servlet`*Listener`,你只需要为它提供一个`@Bean`定义,这种方式很适合注入配置或依赖。不过,需要注意的是它们不会导致其他很多beans的热初始化,因为它们需要在应用生命周期的早期进行安装(让它依赖`DataSource`或JPA配置不是好主意),你可以通过懒加载突破该限制(在第一次使用时才初始化)。 - -对于`Filters`或`Servlets`,你可以通过`FilterRegistrationBean`或`ServletRegistrationBean`添加映射和初始化参数。 - -**注** 在一个filter注册时,如果没指定`dispatcherType`,它将匹配`FORWARD`,`INCLUDE`和`REQUEST`。如果启用异步,它也将匹配`ASYNC`。如果迁移`web.xml`中没有`dispatcher`元素的filter,你需要自己指定一个`dispatcherType`: -```java -@Bean -public FilterRegistrationBean myFilterRegistration() { - FilterRegistrationBean registration = new FilterRegistrationBean(); - registration.setDispatcherTypes(DispatcherType.REQUEST); - .... - - return registration; -} -``` - -**禁止Servlet或Filter的注册** - -如上所述,任何`Servlet`或`Filter` beans都将自动注册到servlet容器。不过,为特定的`Filter`或`Servlet` bean创建一个registration,并将它标记为disabled,可以禁用该filter或servlet。例如: -```java -@Bean -public FilterRegistrationBean registration(MyFilter filter) { - FilterRegistrationBean registration = new FilterRegistrationBean(filter); - registration.setEnabled(false); - return registration; -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md" deleted file mode 100644 index 278f17fc..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md" +++ /dev/null @@ -1,3 +0,0 @@ -###73.1.2 使用classpath扫描添加Servlets, Filters和Listeners - -通过把`@ServletComponentScan`注解到一个`@Configuration`类并指定包含要注册组件的package(s),可以将`@WebServlet`,`@WebFilter`和`@WebListener`注解的类自动注册到内嵌servlet容器。默认情况下,`@ServletComponentScan`将从被注解类的package开始扫描。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.10 Use Tomcat\342\200\231s LegacyCookieProcessor.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.10 Use Tomcat\342\200\231s LegacyCookieProcessor.md" deleted file mode 100644 index 622431f1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.10 Use Tomcat\342\200\231s LegacyCookieProcessor.md" +++ /dev/null @@ -1,14 +0,0 @@ -###73.10 使用Tomcat的LegacyCookieProcessor - -Spring Boot使用的内嵌Tomcat不能开箱即用的支持`Version 0`的Cookie格式,你可能会看到以下错误: -```java -java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value -``` -可以的话,你需要考虑将代码升级到只存储遵从最新版Cookie定义的值。如果不能改变写入的cookie,你可以配置Tomcat使用`LegacyCookieProcessor`。通过向`ServletWebServerFactoryCustomizer`bean添加一个`TomcatContextCustomizer`可以开启`LegacyCookieProcessor`: -```java -@Bean -public WebServerFactoryCustomizer cookieProcessorCustomizer() { - return (serverFactory) -> serverFactory.addContextCustomizers( - (context) -> context.setCookieProcessor(new LegacyCookieProcessor())); -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.11 Use Jetty instead of Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.11 Use Jetty instead of Tomcat.md" deleted file mode 100644 index e794e25d..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.11 Use Jetty instead of Tomcat.md" +++ /dev/null @@ -1,33 +0,0 @@ -### 73.11 使用Jetty替代Tomcat - -Spring Boot starters(特别是`spring-boot-starter-web`)默认都使用Tomcat作为内嵌容器。想使用Jetty替代Tomcat,你需要排除那些Tomcat的依赖并包含Jetty的依赖。为了简化这种事情的处理,Spring Boot将Tomcat和Jetty的依赖捆绑在一起,然后提供了单独的starters。 - -Maven示例: -```xml - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-starter-jetty - -``` -Gradle示例: -```gradle -configurations { - compile.exclude module: 'spring-boot-starter-tomcat' -} - -dependencies { - compile 'org.springframework.boot:spring-boot-starter-web' - compile 'org.springframework.boot:spring-boot-starter-jetty' - // ... -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.12 Configure Jetty.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.12 Configure Jetty.md" deleted file mode 100644 index f83b389b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.12 Configure Jetty.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.12 配置Jetty - -通常你可以遵循[Section 72.8, “Discover built-in options for external properties”](./72.8 Discover built-in options for external properties.md)关于`@ConfigurationProperties`(此处主要是`ServerProperties`)的建议,但也要看下`ServletWebServerFactoryCustomizer`。Jetty API相当丰富,一旦获取到`JettyServletWebServerFactory`,你就可以使用很多方式修改它,或更彻底地就是添加你自己的`JettyServletWebServerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.13 Use Undertow instead of Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.13 Use Undertow instead of Tomcat.md" deleted file mode 100644 index 27435708..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.13 Use Undertow instead of Tomcat.md" +++ /dev/null @@ -1,33 +0,0 @@ -### 73.13 使用Undertow替代Tomcat - -使用Undertow替代Tomcat和[使用Jetty替代Tomcat](./70.11 Use Jetty instead of Tomcat.md)非常类似。你需要排除Tomat依赖,并包含Undertow starter。 - -Maven示例: -```xml - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-starter-undertow - -``` -Gradle示例: -```gradle -configurations { - compile.exclude module: 'spring-boot-starter-tomcat' -} - -dependencies { - compile 'org.springframework.boot:spring-boot-starter-web' - compile 'org.springframework.boot:spring-boot-starter-undertow' - // ... -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.14 Configure Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.14 Configure Undertow.md" deleted file mode 100644 index ba99fbe5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.14 Configure Undertow.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.14 配置Undertow - -通常你可以遵循[Section 72.8, “Discover built-in options for external properties”](./72.8 Discover built-in options for external properties.md)关于`@ConfigurationProperties`(此处主要是`ServerProperties`和`ServerProperties.Undertow`),但也要看下`ServletWebServerFactoryCustomizer`。一旦获取到`UndertowServletWebServerFactory`,你就可以使用`UndertowBuilderCustomizer`修改Undertow的配置以满足你的需求,或更彻底地就是添加你自己的`UndertowServletWebServerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.15 Enable Multiple Listeners with Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.15 Enable Multiple Listeners with Undertow.md" deleted file mode 100644 index a2ccfaad..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.15 Enable Multiple Listeners with Undertow.md" +++ /dev/null @@ -1,18 +0,0 @@ -### 73.15 启用Undertow的多监听器 - -将`UndertowBuilderCustomizer`添加到`UndertowServletWebServerFactory`,然后使用`Builder`添加一个listener: -```java -@Bean -public UndertowServletWebServerFactory servletWebServerFactory() { - UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(); - factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(Builder builder) { - builder.addHttpListener(8080, "0.0.0.0"); - } - - }); - return factory; -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.16 Create WebSocket endpoints using @ServerEndpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.16 Create WebSocket endpoints using @ServerEndpoint.md" deleted file mode 100644 index 5551cdef..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.16 Create WebSocket endpoints using @ServerEndpoint.md" +++ /dev/null @@ -1,10 +0,0 @@ -### 73.16 使用@ServerEndpoint创建WebSocket端点 - -如果想在使用内嵌容器的Spring Boot应用中使用`@ServerEndpoint`,你需要声明一个单独的`ServerEndpointExporter` `@Bean`: -```java -@Bean -public ServerEndpointExporter serverEndpointExporter() { - return new ServerEndpointExporter(); -} -``` -该bean将使用底层的WebSocket容器注册任何被`@ServerEndpoint`注解的beans。当部署到一个单独的servlet容器时,该角色将被一个servlet容器初始化方法执行,`ServerEndpointExporter` bean也就不需要了。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.17 Enable HTTP response compression.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.17 Enable HTTP response compression.md" deleted file mode 100644 index 4942d038..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.17 Enable HTTP response compression.md" +++ /dev/null @@ -1,14 +0,0 @@ -### 73.17 启用HTTP响应压缩 - -Jetty,Tomcat和Undertow支持HTTP响应压缩,你可以通过设置`server.compression.enabled`启用它: -```properties -server.compression.enabled=true -``` -默认情况下,响应信息长度至少2048字节才能触发压缩,通过`server.compression.min-response-size`属性可以改变该长度。另外,只有响应的content type为以下其中之一时才压缩: - -- `text/html` -- `text/xml` -- `text/plain` -- `text/css` - -你可以通过`server.compression.mime-types`属性配置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.2 Change the HTTP port.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.2 Change the HTTP port.md" deleted file mode 100644 index 62e343f2..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.2 Change the HTTP port.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 73.2 改变HTTP端口 - -在一个单独的应用中,主HTTP端口默认为`8080`,不过可以使用`server.port`设置(比如,在`application.properties`中或作为系统属性)。由于`Environment`值的宽松绑定,你也可以使用`SERVER_PORT`(比如,作为OS环境变量)。 - -想要创建`WebApplicationContext`但完全关闭HTTP端点,你可以设置`server.port=-1`(测试时可能有用)。具体详情可查看'Spring Boot特性'章节的[Section 27.3.4, “Customizing embedded servlet containers”](../IV. Spring Boot features/27.3.4 Customizing embedded servlet containers.md),或[ServerProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.2 Troubleshoot Auto-configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.2 Troubleshoot Auto-configuration.md" new file mode 100644 index 00000000..2abcc943 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.2 Troubleshoot Auto-configuration.md" @@ -0,0 +1,14 @@ +### 73.2 解决自动配置问题 + +Spring Boot自动配置总是尝试尽最大努力去做正确的事,但有时候会失败并且很难说出失败原因。 + +在每个Spring Boot `ApplicationContext`中都存在一个相当有用的`ConditionEvaluationReport`。如果开启`DEBUG`日志输出,你将会看到它。如果你使用`spring-boot-actuator`,则会有一个`autoconfig`的端点,它将以JSON形式渲染该报告。你还可以使用它调试应用程序,并能查看Spring Boot运行时都添加了哪些特性(及哪些没添加)。 + +通过查看源码和javadoc可以获取更多问题的答案,以下是一些经验: + +* 查找名为`*AutoConfiguration`的类并阅读源码,特别是`@Conditional*`注解,这可以帮你找出它们启用哪些特性及何时启用。 +将`--debug`添加到命令行或添加系统属性`-Ddebug`可以在控制台查看日志,该日志会记录你的应用中所有自动配置的决策。在运行Actuator的app中,通过查看`autoconfig`端点(`/actuator/conditions`或等效的JMX)可以获取相同信息。 +* 查找`@ConfigurationProperties`的类(比如[ServerProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java))并看下有哪些可用的外部配置选项。`@ConfigurationProperties`类有一个用于充当外部配置前缀的`name`属性,因此`ServerProperties`的`prefix="server"`,它的配置属性有`server.port`,`server.address`等。在运行Actuator的应用中可以查看`configprops`端点。 +* 使用`绑定器`上的`bind`方法以轻松的方式从`环境`中显式地提取配置值。它通常与前缀一起使用。 +* 查看`@Value`注解,它直接绑定到`Environment`。 +* 查看`@ConditionalOnExpression`注解,它根据SpEL表达式的结果来开启或关闭特性,通常使用解析自`Environment`的占位符进行计算。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.3 Customize the Environment or ApplicationContext Before It Starts.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.3 Customize the Environment or ApplicationContext Before It Starts.md" new file mode 100644 index 00000000..9a09b9f7 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.3 Customize the Environment or ApplicationContext Before It Starts.md" @@ -0,0 +1,47 @@ +### 73.3 启动前自定义Environment或ApplicationContext + +每个`SpringApplication`都有`ApplicationListeners`和`ApplicationContextInitializers`,用于自定义上下文(context)或环境(environment)。Spring Boot从`META-INF/spring.factories`下加载很多这样的内部使用的自定义,有很多方法可以注册其他的自定义: + +* 以编程方式为每个应用注册自定义,通过在`SpringApplication`运行前调用它的`addListeners`和`addInitializers`方法来实现。 +* 以声明方式为每个应用注册自定义,通过设置`context.initializer.classes`或`context.listener.classes`来实现。 +* 以声明方式为所有应用注册自定义,通过添加一个`META-INF/spring.factories`并打包成一个jar文件(该应用将它作为一个库)来实现。 + +`SpringApplication`会给监听器(即使是在上下文被创建之前就存在的)发送一些特定的`ApplicationEvents`,然后也会注册监听`ApplicationContext`发布的事件的监听器,查看Spring Boot特性章节中的[23.5. 应用事件和监听器](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-application-events-and-listeners)可以获取完整列表。 + +在应用上下文刷新前使用`EnvironmentPostProcessor`自定义`Environment`是可能的,每个实现都需要注册到`META-INF/spring.factories`: +```properties +org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor +``` + +可以加载任意文件并将它们添加到`环境`中。例如,下面的例子从类路径加载一个YAML配置文件: +```java +public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor { + + private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, + SpringApplication application) { + Resource path = new ClassPathResource("com/example/myapp/config.yml"); + PropertySource propertySource = loadYaml(path); + environment.getPropertySources().addLast(propertySource); + } + + private PropertySource loadYaml(Resource path) { + if (!path.exists()) { + throw new IllegalArgumentException("Resource " + path + " does not exist"); + } + try { + return this.loader.load("custom-resource", path).get(0); + } + catch (IOException ex) { + throw new IllegalStateException( + "Failed to load yaml configuration from " + path, ex); + } + } + +} +``` +**注** 在默认情况下,`环境`已经准备好了所有通常由Spring Boot加载的属性源。因此,可以从环境中获取文件的位置。前面的示例将`自定义资源属性源`添加到列表的末尾,以便在任何其他位置定义的键具有优先级。自定义实现可以定义另一种顺序。 + +**警告** 虽然在`@SpringBootApplication`上使用`@PropertySource`似乎是在`环境`中加载自定义资源的一种方便而简单的方法,但是我们不推荐使用它,因为SpringBoot在刷新`ApplicationContext`之前就准备好了`环境`。使用`@PropertySource`定义的任何键加载太迟,对自动配置没有任何影响。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.3 Use a random unassigned HTTP port.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.3 Use a random unassigned HTTP port.md" deleted file mode 100644 index 263cc8a2..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.3 Use a random unassigned HTTP port.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.3 使用随机未分配的HTTP端口 - -想扫描获取一个未使用的端口(使用操作系统本地端口以防冲突)可以设置`server.port=0`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.4 Build an ApplicationContext Hierarchy\357\274\210Adding a Parent or Root Context\357\274\211.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.4 Build an ApplicationContext Hierarchy\357\274\210Adding a Parent or Root Context\357\274\211.md" new file mode 100644 index 00000000..ae8bd39b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.4 Build an ApplicationContext Hierarchy\357\274\210Adding a Parent or Root Context\357\274\211.md" @@ -0,0 +1,3 @@ +### 73.4 构建ApplicationContext层次结构(添加父或根上下文) + +你可以使用`ApplicationBuilder`类创建parent/child `ApplicationContext`层次结构,查看“Spring Boot特性”章节的[23.4. 流式构建API](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-fluent-builder-api)获取更多信息。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.4 Discover the HTTP port at runtime.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.4 Discover the HTTP port at runtime.md" deleted file mode 100644 index 01aeb6d1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.4 Discover the HTTP port at runtime.md" +++ /dev/null @@ -1,21 +0,0 @@ -### 73.4 发现运行时的HTTP端口 - -你可以从输出的日志或通过它的`EmbeddedWebServer`从`ServletWebServerApplicationContext`获取服务器正在运行的端口。获取和确认服务器已经初始化的最好方式是添加一个`ApplicationListener`类型的`@Bean`,然后当事件发布时将容器pull出来。 - -使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`进行测试时,你可以通过`@LocalServerPort`注解将实际端口注入到字段中,例如: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) -public class MyWebIntegrationTests { - - @Autowired - ServletWebServerApplicationContext server; - - @LocalServerPort - int port; - - // ... - -} -``` -**注** `@LocalServerPort`是`@Value("${local.server.port}")`的元数据,在常规的应用中不要尝试注入端口。正如我们看到的,该值只会在容器初始化后设置。相对于测试,应用代码回调处理的会更早(例如在该值实际可用之前)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.5 Configure SSL.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.5 Configure SSL.md" deleted file mode 100644 index 0bd89770..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.5 Configure SSL.md" +++ /dev/null @@ -1,12 +0,0 @@ -### 73.5 配置SSL - -你可以以声明方式配置SSL,一般通过在`application.properties`或`application.yml`设置各种各样的`server.ssl.*`属性,例如: -```json -server.port = 8443 -server.ssl.key-store = classpath:keystore.jks -server.ssl.key-store-password = secret -server.ssl.key-password = another-secret -``` -查看[Ssl](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot/src/main/java/org/springframework/boot/web/server/Ssl.java)获取所有支持的配置。 - -使用类似于以上示例的配置意味着该应用将不支持端口为8080的普通HTTP连接。Spring Boot不支持通过`application.properties`同时配置HTTP连接器和HTTPS连接器。如果你两个都想要,那就需要以编程的方式配置它们中的一个。推荐使用`application.properties`配置HTTPS,因为HTTP连接器是两个中最容易以编程方式进行配置的,查看[spring-boot-sample-tomcat-multi-connectors](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors)可获取示例项目。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.5 Create a Non-web Application.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.5 Create a Non-web Application.md" new file mode 100644 index 00000000..6d68cd45 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.5 Create a Non-web Application.md" @@ -0,0 +1,3 @@ +### 73.5 创建no-web应用 + +不是所有的Spring应用都必须是web应用(或web服务)。如果你想在`main`方法中执行一些代码,但需要启动一个Spring应用去设置需要的底层设施,那使用Spring Boot的`SpringApplication`特性可以很容易实现。`SpringApplication`会根据它是否需要一个web应用来改变它的`ApplicationContext`类,首先你需要做的是去掉servlet API依赖,如果不能这样做(比如基于相同的代码运行两个应用),那你可以明确地调用`SpringApplication.setWebEnvironment(false)`或设置`applicationContextClass`属性(通过Java API或使用外部配置)。你想运行的,作为业务逻辑的应用代码可以实现为一个`CommandLineRunner`,并将上下文降级为一个`@Bean`定义。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.6 Configure Access Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.6 Configure Access Logging.md" deleted file mode 100644 index 85d5a3eb..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.6 Configure Access Logging.md" +++ /dev/null @@ -1,23 +0,0 @@ -### 73.6 配置访问日志 - -通过相应的命令空间可以为Tomcat、Undertow和Jetty配置访问日志,例如下面是为Tomcat配置的一个[自定义模式](https://tomcat.apache.org/tomcat-8.0-doc/config/valve.html#Access_Logging)的访问日志: -```properties -server.tomcat.basedir=my-tomcat -server.tomcat.accesslog.enabled=true -server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms) -``` -**注** 日志默认路径为tomcat基础路径下的`logs`目录,该dir默认是个临时目录,所以你可能想改变Tomcat的base目录或为日志指定绝对路径。上述示例中,你可以在相对于应用工作目录的`my-tomcat/logs`访问到日志。 - -Undertow的访问日志配置方式类似: -```properties -server.undertow.accesslog.enabled=true -server.undertow.accesslog.pattern=%t %a "%r" %s (%D ms) -``` -日志存储在相对于应用工作目录的`logs`目录下,可以通过`server.undertow.accesslog.directory`自定义。 - -最后,jetty的访问日志也可以这样配置: -```properties -server.jetty.accesslog.enabled=true -server.jetty.accesslog.filename=/var/log/jetty-access.log -``` -默认地,日志会被重定向到`System.err`。更多细节,请查看[文档](https://www.eclipse.org/jetty/documentation/9.3.x/configuring-jetty-request-logs.html)。 \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.7 Use behind a front-end proxy server.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.7 Use behind a front-end proxy server.md" deleted file mode 100644 index 54adbc54..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.7 Use behind a front-end proxy server.md" +++ /dev/null @@ -1,7 +0,0 @@ -###73.7 在前端代理服务器后使用 - -你的应用可能需要发送`302`跳转或使用指向自己的绝对路径渲染内容。当在代理服务器后面运行时,调用者需要的是代理服务器链接而不是部署应用的实际物理机器地址,通常的解决方式是代理服务器将前端地址放到headers并告诉后端服务器如何拼装链接。 - -如果代理添加约定的`X-Forwarded-For`和`X-Forwarded-Proto` headers(大多数都是开箱即用的),只要将`application.properties`中的`server.use-forward-headers`设置为`true`,绝对链接就能正确的渲染。 - -**注** 如果应用运行在Cloud Foundry或Heroku,`server.use-forward-headers`属性没指定的话默认为`true`,其他实例默认为`false`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.7.1 Customize Tomcat\342\200\231s proxy configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.7.1 Customize Tomcat\342\200\231s proxy configuration.md" deleted file mode 100644 index 84843e30..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.7.1 Customize Tomcat\342\200\231s proxy configuration.md" +++ /dev/null @@ -1,16 +0,0 @@ -###73.7.1 自定义Tomcat代理配置 - -如果使用的是Tomcat,你可以配置用于传输"forwarded"信息的headers名: -```properties -server.tomcat.remote-ip-header=x-your-remote-ip-header -server.tomcat.protocol-header=x-your-protocol-header -``` -你也可以为Tomcat配置一个默认的正则表达式,用来匹配内部信任的代理。默认情况下,IP地址`10/8`,`192.168/16`,`169.254/16`和`127/8`是被信任的。通过设置`server.tomcat.internal-proxies`属性可以自定义,比如: -```properties -server.tomcat.internal-proxies=192\\.168\\.\\d{1,3}\\.\\d{1,3} -``` -**注** 只有在使用配置文件时才需要双反斜线,如果使用YAML,只需要单个反斜线,比如`192\.168\.\d{1,3}\.\d{1,3}`。 - -**注** 将`internal-proxies`设置为空表示信任所有代理,不要在生产环境使用。 - -你可以完全控制Tomcat的`RemoteIpValve`配置,只要关掉自动配置(比如设置`server.use-forward-headers=false`)并在`TomcatServletWebServerFactory` bean添加一个新value实例。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.8 Configure Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.8 Configure Tomcat.md" deleted file mode 100644 index 35fd2c66..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.8 Configure Tomcat.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 73.8 配置Tomcat - -通常你可以遵循[Section 72.8, “Discover built-in options for external properties”](./72.8 Discover built-in options for external properties.md)关于`@ConfigurationProperties`(这里主要的是`ServerProperties`)的建议,但也看下`ServletWebServerFactoryCustomizer`和各种你可以添加的Tomcat-specific的`*Customizers`。 - -Tomcat APIs相当丰富,一旦获取到`TomcatServletWebServerFactory`,你就能够以多种方式修改它,或更彻底地就是添加你自己的`TomcatServletWebServerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.9 Enable Multiple Connectors with Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.9 Enable Multiple Connectors with Tomcat.md" deleted file mode 100644 index a48b6e79..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.9 Enable Multiple Connectors with Tomcat.md" +++ /dev/null @@ -1,34 +0,0 @@ -### 73.9 启用Tomcat的多连接器 - -你可以将`org.apache.catalina.connector.Connector`添加到`TomcatServletWebServerFactory`,这就能够允许多连接器,比如HTTP和HTTPS连接器: -```java -@Bean -public ServletWebServerFactory servletContainer() { - TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); - tomcat.addAdditionalTomcatConnectors(createSslConnector()); - return tomcat; -} - -private Connector createSslConnector() { - Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); - Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler(); - try { - File keystore = new ClassPathResource("keystore").getFile(); - File truststore = new ClassPathResource("keystore").getFile(); - connector.setScheme("https"); - connector.setSecure(true); - connector.setPort(8443); - protocol.setSSLEnabled(true); - protocol.setKeystoreFile(keystore.getAbsolutePath()); - protocol.setKeystorePass("changeit"); - protocol.setTruststoreFile(truststore.getAbsolutePath()); - protocol.setTruststorePass("changeit"); - protocol.setKeyAlias("apitester"); - return connector; - } - catch (IOException ex) { - throw new IllegalStateException("can't access keystore: [" + "keystore" - + "] or truststore: [" + "keystore" + "]", ex); - } -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74. Properties and Configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/74. Properties and Configuration.md" new file mode 100644 index 00000000..8da1680f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74. Properties and Configuration.md" @@ -0,0 +1,3 @@ +### 74. 属性与配置 + +本节包括有关设置和读取属性、配置设置及其与Spring Boot应用程序的交互的主题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74. Spring MVC.md" "b/IX. \342\200\230How-to\342\200\231 guides/74. Spring MVC.md" deleted file mode 100644 index 4ca17beb..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74. Spring MVC.md" +++ /dev/null @@ -1 +0,0 @@ -### 74. Spring MVC diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.1 Write a JSON REST service.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.1 Write a JSON REST service.md" deleted file mode 100644 index 1ada940b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.1 Write a JSON REST service.md" +++ /dev/null @@ -1,15 +0,0 @@ -### 74.1 编写JSON REST服务 - -只要添加的有Jackson2依赖,Spring Boot应用中的任何`@RestController`默认都会渲染为JSON响应,例如: -```java -@RestController -public class MyController { - -    @RequestMapping("/thing") -    public MyThing thing() { - return new MyThing(); - } - -} -``` -只要`MyThing`能够通过Jackson2序列化(比如,一个标准的POJO或Groovy对象),默认[localhost:8080/thing](http://localhost:8080/thing)将响应一个JSON数据。有时在浏览器中你可能看到XML响应,因为浏览器倾向于发送XML accept headers。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.1. Automatically Expand Properties at Build Time.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.1. Automatically Expand Properties at Build Time.md" new file mode 100644 index 00000000..3b4cbd36 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.1. Automatically Expand Properties at Build Time.md" @@ -0,0 +1,3 @@ +### 74.1. 运行时暴露属性 + +相对于在项目构建配置中硬编码某些配置,你可以使用已存在的构建配置自动暴露它们。Maven和Gradle都支持。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.1.1. Automatic Property Expansion Using Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.1.1. Automatic Property Expansion Using Maven.md" new file mode 100644 index 00000000..9e77be67 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.1.1. Automatic Property Expansion Using Maven.md" @@ -0,0 +1,37 @@ +### 74.1.1. 使用Maven自动暴露属性 + +你可以使用Maven的资源过滤自动暴露来自Maven项目的属性,如果使用`spring-boot-starter-parent`,你可以通过`@..@`占位符引用Maven项目的属性,例如: +```properties +app.encoding=@project.build.sourceEncoding@ +app.java.version=@java.version@ +``` + +**注** 仅对生产配置进行过滤(换句话说,对`src/test/resources`不应用过滤)。 + +**注** 如果启用`addResources`标识,`spring-boot:run`可以将`src/main/resources`直接添加到classpath(出于热加载目的),这就绕过了资源过滤和本特性。你可以使用`exec:java`目标进行替代,或自定义该插件的配置,具体查看[插件使用页面](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin/usage.html)。 + +如果不使用starter parent,你需要将以下片段添加到`pom.xml`中(``元素内): +```xml + + + src/main/resources + true + + +``` +和(``元素内): +```xml + + org.apache.maven.plugins + maven-resources-plugin + 2.7 + + + @ + + false + + +``` + +**注** 如果你在配置中使用标准的Spring占位符(比如`${placeholder}`)且没有将`useDefaultDelimiters`属性设置为`false`,那构建时这些属性将被暴露出去。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.1.2. Automatic Property Expansion Using Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.1.2. Automatic Property Expansion Using Gradle.md" new file mode 100644 index 00000000..898ae75e --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.1.2. Automatic Property Expansion Using Gradle.md" @@ -0,0 +1,15 @@ +### 74.1.2. 使用Gradle自动暴露属性 + +你可以通过配置Java插件的`processResources`任务自动暴露来自Gradle项目的属性: +```gradle +processResources { + expand(project.properties) +} +``` +然后你可以通过占位符引用Gradle项目的属性: +```properties +app.name=${name} +app.description=${description} +``` + +**注** Gradle的`expand`方法使用Groovy的`SimpleTemplateEngine`转换`${..}`占位符,`${..}`这种格式跟Spring自身的属性占位符机制冲突,想要自动暴露Spring属性占位符,你需要将其进行编码,比如`\${..}`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.2 Write an XML REST service.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.2 Write an XML REST service.md" deleted file mode 100644 index d660616b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.2 Write an XML REST service.md" +++ /dev/null @@ -1,25 +0,0 @@ -### 74.2 编写XML REST服务 - -如果classpath下存在Jackson XML扩展(`jackson-dataformat-xml`),它会被用来渲染XML响应,示例和JSON的非常相似。想要使用它,只需为你的项目添加以下依赖: -```xml - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - -``` -你可能还需要添加Woodstox的依赖,它比JDK提供的默认StAX实现快很多,并且支持良好的格式化输出,提高了namespace处理能力: -```xml - - org.codehaus.woodstox - woodstox-core-asl - -``` -如果Jackson的XML扩展不可用,Spring Boot将使用JAXB(JDK默认提供),不过`MyThing`需要注解`@XmlRootElement`: -```java -@XmlRootElement -public class MyThing { - private String name; - // .. getters and setters -} -``` -想要服务器渲染XML而不是JSON,你可能需要发送一个`Accept: text/xml`头部(或使用浏览器)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.2. Externalize the Configuration of SpringApplication.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.2. Externalize the Configuration of SpringApplication.md" new file mode 100644 index 00000000..13eaca87 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.2. Externalize the Configuration of SpringApplication.md" @@ -0,0 +1,24 @@ +### 74.2. 外部化SpringApplication配置 + +SpringApplication已经被属性化(主要是setters),所以你可以在创建应用时使用它的Java API修改其行为,或者使用以`spring.main.*`为key的属性来外部化这些配置。比如,在`application.properties`中可能会有以下内容: +```java +spring.main.web-environment=false +spring.main.banner-mode=off +``` +这样,Spring Boot在启动时将不会显示banner,并且该应用也不是一个web应用。 + +**注** 以上示例也展示在属性名中使用下划线(`_`)和中划线(`-`)的灵活绑定。 + +外部配置定义的属性会覆盖创建`ApplicationContext`时通过Java API指定的值,让我们看如下应用: +```java +new SpringApplicationBuilder() + .bannerMode(Banner.Mode.OFF) + .sources(demo.MyApp.class) + .run(args); +``` +并使用以下配置: +```properties +spring.main.sources=com.acme.Config,com.acme.ExtraConfig +spring.main.banner-mode=console +``` +实际的应用将显示banner(被配置覆盖),并为`ApplicationContext`指定3个sources,依次为:`demo.MyApp`,`com.acme.Config`,`com.acme.ExtraConfig`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.3 Change the Location of External Properties of an Application.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.3 Change the Location of External Properties of an Application.md" new file mode 100644 index 00000000..7ba7174d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.3 Change the Location of External Properties of an Application.md" @@ -0,0 +1,12 @@ +### 74.3 改变应用程序外部配置文件的位置 + +默认情况下,来自不同源的属性以一个定义好的顺序添加到Spring的`Environment`中(精确顺序可查看'Sprin Boot特性'章节的[24.外部化配置](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config))。 + +为应用程序源添加`@PropertySource`注解是一种很好的添加和修改源顺序的方法。传递给`SpringApplication`静态便利设施(convenience)方法的类和使用`setSources()`添加的类都会被检查,以查看它们是否有`@PropertySources`,如果有,这些属性会被尽可能早的添加到`Environment`里,以确保`ApplicationContext`生命周期的所有阶段都能使用。以这种方式添加的属性优先级低于任何使用默认位置(比如`application.properties`)添加的属性,系统属性,环境变量或命令行参数。 + +你也可以提供系统属性(或环境变量)来改变该行为: + +* `spring.config.name`(`SPRING_CONFIG_NAME`)是根文件名,默认为`application`。 +* `spring.config.location`(`SPRING_CONFIG_LOCATION`)是要加载的文件(例如,一个classpath资源或URL)。Spring Boot为该文档设置一个单独的`Environment`属性,它可以被系统属性,环境变量或命令行参数覆盖。 + +不管你在environment设置什么,Spring Boot都将加载上面讨论过的`application.properties`。如果使用YAML,那具有`.yml`扩展的文件默认也会被添加到该列表,详情参考[ConfigFileApplicationListener](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java) diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.3 Customize the Jackson ObjectMapper.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.3 Customize the Jackson ObjectMapper.md" deleted file mode 100644 index 7bdeef14..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.3 Customize the Jackson ObjectMapper.md" +++ /dev/null @@ -1,33 +0,0 @@ -### 74.3 自定义Jackson ObjectMapper - -在一个HTTP交互中,Spring MVC(客户端和服务端)使用`HttpMessageConverters`协商内容转换。如果classpath下存在Jackson,你就获取到`Jackson2ObjectMapperBuilder`提供的默认转换器,这是Spring Boot为你自动配置的实例。 - -创建的`ObjectMapper`(或用于Jackson XML转换的`XmlMapper`)实例默认有以下自定义属性: - -- `MapperFeature.DEFAULT_VIEW_INCLUSION`,默认是禁用的 -- `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`,默认是禁用的 - -Spring Boot也有一些用于简化自定义该行为的特性。 - -你可以使用当前的environment配置`ObjectMapper`和`XmlMapper`实例。Jackson提供一个扩展套件,可以用来关闭或开启一些特性,你可以用它们配置Jackson以处理不同方面。这些特性在Jackson中是使用6个枚举进行描述的,并被映射到environment的属性上: - -|Jackson枚举|Environment属性| -|------|:-------| -|`com.fasterxml.jackson.databind.DeserializationFeature`|`spring.jackson.deserialization.=true|false`| -|`com.fasterxml.jackson.core.JsonGenerator.Feature`|`spring.jackson.generator.=true|false`| -|`com.fasterxml.jackson.databind.MapperFeature`|`spring.jackson.mapper.=true|false`| -|`com.fasterxml.jackson.core.JsonParser.Feature`|`spring.jackson.parser.=true|false`| -|`com.fasterxml.jackson.databind.SerializationFeature`|`spring.jackson.serialization.=true|false`| -|`com.fasterxml.jackson.annotation.JsonInclude.Include`|`spring.jackson.serialization-inclusion=always|non_null|non_absent|non_default|non_empty`| - -例如,设置`spring.jackson.serialization.indent_output=true`可以美化打印输出(pretty print)。注意,由于[松散绑定](../IV. Spring Boot features/24.7.2. Relaxed binding.md)的使用,`indent_output`不必匹配对应的枚举常量`INDENT_OUTPUT`。 - -基于environment的配置会应用到自动配置的`Jackson2ObjectMapperBuilder` bean,然后应用到通过该builder创建的mappers,包括自动配置的`ObjectMapper` bean。 - -`ApplicationContext`中的`Jackson2ObjectMapperBuilder`可以通过`Jackson2ObjectMapperBuilderCustomizer` bean自定义。这些customizer beans可以排序,Spring Boot自己的customizer序号为0,其他自定义可以应用到Spring Boot自定义之前或之后。 - -所有类型为`com.fasterxml.jackson.databind.Module`的beans都会自动注册到自动配置的`Jackson2ObjectMapperBuilder`,并应用到它创建的任何`ObjectMapper`实例。这提供了一种全局机制,用于在为应用添加新特性时贡献自定义模块。 - -如果想完全替换默认的`ObjectMapper`,你既可以定义该类型的`@Bean`并注解`@Primary`,也可以定义`Jackson2ObjectMapperBuilder` `@Bean`,通过builder构建。注意不管哪种方式都会禁用所有的自动配置`ObjectMapper`。 - -如果你提供`MappingJackson2HttpMessageConverter`类型的`@Bean`,它们将替换MVC配置中的默认值。Spring Boot也提供了一个`HttpMessageConverters`类型的便利bean(如果你使用MVC默认配置,那它就总是可用的),它提供了一些有用的方法来获取默认和用户增强的消息转换器(message converters)。具体详情可参考[Section 74.4, “Customize the @ResponseBody rendering”](./74.4 Customize the @ResponseBody rendering.md)及[WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.4 Customize the @ResponseBody rendering.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.4 Customize the @ResponseBody rendering.md" deleted file mode 100644 index 66af5f6f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.4 Customize the @ResponseBody rendering.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 74.4 自定义@ResponseBody渲染 - -Spring使用`HttpMessageConverters`渲染`@ResponseBody`(或来自`@RestController`的响应),你可以通过在Spring Boot上下文中添加该类型的beans来贡献其他的转换器。如果你添加的bean类型默认已经包含了(像用于JSON转换的`MappingJackson2HttpMessageConverter`),那它将替换默认的。Spring Boot提供一个方便的`HttpMessageConverters`类型的bean,它有一些有用的方法可以访问默认的和用户增强的message转换器(比如你想要手动将它们注入到一个自定义的`RestTemplate`时就很有用)。 - -在通常的MVC用例中,任何你提供的`WebMvcConfigurerAdapter` beans通过覆盖`configureMessageConverters`方法也能贡献转换器,但不同于通常的MVC,你可以只提供你需要的转换器(因为Spring Boot使用相同的机制来贡献它默认的转换器)。最终,如果你通过提供自己的` @EnableWebMvc`注解覆盖Spring Boot默认的MVC配置,那你就可以完全控制,并使用来自`WebMvcConfigurationSupport`的`getMessageConverters`手动做任何事。 - -更多详情可参考[WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.4 Use \342\200\230Short\342\200\231 Command Line Arguments.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.4 Use \342\200\230Short\342\200\231 Command Line Arguments.md" new file mode 100644 index 00000000..a2cd1c27 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.4 Use \342\200\230Short\342\200\231 Command Line Arguments.md" @@ -0,0 +1,9 @@ +### 74.4 使用“短”命令行参数 + +有些人喜欢使用(例如)`--port=9000`代替`--server.port=9000`来设置命令行配置属性。你可以通过在`application.properties`中使用占位符来启用该功能,比如: +```properties +server.port=${port:8080} +``` +**注** 如果你继承自`spring-boot-starter-parent` POM,为了防止和Spring格式的占位符产生冲突,`maven-resources-plugins`默认的过滤令牌(filter token)已经从`${*}`变为`@`(即`@maven.token@`代替`${maven.token}`)。如果直接启用Maven对`application.properties`的过滤,你可能想使用[其他的分隔符](https://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html#delimiters)替换默认的过滤令牌。 + +**注** 在这种特殊的情况下,端口绑定能够在一个PaaS环境下工作,比如Heroku和Cloud Foundry,因为在这两个平台中`PORT`环境变量是自动设置的,并且Spring能够绑定`Environment`属性的大写同义词。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.5 Handling Multipart File Uploads.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.5 Handling Multipart File Uploads.md" deleted file mode 100644 index 2ccdcff2..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.5 Handling Multipart File Uploads.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 74.5 处理Multipart文件上传 - -Spring Boot采用Servlet 3 `javax.servlet.http.Part` API来支持文件上传。默认情况下,Spring Boot配置Spring MVC在单个请求中只处理每个文件最大1MB,最多10MB的文件数据。你可以覆盖那些值,也可以设置临时文件存储的位置(比如,存储到`/tmp`文件夹下)及传递数据刷新到磁盘的阀值(通过使用`MultipartProperties`类暴露的属性)。如果你需要设置文件不受限制,可以设置`spring.servlet.multipart.max-file-size`属性值为`-1`。 - -当你想要接收multipart编码文件数据作为Spring MVC控制器(controller)处理方法中被`@RequestParam`注解的`MultipartFile`类型的参数时,multipart支持就非常有用了。 - -更多详情可参考[MultipartAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.5 Use YAML for External Properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.5 Use YAML for External Properties.md" new file mode 100644 index 00000000..3b38ad67 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.5 Use YAML for External Properties.md" @@ -0,0 +1,23 @@ +### 74.5 使用YAML配置外部属性 + +YAML是JSON的一个超集,可以非常方便的将外部配置以层次结构形式存储起来,比如: +```json +spring: + application: + name: cruncher + datasource: + driverClassName: com.mysql.jdbc.Driver + url: jdbc:mysql://localhost/test +server: + port: 9000 +``` +创建一个`application.yml`文件,将它放到classpath的根目录下,并添加`snakeyaml`依赖(Maven坐标为`org.yaml:snakeyaml`,如果你使用`spring-boot-starter`那就已经包含了)。一个YAML文件会被解析为一个Java `Map`(和一个JSON对象类似),Spring Boot会平伸该map,这样它就只有1级深度,并且有period-separated的keys,跟人们在Java中经常使用的`Properties`文件非常类似。 +上面的YAML示例对应于下面的`application.properties`文件: +```java +spring.application.name=cruncher +spring.datasource.driverClassName=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://localhost/test +server.port=9000 +``` + +查看'Spring Boot特性'章节的[24.6. 使用YAML代替Properties](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-yaml)可以获取更多关于YAML的信息。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.6 Set the Active Spring Profiles.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.6 Set the Active Spring Profiles.md" new file mode 100644 index 00000000..b03e84e7 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.6 Set the Active Spring Profiles.md" @@ -0,0 +1,13 @@ +### 74.6 设置生效的Spring profiles + +Spring `Environment`有一个API可以设置生效的profiles,但通常你会通过系统属性(`spring.profiles.active`)或OS环境变量(`SPRING_PROFILES_ACTIVE`)设置。比如,使用一个`-D`参数启动应用程序(记着把它放到`main`类或jar文件之前): +```shell +$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar +``` +在Spring Boot中,你也可以在`application.properties`里设置生效的profile,例如: +```java +spring.profiles.active=production +``` +通过这种方式设置的值会被系统属性或环境变量替换,但不会被`SpringApplicationBuilder.profiles()`方法替换。因此,后面的Java API可用来在不改变默认设置的情况下增加profiles。 + +想要获取更多信息可查看'Spring Boot特性'章节的[25. Profiles](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-profiles)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.6 Switch off the Spring MVC DispatcherServlet.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.6 Switch off the Spring MVC DispatcherServlet.md" deleted file mode 100644 index eaa22778..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.6 Switch off the Spring MVC DispatcherServlet.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 74.6 关闭Spring MVC DispatcherServlet - -Spring Boot想要服务来自应用程序root `/`下的所有内容。如果你想将自己的servlet映射到该目录下也是可以的,但当然你可能失去一些Spring Boot MVC特性。为了添加你自己的servlet,并将它映射到root资源,你只需声明一个`Servlet`类型的`@Bean`,并给它特定的bean名称`dispatcherServlet`(如果只想关闭但不替换它,你可以使用该名称创建不同类型的bean)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.7 Change Configuration Depending on the Environment.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.7 Change Configuration Depending on the Environment.md" new file mode 100644 index 00000000..d086340b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.7 Change Configuration Depending on the Environment.md" @@ -0,0 +1,29 @@ +### 74.7 根据环境改变配置 + +一个YAML文件实际上是一系列以`---`线分割的文档,每个文档都被单独解析为一个平坦的(flattened)map。 + +如果一个YAML文档包含一个`spring.profiles`关键字,那profiles的值(以逗号分割的profiles列表)将被传入Spring的`Environment.acceptsProfiles()`方法,并且如果这些profiles的任何一个被激活,对应的文档被包含到最终的合并中(否则不会)。 + +示例: +```yaml +server: + port: 9000 +--- + +spring: + profiles: development +server: + port: 9001 + +--- + +spring: + profiles: production +server: + port: 0 +``` +在这个示例中,默认的端口是`9000`,但如果Spring profile `development`生效则该端口是`9001`,如果`production`生效则它是`0`。 + +**注** YAML文档以它们出现的顺序合并,所以后面的值会覆盖前面的值。 + +想要使用profiles文件完成同样的操作,你可以使用`application-${profile}.properties`指定特殊的,profile相关的值。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.7 Switch off the Default MVC configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.7 Switch off the Default MVC configuration.md" deleted file mode 100644 index 543efd34..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.7 Switch off the Default MVC configuration.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 74.7 关闭默认的MVC配置 - -完全控制MVC配置的最简单方式是提供你自己的被`@EnableWebMvc`注解的`@Configuration`,这样所有的MVC配置都逃不出你的掌心。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.8 Customize ViewResolvers.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.8 Customize ViewResolvers.md" deleted file mode 100644 index db883e71..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.8 Customize ViewResolvers.md" +++ /dev/null @@ -1,15 +0,0 @@ -### 74.8 自定义ViewResolvers - -`ViewResolver`是Spring MVC的核心组件,它负责转换`@Controller`中的视图名称到实际的`View`实现。注意`ViewResolvers`主要用在UI应用中,而不是REST风格的服务(`View`不是用来渲染`@ResponseBody`的)。Spring有很多你可以选择的`ViewResolver`实现,并且Spring自己对如何选择相应实现也没发表意见。另一方面,Spring Boot会根据classpath上的依赖和应用上下文为你安装一或两个`ViewResolver`实现。`DispatcherServlet`使用所有在应用上下文中找到的解析器(resolvers),并依次尝试每一个直到它获取到结果,所以如果你正在添加自己的解析器,那就要小心顺序和你的解析器添加的位置。 - -`WebMvcAutoConfiguration`将会为你的上下文添加以下`ViewResolvers`: - -- bean id为`defaultViewResolver`的`InternalResourceViewResolver`,它会定位可以使用`DefaultServlet`渲染的物理资源(比如静态资源和JSP页面)。它在视图名上应用了一个前缀和后缀(默认都为空,但你可以通过`spring.view.prefix`和`spring.view.suffix`设置),然后查找在servlet上下文中具有该路径的物理资源,可以通过提供相同类型的bean覆盖它。 -- id为`beanNameViewResolver`的`BeanNameViewResolver`,它是视图解析器链的一个非常有用的成员,可以在`View`解析时收集任何具有相同名称的beans,没必要覆盖或替换它。 -- id为`viewResolver`的`ContentNegotiatingViewResolver`,它只会在实际`View`类型的beans出现时添加。这是一个'master'解析器,它的职责会代理给其他解析器,它会尝试找到客户端发送的一个匹配'Accept'的HTTP头部。这有一篇关于[ContentNegotiatingViewResolver](https://spring.io/blog/2013/06/03/content-negotiation-using-views)的博客,你也可以也查看下源码。通过定义一个名叫'viewResolver'的bean,你可以关闭自动配置的`ContentNegotiatingViewResolver`。 -- 如果使用Thymeleaf,你将有一个id为`thymeleafViewResolver`的`ThymeleafViewResolver`,它会通过加前缀和后缀的视图名来查找资源(外部配置为`spring.thymeleaf.prefix`和`spring.thymeleaf.suffix`,对应的默认为'classpath:/templates/'和'.html')。你可以通过提供相同名称的bean来覆盖它。 -- 如果使用FreeMarker,你将有一个id为`freeMarkerViewResolver`的`FreeMarkerViewResolver`,它会使用加前缀和后缀(外部配置为`spring.freemarker.prefix`和`spring.freemarker.suffix`,对应的默认值为空和'.ftl')的视图名从加载路径(外部配置为`spring.freemarker.templateLoaderPath`,默认为'classpath:/templates/')下查找资源。你可以通过提供相同名称的bean来覆盖它。 -- 如果使用Groovy模板(实际上只要你把groovy-templates添加到classpath下),你将有一个id为`groovyTemplateViewResolver`的`Groovy TemplateViewResolver`,它会使用加前缀和后缀(外部属性为`spring.groovy.template.prefix`和`spring.groovy.template.suffix`,对应的默认值为'classpath:/templates/'和'.tpl')的视图名从加载路径下查找资源。你可以通过提供相同名称的bean来覆盖它。 -- 如果使用Velocity,你将有一个id为`velocityViewResolver`的`VelocityViewResolver`,它会使用加前缀和后缀(外部属性为`spring.velocity.prefix`和`spring.velocity.suffix`,对应的默认值为空和'.vm')的视图名从加载路径(外部属性为`spring.velocity.resourceLoaderPath`,默认为'classpath:/templates/')下查找资源。你可以通过提供相同名称的bean来覆盖它。 - -更多详情可查看源码:  [WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java),[ThymeleafAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[FreeMarkerAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java),[GroovyTemplateAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.8 Discover Built-in Options for External Properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.8 Discover Built-in Options for External Properties.md" new file mode 100644 index 00000000..e8c1f87d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.8 Discover Built-in Options for External Properties.md" @@ -0,0 +1,8 @@ + +### 74.8 发现外部属性的内置选项 + +Spring Boot在运行时会将来自`application.properties`(或`.yml`)的外部属性绑定到应用,因为不可能将所有支持的属性放到一个地方,classpath下的其他jar也有支持的属性。 + +每个运行中且有Actuator特性的应用都会有一个`configprops`端点,它能够展示所有边界和可通过`@ConfigurationProperties`绑定的属性。 + +附录中包含一个[application.properties](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#common-application-properties)示例。它列举了Spring Boot支持的大多数常用属性,查看`@ConfigurationProperties`,`@Value`,还有不经常使用的`Binder`的源码可获取最权威的属性列表。有关加载属性的准确顺序的详细信息,请参阅[24.外部化配置](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75. Embedded Web Servers.md" "b/IX. \342\200\230How-to\342\200\231 guides/75. Embedded Web Servers.md" new file mode 100644 index 00000000..62d2f7ea --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75. Embedded Web Servers.md" @@ -0,0 +1,3 @@ +### 75. 内嵌网络服务器 + +每个Spring Boot网络应用程序都包含一个嵌入式网络服务器。该特性会导致许多操作问题,包括如何更改嵌入式服务器以及如何配置嵌入式服务器。本节将回答这些问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75. HTTP clients.md" "b/IX. \342\200\230How-to\342\200\231 guides/75. HTTP clients.md" deleted file mode 100644 index b5d4cfd2..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/75. HTTP clients.md" +++ /dev/null @@ -1 +0,0 @@ -###75. HTTP客户端 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.1 Configure RestTemplate to use a proxy.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.1 Configure RestTemplate to use a proxy.md" deleted file mode 100644 index ef559c95..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/75.1 Configure RestTemplate to use a proxy.md" +++ /dev/null @@ -1,30 +0,0 @@ -###75.1 配置RestTemplate使用代理 -正如[Section 33.1, “RestTemplate customization”](../IV. Spring Boot features/33.1 RestTemplate customization.md)描述的那样,你可以使用`RestTemplateCustomizer`和`RestTemplateBuilder`构建一个自定义的`RestTemplate`,这是创建使用代理的`RestTemplate`的推荐方式。 - -代理配置的确切细节取决于底层使用的客户端请求factory,这里有个示例演示`HttpClient`配置的`HttpComponentsClientRequestFactory`对所有hosts都使用代理,除了`192.168.0.5`。 -```java -static class ProxyCustomizer implements RestTemplateCustomizer { - - @Override - public void customize(RestTemplate restTemplate) { - HttpHost proxy = new HttpHost("proxy.example.com"); - HttpClient httpClient = HttpClientBuilder.create() - .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { - - @Override - public HttpHost determineProxy(HttpHost target, - HttpRequest request, HttpContext context) - throws HttpException { - if (target.getHostName().equals("192.168.0.5")) { - return null; - } - return super.determineProxy(target, request, context); - } - - }).build(); - restTemplate.setRequestFactory( - new HttpComponentsClientHttpRequestFactory(httpClient)); - } - -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.1 Use Another Web Server.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.1 Use Another Web Server.md" new file mode 100644 index 00000000..ad31c0d5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.1 Use Another Web Server.md" @@ -0,0 +1,44 @@ +### 75.1 使用另外的网络服务器 + +许多Spring Boot程序都包含默认的嵌入式容器。`spring-boot-starter-web`通过包含`spring-boot-starter-tomcat`来包含Tomcat。但是,你可以使用`spring-boot-starter-jetty`或`spring-boot-starter-undertow`来代替。`spring-boot-starter-webflux`通过包含`spring-boot-starter-reactor-netty`,包含了Reactor Netty。但是,你可以使用`spring-boot-starter-tomcat`、`spring-boot-starter-jetty`或者`spring-boot-starter-undertow`来代替。 + +**注** 许多starter只支持Spring MVC,因此它们将`spring-boot-starter-web`引入到你的应用程序类路径中。 + +如果需要使用不同的HTTP服务器,则需要排除默认依赖项,并包含所需的依赖项。Spring Boot为HTTP服务器提供了独立的启动程序,以帮助尽可能简化这个过程。 + +下面的Maven示例展示了如何在Spring MVC中排除Tomcat并包含Jetty: +```xml + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.springframework.boot + spring-boot-starter-jetty + +``` + +下面的Gradle例子展示了如何在Spring WebFlux中排除Netty并包含Undertow: +``` +configurations { + // exclude Reactor Netty + compile.exclude module: 'spring-boot-starter-reactor-netty' +} + +dependencies { + compile 'org.springframework.boot:spring-boot-starter-webflux' + // Use Undertow instead + compile 'org.springframework.boot:spring-boot-starter-undertow' + // ... +} +``` + +**注** `spring-boot-starter-reactor-netty`需要使用`WebClient`类,所以即使需要包含不同的HTTP服务器,也可能需要保持对Netty的依赖。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.10 Running Behind a Front-end Proxy Server.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.10 Running Behind a Front-end Proxy Server.md" new file mode 100644 index 00000000..3d826b74 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.10 Running Behind a Front-end Proxy Server.md" @@ -0,0 +1,7 @@ +### 75.10 在前端代理服务器后运行 + +你的应用可能需要发送`302`跳转或使用指向自己的绝对路径渲染内容。当在代理服务器后面运行时,调用者需要的是代理服务器链接而不是部署应用的实际物理机器地址,通常的解决方式是代理服务器将前端地址放到headers并告诉后端服务器如何拼装链接。 + +如果代理添加约定的`X-Forwarded-For`和`X-Forwarded-Proto` headers(大多数代理服务器会这样做),只要将`application.properties`中的`server.use-forward-headers`设置为`true`,绝对链接就能正确的渲染。 + +**注** 如果应用运行在Cloud Foundry或Heroku,`server.use-forward-headers`属性默认为`true`。其他实例默认为`false`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.10.1 Customize Tomcat\342\200\231s Proxy Configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.10.1 Customize Tomcat\342\200\231s Proxy Configuration.md" new file mode 100644 index 00000000..b1667b27 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.10.1 Customize Tomcat\342\200\231s Proxy Configuration.md" @@ -0,0 +1,16 @@ +### 75.10.1 自定义Tomcat代理配置 + +如果使用的是Tomcat,你可以配置用于传输"forwarded"信息的headers名: +```properties +server.tomcat.remote-ip-header=x-your-remote-ip-header +server.tomcat.protocol-header=x-your-protocol-header +``` +你也可以为Tomcat配置一个默认的正则表达式,用来匹配内部信任的代理。默认情况下,IP地址`10/8`,`192.168/16`,`169.254/16`和`127/8`是被信任的。通过设置`server.tomcat.internal-proxies`属性可以自定义,比如: +```properties +server.tomcat.internal-proxies=192\\.168\\.\\d{1,3}\\.\\d{1,3} +``` +**注** 只有在使用配置文件时才需要双反斜线,如果使用YAML,只需要单个反斜线,比如`192\.168\.\d{1,3}\.\d{1,3}`。 + +**注** 将`internal-proxies`设置为空表示信任所有代理,不要在生产环境使用。 + +你可以完全控制Tomcat的`RemoteIpValve`配置,只要关掉自动配置(比如设置`server.use-forward-headers=false`)并在`TomcatServletWebServerFactory` bean添加一个新value实例。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.11 Configure Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.11 Configure Tomcat.md" new file mode 100644 index 00000000..3439eb03 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.11 Configure Tomcat.md" @@ -0,0 +1,5 @@ +### 75.11 配置Tomcat + +通常你可以遵循[74.8 发现外部属性的内置选项](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(这里主要的是`ServerProperties`)的建议,但也看下`WebServerFactoryCustomizer`和各种你可以添加的Tomcat特定的`*Customizers`。 + +Tomcat APIs相当丰富,一旦获取到`TomcatServletWebServerFactory`,你就能够以多种方式修改它,或更彻底地就是添加你自己的`TomcatServletWebServerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.12 Enable Multiple Connectors with Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.12 Enable Multiple Connectors with Tomcat.md" new file mode 100644 index 00000000..0951a023 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.12 Enable Multiple Connectors with Tomcat.md" @@ -0,0 +1,34 @@ +### 75.12 启用Tomcat的多连接器 + +你可以将`org.apache.catalina.connector.Connector`添加到`TomcatServletWebServerFactory`,这就能够允许多连接器,比如HTTP和HTTPS连接器: +```java +@Bean +public ServletWebServerFactory servletContainer() { + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); + tomcat.addAdditionalTomcatConnectors(createSslConnector()); + return tomcat; +} + +private Connector createSslConnector() { + Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); + Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler(); + try { + File keystore = new ClassPathResource("keystore").getFile(); + File truststore = new ClassPathResource("keystore").getFile(); + connector.setScheme("https"); + connector.setSecure(true); + connector.setPort(8443); + protocol.setSSLEnabled(true); + protocol.setKeystoreFile(keystore.getAbsolutePath()); + protocol.setKeystorePass("changeit"); + protocol.setTruststoreFile(truststore.getAbsolutePath()); + protocol.setTruststorePass("changeit"); + protocol.setKeyAlias("apitester"); + return connector; + } + catch (IOException ex) { + throw new IllegalStateException("can't access keystore: [" + "keystore" + + "] or truststore: [" + "keystore" + "]", ex); + } +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.13 Use Tomcat\342\200\231s LegacyCookieProcessor.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.13 Use Tomcat\342\200\231s LegacyCookieProcessor.md" new file mode 100644 index 00000000..411c814f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.13 Use Tomcat\342\200\231s LegacyCookieProcessor.md" @@ -0,0 +1,14 @@ +### 75.13 使用Tomcat的LegacyCookieProcessor + +默认的,Spring Boot使用的内嵌Tomcat不能支持`Version 0`的Cookie格式,你可能会看到以下错误: +```java +java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value +``` +可以的话,你需要考虑将代码升级到只存储遵从最新版Cookie定义的值。如果不能改变写入的cookie,你可以配置Tomcat使用`LegacyCookieProcessor`。通过向`WebServerFactoryCustomizer`bean添加一个`TomcatContextCustomizer`可以开启`LegacyCookieProcessor`: +```java +@Bean +public WebServerFactoryCustomizer cookieProcessorCustomizer() { + return (factory) -> factory.addContextCustomizers( + (context) -> context.setCookieProcessor(new LegacyCookieProcessor())); +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.14 Configure Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.14 Configure Undertow.md" new file mode 100644 index 00000000..67e653d5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.14 Configure Undertow.md" @@ -0,0 +1,3 @@ +### 75.14 配置Undertow + +通常你可以遵循[74.8 发现外部属性的内置选项](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(此处主要是`ServerProperties`和`ServerProperties.Undertow`),但也要看下`WebServerFactoryCustomizer`。一旦获取到`UndertowServletWebServerFactory`,你就可以使用`UndertowBuilderCustomizer`修改Undertow的配置以满足你的需求,或更彻底地就是添加你自己的`UndertowServletWebServerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.15 Enable Multiple Listeners with Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.15 Enable Multiple Listeners with Undertow.md" new file mode 100644 index 00000000..8ee7168c --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.15 Enable Multiple Listeners with Undertow.md" @@ -0,0 +1,18 @@ +### 75.15 启用Undertow的多监听器 + +将`UndertowBuilderCustomizer`添加到`UndertowServletWebServerFactory`,然后使用`Builder`添加一个listener: +```java +@Bean +public UndertowServletWebServerFactory servletWebServerFactory() { + UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(); + factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { + + @Override + public void customize(Builder builder) { + builder.addHttpListener(8080, "0.0.0.0"); + } + + }); + return factory; +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.16 Create WebSocket Endpoints Using @ServerEndpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.16 Create WebSocket Endpoints Using @ServerEndpoint.md" new file mode 100644 index 00000000..58f13d01 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.16 Create WebSocket Endpoints Using @ServerEndpoint.md" @@ -0,0 +1,10 @@ +### 75.16 使用@ServerEndpoint创建WebSocket端点 + +如果想在使用内嵌容器的Spring Boot应用中使用`@ServerEndpoint`,你需要声明一个单独的`ServerEndpointExporter` `@Bean`: +```java +@Bean +public ServerEndpointExporter serverEndpointExporter() { + return new ServerEndpointExporter(); +} +``` +该bean将使用底层的WebSocket容器注册任何被`@ServerEndpoint`注解的beans。当部署到一个单独的servlet容器时,该角色将被一个servlet容器初始化方法执行,`ServerEndpointExporter` bean也就不需要了。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.17 Enable HTTP Response Compression.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.17 Enable HTTP Response Compression.md" new file mode 100644 index 00000000..79252801 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.17 Enable HTTP Response Compression.md" @@ -0,0 +1,14 @@ +### 75.17 启用HTTP响应压缩 + +Jetty,Tomcat和Undertow支持HTTP响应压缩,你可以通过设置`server.compression.enabled`启用它: +```properties +server.compression.enabled=true +``` +默认情况下,响应信息长度至少2048字节才能触发压缩,通过`server.compression.min-response-size`属性可以改变该长度。另外,只有响应的content type为以下其中之一时才压缩: + +- `text/html` +- `text/xml` +- `text/plain` +- `text/css` + +你可以通过`server.compression.mime-types`属性配置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.2 Configure Jetty.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.2 Configure Jetty.md" new file mode 100644 index 00000000..333d2549 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.2 Configure Jetty.md" @@ -0,0 +1,3 @@ +### 75.2 配置Jetty + +通常,你可以遵循[74.8 发现外部属性的内置选项](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`的部分(`ServerProperties`是这里的主要选项)。但是,你还应该查看[WebServerFactoryCustomizer](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/web/server/WebServerFactoryCustomizer.html)。Jetty API非常丰富。因此,一旦你访问了`JettyServletWebServerFactory`,就可以通过多种方式修改它。或者,如果需要更多的控制和定制,可以添加自己的`JettyServletWebServerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.3 Add a Servlet, Filter, or Listener to an Application.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.3 Add a Servlet, Filter, or Listener to an Application.md" new file mode 100644 index 00000000..18181e81 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.3 Add a Servlet, Filter, or Listener to an Application.md" @@ -0,0 +1,6 @@ +### 75.3 为应用添加Servlet、Filter或Listener + +这里有两种方式可以为应用添加`Servlet`、`Filter`、`ServletContextListener`和其他Servlet支持的特定listener。 + +- [75.3.1 使用Spring bean添加Servlet、Filter或Listener](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-add-a-servlet-filter-or-listener-as-spring-bean) +- [75.3.2 使用类路径扫描添加Servlet、Filter和Listener](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-add-a-servlet-filter-or-listener-using-scanning) diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.3.1 Add a Servlet, Filter, or Listener by Using a Spring Bean.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.3.1 Add a Servlet, Filter, or Listener by Using a Spring Bean.md" new file mode 100644 index 00000000..85c5a3df --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.3.1 Add a Servlet, Filter, or Listener by Using a Spring Bean.md" @@ -0,0 +1,21 @@ +### 75.3.1 使用Spring bean添加Servlet, Filter或Listener + +想要使用Spring bean添加`Servlet`,`Filter`或Servlet`*Listener`,你只需要为它提供一个`@Bean`定义,这种方式很适合注入配置或依赖。不过,需要注意的是它们不会导致其他很多beans的热初始化,因为它们需要在应用生命周期的早期进行安装(让它依赖`DataSource`或JPA配置不是好主意),你可以通过懒加载突破该限制(在第一次使用时才初始化)。 + +对于`Filters`或`Servlets`,你可以通过`FilterRegistrationBean`或`ServletRegistrationBean`添加映射和初始化参数。 + +**注** 在一个filter注册时,如果没指定`dispatcherType`,它将使用`REQUEST`。这与Servlet规范的默认dispatcher类型一致。 + +与任何其他Spring bean一样,你可以定义Servlet筛选器bean的顺序。请确保查看了[将Servlet、Filter和listener注册为Spring bean](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans)章节。 + +**禁止Servlet或Filter的注册** + +如上所述,任何`Servlet`或`Filter` bean都将自动注册到servlet容器。不过,为特定的`Filter`或`Servlet` bean创建一个registration,并将它标记为disabled,可以禁用该filter或servlet。例如: +```java +@Bean +public FilterRegistrationBean registration(MyFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean(filter); + registration.setEnabled(false); + return registration; +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.3.2 Add Servlets, Filters, and Listeners by Using Classpath Scanning.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.3.2 Add Servlets, Filters, and Listeners by Using Classpath Scanning.md" new file mode 100644 index 00000000..7625599e --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.3.2 Add Servlets, Filters, and Listeners by Using Classpath Scanning.md" @@ -0,0 +1,3 @@ +### 75.3.2 使用类路径扫描添加Servlet、Filter和Listener + +通过把`@ServletComponentScan`注解到一个`@Configuration`类并指定包含要注册组件的包,可以将`@WebServlet`,`@WebFilter`和`@WebListener`注解的类自动注册到内嵌servlet容器。默认情况下,`@ServletComponentScan`将从被注解类的包开始扫描。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.4 Change the HTTP Port.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.4 Change the HTTP Port.md" new file mode 100644 index 00000000..86d6d4b5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.4 Change the HTTP Port.md" @@ -0,0 +1,5 @@ +### 75.4 改变HTTP端口 + +在一个单独的应用中,主HTTP端口默认为`8080`,不过可以使用`server.port`设置(比如,在`application.properties`中或作为系统属性)。由于`Environment`值的宽松绑定,你也可以使用`SERVER_PORT`(比如,作为OS环境变量)。 + +想要创建`WebApplicationContext`但完全关闭HTTP端点,你可以设置`server.port=-1`(测试时可能有用)。具体详情可查看'Spring Boot特性'章节的[27.4.4 自定义内嵌servlet容器](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-customizing-embedded-containers),或[ServerProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.5 Use a Random Unassigned HTTP Port.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.5 Use a Random Unassigned HTTP Port.md" new file mode 100644 index 00000000..576d8776 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.5 Use a Random Unassigned HTTP Port.md" @@ -0,0 +1,3 @@ +### 75.5 使用随机未分配的HTTP端口 + +想扫描获取一个未使用的端口(使用操作系统本地端口以防冲突)可以设置`server.port=0`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.6 Discover the HTTP Port at Runtime.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.6 Discover the HTTP Port at Runtime.md" new file mode 100644 index 00000000..dee15006 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.6 Discover the HTTP Port at Runtime.md" @@ -0,0 +1,21 @@ +### 75.6 在运行时发现HTTP端口 + +你可以从输出的日志或通过它的`EmbeddedWebServer`从`ServletWebServerApplicationContext`获取服务器正在运行的端口。获取和确认服务器已经初始化的最好方式是添加一个`ApplicationListener`类型的`@Bean`,然后当事件发布时将容器pull出来。 + +使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`进行测试时,你可以通过`@LocalServerPort`注解将实际端口注入到字段中,例如: +```java +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) +public class MyWebIntegrationTests { + + @Autowired + ServletWebServerApplicationContext server; + + @LocalServerPort + int port; + + // ... + +} +``` +**注** `@LocalServerPort`是`@Value("${local.server.port}")`的元数据,在常规的应用中不要尝试注入端口。正如我们看到的,该值只会在容器初始化后设置。相对于测试,应用代码回调处理的会更早(例如在该值实际可用之前)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.7 Configure SSL.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.7 Configure SSL.md" new file mode 100644 index 00000000..15e5d937 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.7 Configure SSL.md" @@ -0,0 +1,12 @@ +### 75.7 配置SSL + +你可以以声明方式配置SSL,一般通过在`application.properties`或`application.yml`设置各种各样的`server.ssl.*`属性,例如: +```json +server.port = 8443 +server.ssl.key-store = classpath:keystore.jks +server.ssl.key-store-password = secret +server.ssl.key-password = another-secret +``` +查看[Ssl](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/Ssl.java)获取所有支持的配置。 + +使用类似于以上示例的配置意味着该应用将不支持端口为8080的普通HTTP连接。Spring Boot不支持通过`application.properties`同时配置HTTP连接器和HTTPS连接器。如果你两个都想要,那就需要以编程的方式配置它们中的一个。推荐使用`application.properties`配置HTTPS,因为HTTP连接器是两个中最容易以编程方式进行配置的,查看[spring-boot-sample-tomcat-multi-connectors](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors)可获取示例项目。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.8 Configure HTTP2.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.8 Configure HTTP2.md" new file mode 100644 index 00000000..9c1aa272 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.8 Configure HTTP2.md" @@ -0,0 +1,5 @@ +### 75.8 配置HTTP/2 + +你可以使用`server.http2.enabled`配置属性,在Spring Boot应用程序中启用HTTP/2支持。这项支持取决于所选的web服务器和应用程序环境,因为JDK8不支持那个协议开箱即用。 + +**注** Spring Boot不支持`h2c`,即明文版本的HTTP/2协议。因此必须[首先配置SSL](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-configure-ssl)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.8.1 HTTP2 with Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.8.1 HTTP2 with Undertow.md" new file mode 100644 index 00000000..c2c429a7 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.8.1 HTTP2 with Undertow.md" @@ -0,0 +1,3 @@ +### 75.8.1 HTTP/2与Undertow + +Undertow从1.4.0+开始,在JDK8上支持HTTP/2,不需要任何额外的要求。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.8.2 HTTP2 with Jetty.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.8.2 HTTP2 with Jetty.md" new file mode 100644 index 00000000..b6fe2a0a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.8.2 HTTP2 with Jetty.md" @@ -0,0 +1,3 @@ +### 75.8.2 HTTP/2与Jetty + +从Jetty 9.4.8开始,Conscrypt库也支持HTTP/2。要启用这种支持,你的应用程序需要有两个附加的依赖项:`org.eclipse.jetty:jetty-alpn-conscrypt-server`和`org.eclipse.jetty.http2:http2-server`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.8.3 HTTP2 with Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.8.3 HTTP2 with Tomcat.md" new file mode 100644 index 00000000..5991f890 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.8.3 HTTP2 with Tomcat.md" @@ -0,0 +1,13 @@ +### 75.8.3 HTTP/2与Tomcat + +默认情况下,Spring Boot提供Tomcat 8.5.x。对于该版本,只有在主机操作系统上安装了`libtcnative`库及其依赖项时,才支持HTTP/2。 + +必须使库文件夹对JVM库路径可用。你可以使用诸如`-Djava.library.path=/usr/local/opt/tomcat-native/lib`这样的JVM参数来实现这一点。关于这方面的更多信息,请参阅[Tomcat官方文档](https://tomcat.apache.org/tomcat-8.5-doc/apr.html)。 +在没有那个本地支持的情况下启动Tomcat 8.5,会记录以下错误: +``` +ERROR 8787 --- [ main] o.a.coyote.http11.Http11NioProtocol : The upgrade handler [org.apache.coyote.http2.Http2Protocol] for [h2] only supports upgrade via ALPN but has been configured for the ["https-jsse-nio-8443"] connector that does not support ALPN. +``` + +这个错误不是致命的,应用程序仍然使用HTTP/1.1 SSL支持启动。 + +使用Tomcat 9.0.x与JDK9运行应用程序,不需要安装任何本机库。要使用Tomcat 9,可以覆盖`tomcat.version`构建属性,来使用你选择的版本。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.9 Configure Access Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.9 Configure Access Logging.md" new file mode 100644 index 00000000..b387a28f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.9 Configure Access Logging.md" @@ -0,0 +1,23 @@ +### 75.9 配置访问日志 + +通过相应的命令空间可以为Tomcat、Undertow和Jetty配置访问日志,例如下面是为Tomcat配置的一个[自定义模式](https://tomcat.apache.org/tomcat-8.5-doc/config/valve.html#Access_Logging)的访问日志: +```properties +server.tomcat.basedir=my-tomcat +server.tomcat.accesslog.enabled=true +server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms) +``` +**注** 日志默认路径为Tomcat基础路径下的`logs`目录,该dir默认是个临时目录,所以你可能想改变Tomcat的base目录或为日志指定绝对路径。上述示例中,你可以在相对于应用工作目录的`my-tomcat/logs`访问到日志。 + +Undertow的访问日志配置方式类似: +```properties +server.undertow.accesslog.enabled=true +server.undertow.accesslog.pattern=%t %a "%r" %s (%D ms) +``` +日志存储在相对于应用工作目录的`logs`目录下,可以通过`server.undertow.accesslog.directory`属性自定义。 + +最后,Jetty的访问日志也可以这样配置: +```properties +server.jetty.accesslog.enabled=true +server.jetty.accesslog.filename=/var/log/jetty-access.log +``` +默认地,日志会被重定向到`System.err`。更多细节,请查看[Jetty文档](https://www.eclipse.org/jetty/documentation/9.4.x/configuring-jetty-request-logs.html)。 \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76. Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/76. Logging.md" deleted file mode 100644 index fdca95be..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/76. Logging.md" +++ /dev/null @@ -1,17 +0,0 @@ -### 76. 日志 - -Spring Boot除了`commons-logging`API外没有其他强制性的日志依赖,你有很多可选的日志实现。想要使用[Logback](http://logback.qos.ch/),你需要包含它及`jcl-over-slf4j`(它实现了Commons Logging API)。最简单的方式是通过依赖`spring-boot-starter-logging`的starters。对于一个web应用程序,你只需添加`spring-boot-starter-web`依赖,因为它依赖于logging starter。例如,使用Maven: -```xml - - org.springframework.boot - spring-boot-starter-web - -``` -Spring Boot有一个`LoggingSystem`抽象,用于尝试通过classpath上下文配置日志系统。如果Logback可用,则首选它。如果你唯一需要做的就是设置不同日志级别,那可以通过在`application.properties`中使用`logging.level`前缀实现,比如: -```java -logging.level.org.springframework.web=DEBUG -logging.level.org.hibernate=ERROR -``` -你也可以使用`logging.file`设置日志文件的位置(除控制台之外,默认会输出到控制台)。 - -想要对日志系统进行更细粒度的配置,你需要使用`LoggingSystem`支持的原生配置格式。默认情况下,Spring Boot从系统的默认位置加载原生配置(比如对于Logback为`classpath:logback.xml`),但你可以使用`logging.config`属性设置配置文件的位置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76. Spring MVC.md" "b/IX. \342\200\230How-to\342\200\231 guides/76. Spring MVC.md" new file mode 100644 index 00000000..b03d0e94 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76. Spring MVC.md" @@ -0,0 +1,3 @@ +### 76. Spring MVC + +Spring Boot有许多starter,包括Spring MVC。注意,一些starter包含了对Spring MVC的依赖,而不是直接包含它。本节回答有关Spring MVC和Spring Boot的常见问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.1 Configure Logback for logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.1 Configure Logback for logging.md" deleted file mode 100644 index 1faa746e..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/76.1 Configure Logback for logging.md" +++ /dev/null @@ -1,19 +0,0 @@ -### 76.1 配置Logback - -如果你将`logback.xml`放到classpath根目录下,那它将会被从这加载(或`logback-spring.xml`充分利用Boot提供的模板特性)。Spring Boot提供一个默认的基本配置,如果你只是设置日志级别,那你可以包含它,比如: -```xml - - - - - -``` -如果查看spring-boot jar中的`base.xml`,你将会看到`LoggingSystem`为你创建的很多有用的系统属性,比如: -- `${PID}`,当前进程id。 -- `${LOG_FILE}`,如果在Boot外部配置中设置了`logging.file`。 -- `${LOG_PATH}`,如果设置了`logging.path`(表示日志文件产生的目录)。 -- `${LOG_EXCEPTION_CONVERSION_WORD}`,如果在Boot外部配置中设置了`logging.exception-conversion-word`。 - -Spring Boot也提供使用自定义的Logback转换器在控制台上输出一些漂亮的彩色ANSI日志信息(不是日志文件),具体参考默认的`base.xml`配置。 - -如果Groovy在classpath下,你也可以使用`logback.groovy`配置Logback。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.1 Write a JSON REST Service.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.1 Write a JSON REST Service.md" new file mode 100644 index 00000000..9e76abd5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.1 Write a JSON REST Service.md" @@ -0,0 +1,15 @@ +### 76.1 编写JSON REST服务 + +只要添加的有Jackson2依赖,Spring Boot应用中的任何`@RestController`默认都会渲染为JSON响应,例如: +```java +@RestController +public class MyController { + +    @RequestMapping("/thing") +    public MyThing thing() { + return new MyThing(); + } + +} +``` +只要`MyThing`能够通过Jackson2序列化(比如,一个标准的POJO或Groovy对象),默认[localhost:8080/thing](http://localhost:8080/thing)将响应一个JSON数据。有时在浏览器中你可能看到XML响应,因为浏览器倾向于发送XML accept headers。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.1.1 Configure logback for file only output.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.1.1 Configure logback for file only output.md" deleted file mode 100644 index c23e4913..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/76.1.1 Configure logback for file only output.md" +++ /dev/null @@ -1,18 +0,0 @@ -###76.1.1 配置logback只输出到文件 - -如果想禁用控制台日志记录,只将输出写入文件中,你需要一个只导入`file-appender.xml`而不是`console-appender.xml`的自定义`logback-spring.xml`: -```xml - - - - - - - - - -``` -你还需要将`logging.file`添加到`application.properties`: -```properties -logging.file=myapplication.log -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.2 Configure Log4j for logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.2 Configure Log4j for logging.md" deleted file mode 100644 index 50ae8040..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/76.2 Configure Log4j for logging.md" +++ /dev/null @@ -1,27 +0,0 @@ -### 76.2 配置Log4j - -如果[Log4j 2](http://logging.apache.org/log4j/2.x)出现在classpath下,Spring Boot会将其作为日志配置。如果你正在使用starters进行依赖装配,这意味着你需要排除Logback,然后包含log4j 2。如果不使用starters,除了添加Log4j 2,你还需要提供`jcl-over-slf4j`依赖(至少)。 - -最简单的方式可能就是通过starters,尽管它需要排除一些依赖,比如,在Maven中: -```xml - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 - -``` - -**注** Log4j starters会收集好依赖以满足普通日志记录的需求(比如,Tomcat中使用`java.util.logging`,但使用Log4j 2作为输出),具体查看Actuator Log4j 2的示例,了解如何将它用于实战。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.2 Write an XML REST Service.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.2 Write an XML REST Service.md" new file mode 100644 index 00000000..40d33034 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.2 Write an XML REST Service.md" @@ -0,0 +1,25 @@ +### 76.2 编写XML REST服务 + +如果classpath下存在Jackson XML扩展(`jackson-dataformat-xml`),它会被用来渲染XML响应,示例和JSON的非常相似。想要使用Jackson XML渲染器,只需为你的项目添加以下依赖: +```xml + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + +``` +你可能还需要添加Woodstox的依赖,它比JDK提供的默认StAX实现快很多,并且支持良好的格式化输出,提高了namespace处理能力: +```xml + + org.codehaus.woodstox + woodstox-core-asl + +``` +如果Jackson的XML扩展不可用,Spring Boot将使用JAXB(JDK默认提供),不过`MyThing`需要注解`@XmlRootElement`: +```java +@XmlRootElement +public class MyThing { + private String name; + // .. getters and setters +} +``` +想要服务器渲染XML而不是JSON,你可能需要发送一个`Accept: text/xml`头部(或使用浏览器)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.2.1 Use YAML or JSON to configure Log4j 2.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.2.1 Use YAML or JSON to configure Log4j 2.md" deleted file mode 100644 index 3fbafb87..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/76.2.1 Use YAML or JSON to configure Log4j 2.md" +++ /dev/null @@ -1,8 +0,0 @@ -### 76.2.1 使用YAML或JSON配置Log4j2 - -除了它的默认XML配置格式,Log4j 2也支持YAML和JSON配置文件。想使用其他配置文件格式配置Log4j 2,你需要添加合适的依赖到classpath,并以匹配所选格式的方式命名配置文件: - -|格式|依赖|文件名| -|:----|:----|:---| -|YAML|`com.fasterxml.jackson.core:jackson-databind` `com.fasterxml.jackson.dataformat:jackson-dataformat-yaml`|`log4j2.yaml` `log4j2.yml`| -|JSON|`com.fasterxml.jackson.core:jackson-databind`|`log4j2.json` `log4j2.jsn`| diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.3 Customize the Jackson ObjectMapper.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.3 Customize the Jackson ObjectMapper.md" new file mode 100644 index 00000000..f4de4ba4 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.3 Customize the Jackson ObjectMapper.md" @@ -0,0 +1,34 @@ +### 76.3 自定义Jackson ObjectMapper + +在一个HTTP交互中,Spring MVC(客户端和服务端)使用`HttpMessageConverters`协商内容转换。如果classpath下存在Jackson,你就获取到`Jackson2ObjectMapperBuilder`提供的默认转换器,这是Spring Boot为你自动配置的实例。 + +创建的`ObjectMapper`(或用于Jackson XML转换的`XmlMapper`)实例默认有以下自定义属性: + +- `MapperFeature.DEFAULT_VIEW_INCLUSION`,默认是禁用的 +- `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`,默认是禁用的 +- `SerializationFeature.WRITE_DATES_AS_TIMESTAMPS`,默认是禁用的 + +Spring Boot也有一些用于简化自定义该行为的特性。 + +你可以使用当前的environment配置`ObjectMapper`和`XmlMapper`实例。Jackson提供一个扩展套件,可以用来关闭或开启一些特性,你可以用它们配置Jackson以处理不同方面。这些特性在Jackson中是使用6个枚举进行描述的,并被映射到environment的属性上: + +|Jackson枚举|Environment属性| +|------|:-------| +|`com.fasterxml.jackson.databind.DeserializationFeature`|`spring.jackson.deserialization.=true|false`| +|`com.fasterxml.jackson.core.JsonGenerator.Feature`|`spring.jackson.generator.=true|false`| +|`com.fasterxml.jackson.databind.MapperFeature`|`spring.jackson.mapper.=true|false`| +|`com.fasterxml.jackson.core.JsonParser.Feature`|`spring.jackson.parser.=true|false`| +|`com.fasterxml.jackson.databind.SerializationFeature`|`spring.jackson.serialization.=true|false`| +|`com.fasterxml.jackson.annotation.JsonInclude.Include`|`spring.jackson.serialization-inclusion=always|non_null|non_absent|non_default|non_empty`| + +例如,设置`spring.jackson.serialization.indent_output=true`可以美化打印输出(pretty print)。注意,由于[松散绑定](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-relaxed-binding)的使用,`indent_output`不必匹配对应的枚举常量`INDENT_OUTPUT`。 + +基于environment的配置会应用到自动配置的`Jackson2ObjectMapperBuilder` bean,然后应用到通过该builder创建的mappers,包括自动配置的`ObjectMapper` bean。 + +`ApplicationContext`中的`Jackson2ObjectMapperBuilder`可以通过`Jackson2ObjectMapperBuilderCustomizer` bean自定义。这些customizer beans可以排序(Spring Boot自己的customizer序号为0)。其他自定义可以应用到Spring Boot自定义之前或之后。 + +所有类型为`com.fasterxml.jackson.databind.Module`的beans都会自动注册到自动配置的`Jackson2ObjectMapperBuilder`,并应用到它创建的任何`ObjectMapper`实例。这提供了一种全局机制,用于在为应用添加新特性时贡献自定义模块。 + +如果想完全替换默认的`ObjectMapper`,你既可以定义该类型的`@Bean`并注解`@Primary`,也可以定义`Jackson2ObjectMapperBuilder` `@Bean`,通过builder构建。注意不管哪种方式都会禁用所有的自动配置`ObjectMapper`。 + +如果你提供`MappingJackson2HttpMessageConverter`类型的`@Bean`,它们将替换MVC配置中的默认值。Spring Boot也提供了一个`HttpMessageConverters`类型的便利bean(如果你使用MVC默认配置,那它就总是可用的),它提供了一些有用的方法来获取默认和用户增强的消息转换器(message converters)。具体详情可参考[76.4 自定义@ResponseBody渲染](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-customize-the-responsebody-rendering)及[WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.4 Customize the @ResponseBody Rendering.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.4 Customize the @ResponseBody Rendering.md" new file mode 100644 index 00000000..54c3250f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.4 Customize the @ResponseBody Rendering.md" @@ -0,0 +1,7 @@ +### 76.4 自定义@ResponseBody渲染 + +Spring使用`HttpMessageConverters`渲染`@ResponseBody`(或来自`@RestController`的响应)。你可以通过在Spring Boot上下文中添加该类型的beans来贡献其他的转换器。如果你添加的bean类型默认已经包含了(像用于JSON转换的`MappingJackson2HttpMessageConverter`),那它将替换默认的。Spring Boot提供一个`HttpMessageConverters`类型的bean,它有一些有用的方法可以访问默认的和用户增强的message转换器(比如你想要手动将它们注入到一个自定义的`RestTemplate`时就很有用)。 + +在通常的MVC用例中,任何你提供的`WebMvcConfigurer` beans通过覆盖`configureMessageConverters`方法也能贡献转换器,但不同于通常的MVC,你可以只提供你需要的转换器(因为Spring Boot使用相同的机制来贡献它默认的转换器)。最终,如果你通过提供自己的` @EnableWebMvc`注解覆盖Spring Boot默认的MVC配置,那你就可以完全控制,并使用来自`WebMvcConfigurationSupport`的`getMessageConverters`手动做任何事。 + +更多详情可参考[WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.5 Handling Multipart File Uploads.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.5 Handling Multipart File Uploads.md" new file mode 100644 index 00000000..3327edba --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.5 Handling Multipart File Uploads.md" @@ -0,0 +1,7 @@ +### 76.5 处理Multipart文件上传 + +Spring Boot采用Servlet 3 `javax.servlet.http.Part` API来支持文件上传。默认情况下,Spring Boot配置Spring MVC在单个请求中只处理每个文件最大1MB,最多10MB的文件数据。你可以覆盖那些值,也可以设置临时文件存储的位置(比如,存储到`/tmp`文件夹下)及传递数据刷新到磁盘的阀值(通过使用`MultipartProperties`类暴露的属性)。如果你需要设置文件不受限制,可以设置`spring.servlet.multipart.max-file-size`属性值为`-1`。 + +当你想要接收multipart编码文件数据作为Spring MVC控制器(controller)处理方法中被`@RequestParam`注解的`MultipartFile`类型的参数时,multipart支持就非常有用了。 + +更多详情可参考[MultipartAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.6 Switch Off the Spring MVC DispatcherServlet.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.6 Switch Off the Spring MVC DispatcherServlet.md" new file mode 100644 index 00000000..3bfb2f21 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.6 Switch Off the Spring MVC DispatcherServlet.md" @@ -0,0 +1,3 @@ +### 76.6 关闭Spring MVC DispatcherServlet + +Spring Boot想要服务来自应用程序root(`/`)下的所有内容。如果你想将自己的servlet映射到该目录下也是可以的,但当然你可能失去一些Spring Boot MVC特性。为了添加你自己的servlet,并将它映射到root资源,你只需声明一个`Servlet`类型的`@Bean`,并给它特定的bean名称`dispatcherServlet`(如果只想关闭但不替换它,你可以使用该名称创建不同类型的bean)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.7 Switch off the Default MVC Configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.7 Switch off the Default MVC Configuration.md" new file mode 100644 index 00000000..184de21f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.7 Switch off the Default MVC Configuration.md" @@ -0,0 +1,3 @@ +### 76.7 关闭默认的MVC配置 + +完全控制MVC配置的最简单方式是提供你自己的被`@EnableWebMvc`注解的`@Configuration`,这样所有的MVC配置都逃不出你的掌心。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.8 Customize ViewResolvers.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.8 Customize ViewResolvers.md" new file mode 100644 index 00000000..7314c3a8 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.8 Customize ViewResolvers.md" @@ -0,0 +1,18 @@ +### 76.8 自定义ViewResolvers + +`ViewResolver`是Spring MVC的核心组件,它负责转换`@Controller`中的视图名称到实际的`View`实现。注意`ViewResolvers`主要用在UI应用中,而不是REST风格的服务(`View`不是用来渲染`@ResponseBody`的)。Spring有很多你可以选择的`ViewResolver`实现,并且Spring自己对如何选择相应实现也没发表意见。另一方面,Spring Boot会根据classpath上的依赖和应用上下文为你安装一或两个`ViewResolver`实现。`DispatcherServlet`使用所有在应用上下文中找到的解析器(resolvers),并依次尝试每一个直到它获取到结果,所以如果你正在添加自己的解析器,那就要小心顺序和你的解析器添加的位置。 + +`WebMvcAutoConfiguration`将会为你的上下文添加以下`ViewResolvers`: + +- 名为`defaultViewResolver`的`InternalResourceViewResolver`,它会定位可以使用`DefaultServlet`渲染的物理资源(比如静态资源和JSP页面)。它在视图名上应用了一个前缀和后缀(默认都为空,但你可以通过`spring.view.prefix`和`spring.view.suffix`设置),然后查找在servlet上下文中具有该路径的物理资源,可以通过提供相同类型的bean覆盖它。 +- 名为`beanNameViewResolver`的`BeanNameViewResolver`,它是视图解析器链的一个非常有用的成员,可以在`View`解析时收集任何具有相同名称的beans,没必要覆盖或替换它。 +- 名为`viewResolver`的`ContentNegotiatingViewResolver`,它只会在实际`View`类型的beans出现时添加。这是一个'master'解析器,它的职责会代理给其他解析器,它会尝试找到客户端发送的一个匹配'Accept'的HTTP头部。这有一篇关于[ContentNegotiatingViewResolver](https://spring.io/blog/2013/06/03/content-negotiation-using-views)的博客,你也可以也查看下源码。通过定义一个名叫'viewResolver'的bean,你可以关闭自动配置的`ContentNegotiatingViewResolver`。 +- 如果使用Thymeleaf,你将有一个id为`thymeleafViewResolver`的`ThymeleafViewResolver`,它会通过加前缀和后缀的视图名来查找资源(外部配置为`spring.thymeleaf.prefix`和`spring.thymeleaf.suffix`,对应的默认为'classpath:/templates/'和'.html')。你可以通过提供相同名称的bean来覆盖它。 +- 如果使用FreeMarker,你将有一个名为`freeMarkerViewResolver`的`FreeMarkerViewResolver`,它会使用加前缀和后缀。它通过在视图名周围加上前缀和后缀来查找加载器路径中的资源(加载器路径外化为`spring.freemarker.templateLoaderPath`,默认值为`classpath:/templates/`)。前缀外部化为`spring.freemarker.prefix`,后缀外部化为`spring.freemarker.suffix`。前缀和后缀的默认值为空和`.ftl`。你可以通过提供同名的bean来覆盖`FreeMarkerViewResolver`。 +- 如果使用Groovy模板(实际上只要你把groovy-templates添加到classpath下),你将有一个名为`groovyTemplateViewResolver`的`Groovy TemplateViewResolver`。它会使用加前缀和后缀(外部属性为`spring.groovy.template.prefix`和`spring.groovy.template.suffix`,对应的默认值为`classpath:/templates/`和`.tpl`)的视图名从加载路径下查找资源。你可以通过提供同名的bean来覆盖它。 + +更多详情,可查看下列章节: +- [WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java) +- [ThymeleafAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java) +- [FreeMarkerAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java) +- [GroovyTemplateAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77. Data Access.md" "b/IX. \342\200\230How-to\342\200\231 guides/77. Data Access.md" deleted file mode 100644 index cf1c449c..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77. Data Access.md" +++ /dev/null @@ -1 +0,0 @@ -### 77. 数据访问 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77. HTTP Clients.md" "b/IX. \342\200\230How-to\342\200\231 guides/77. HTTP Clients.md" new file mode 100644 index 00000000..aa2dcae5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/77. HTTP Clients.md" @@ -0,0 +1,3 @@ +### 77. HTTP客户端 + +Spring Boot提供了许多使用HTTP客户端的starter。本节回答与使用它们相关的问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.1 Configure RestTemplate to Use a Proxy.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.1 Configure RestTemplate to Use a Proxy.md" new file mode 100644 index 00000000..17790f00 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/77.1 Configure RestTemplate to Use a Proxy.md" @@ -0,0 +1,31 @@ +### 77.1 配置RestTemplate使用代理 + +正如[33.1 自定义RestTemplate](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-resttemplate-customization)描述的那样,你可以使用`RestTemplateCustomizer`和`RestTemplateBuilder`构建一个自定义的`RestTemplate`。这是创建使用代理的`RestTemplate`的推荐方式。 + +代理配置的确切细节取决于底层使用的客户端请求factory,这里有个示例演示`HttpClient`配置的`HttpComponentsClientRequestFactory`对所有hosts都使用代理,除了`192.168.0.5`。 +```java +static class ProxyCustomizer implements RestTemplateCustomizer { + + @Override + public void customize(RestTemplate restTemplate) { + HttpHost proxy = new HttpHost("proxy.example.com"); + HttpClient httpClient = HttpClientBuilder.create() + .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { + + @Override + public HttpHost determineProxy(HttpHost target, + HttpRequest request, HttpContext context) + throws HttpException { + if (target.getHostName().equals("192.168.0.5")) { + return null; + } + return super.determineProxy(target, request, context); + } + + }).build(); + restTemplate.setRequestFactory( + new HttpComponentsClientHttpRequestFactory(httpClient)); + } + +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.1 Configure a custom DataSource.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.1 Configure a custom DataSource.md" deleted file mode 100644 index 589edd1c..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.1 Configure a custom DataSource.md" +++ /dev/null @@ -1,84 +0,0 @@ -### 77.1 配置自定义的数据源 - -在你的配置中自定义那种类型的`@Bean`来配置你自己的`数据源`。需要的时候,Spring Boot将会重复使用你的`数据源`,包括数据库的初始化。如果你需要具体化一些配置,你可以轻松的将你的`数据源`跟环境绑定([查看24.7.1章节,“第三方配置”](../IV. Spring Boot features/24.7.1. Third-party configuration.md))。 -```java -@Bean -@ConfigurationProperties(prefix="app.datasource") -public DataSource dataSource() { - return new FancyDataSource(); -} -``` -```properties -app.datasource.url=jdbc:h2:mem:mydb -app.datasource.username=sa -app.datasource.pool-size=30 -``` -假设对于这个URL,你的`FancyDataSource`有一个常规的JavaBean属性。用户名和池的大小,这些设置将会在`数据源`对其它组件可用之前,被自动绑定。常规的[数据库初始化](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc)也将会发生(这样,相关的`spring.datasource.*`的子集仍旧可以在你的自定义配置中使用)。 - -如果你正在配置一个自定义的JNDI`数据源`,你可以应用相同的原则: -```java -@Bean(destroyMethod="") -@ConfigurationProperties(prefix="app.datasource") -public DataSource dataSource() throws Exception { - JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); - return dataSourceLookup.getDataSource("java:comp/env/jdbc/YourDS"); -} -``` -Spring Boot也提供了一个工具生成器类`DataSourceBuilder`,可以被用于生成标准的数据源(如果它在类路径上)。在类路径上哪个可用,生成器就会用哪个。它也会基于JDBC url自动探测驱动。 -```java -@Bean -@ConfigurationProperties("app.datasource") -public DataSource dataSource() { - return DataSourceBuilder.create().build(); -} -``` -运行一个带有那个`数据源`的应用,只需要连接信息。也可以提供指定池的设置。检查将要在运行时使用的实现,来获取更多细节。 -```properties -app.datasource.url=jdbc:mysql://localhost/test -app.datasource.username=dbuser -app.datasource.password=dbpass -app.datasource.pool-size=30 -``` -然而,这里有一个陷阱。因为连接池的实际类型没有被暴露,对于你自定义的`数据源`,在元数据中没有键值生成。同时,在你的IDE中也没有补全的方法(数据源接口没有暴露任何属性)。如果你的类路径里存在Hikari,基本的设置将不会生效,因为Hikari没有`url`参数(但有一个`jdbcUrl`参数)。你将不得不如下重写你的配置: -```properties -app.datasource.jdbc-url=jdbc:mysql://localhost/test -app.datasource.username=dbuser -app.datasource.password=dbpass -app.datasource.maximum-pool-size=30 -``` -你可以通过强制连接池使用和返回一个专用的实现而不是`数据源`来处理。你将无法在运行时改变实现,但是选项的列表将会明确。 -```java -@Bean -@ConfigurationProperties("app.datasource") -public HikariDataSource dataSource() { - return (HikariDataSource) DataSourceBuilder.create() - .type(HikariDataSource.class).build(); -} -``` -通过利用`DataSourceProperties`,你可以走得更远。如果没有url(带有可感测的用户名和密码)被提供,它提供一个默认的内嵌的数据库。你可以从任何`DataSourceProperties`的状态,轻松地初始化一个`DataSourceBuilder`。这样,你幸好可以注入Spring Boot自动创建的那个。可是,那将会把你的配置分离为两个命名空间:`spring.datasource`上的url,用户名,密码,类型和驱动,以及在你自定义的命名空间(`app.datasource`)上的剩余部分。为了避免这种情况,你可以在你自定义的命名空间,重新定义一个自定义的`DataSourceProperties`: -```java -@Bean -@Primary -@ConfigurationProperties("app.datasource") -public DataSourceProperties dataSourceProperties() { - return new DataSourceProperties(); -} - -@Bean -@ConfigurationProperties("app.datasource") -public HikariDataSource dataSource(DataSourceProperties properties) { - return (HikariDataSource) properties.initializeDataSourceBuilder() - .type(HikariDataSource.class).build(); -} -``` -这项设置与Spring Boot默认为你做的刚好是一对,除了一个专用的连接池被选择(在代码里),同时它的设置被暴露在相同的命名空间。因为`DataSourceProperties`会为你处理`url`或者`jdbcUrl`的翻译,你可以像这样配置它: -```properties -app.datasource.url=jdbc:mysql://localhost/test -app.datasource.username=dbuser -app.datasource.password=dbpass -app.datasource.maximum-pool-size=30 -``` - -**注** 因为你自定义的配置选择使用Hikari,`app.datasource.type`将会失效。实际上,生成器将会被任何你设置在那儿的值初始化,然后被`.type()`的调用重写。 - -具体详情可参考'Spring Boot特性'章节中的[Section 29.1, “Configure a DataSource”](../IV. Spring Boot features/29.1. Configure a DataSource.md)和[`DataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java)类源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.10 Use Spring Data JPA and Mongo repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.10 Use Spring Data JPA and Mongo repositories.md" deleted file mode 100644 index bae5c48b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.10 Use Spring Data JPA and Mongo repositories.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 77.10 使用Spring Data JPA和Mongo仓库 - -Spring Data JPA和Spring Data Mongo都能自动为你创建`Repository`实现。如果它们同时出现在classpath下,你可能需要添加额外的配置来告诉Spring Boot你想要哪个(或两个)为你创建仓库。最明确地方式是使用标准的Spring Data `@Enable*Repositories`,然后告诉它你的`Repository`接口的位置(此处`*`即可以是Jpa,也可以是Mongo,或者两者都是)。 - -这里也有`spring.data.*.repositories.enabled`标志,可用来在外部配置中开启或关闭仓库的自动配置,这在你想关闭Mongo仓库但仍使用自动配置的`MongoTemplate`时非常有用。 - -相同的障碍和特性也存在于其他自动配置的Spring Data仓库类型(Elasticsearch, Solr),只需要改变对应注解的名称和标志。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.11 Expose Spring Data repositories as REST endpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.11 Expose Spring Data repositories as REST endpoint.md" deleted file mode 100644 index ccc1bde4..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.11 Expose Spring Data repositories as REST endpoint.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 77.11 将Spring Data仓库暴露为REST端点 - -Spring Data REST能够将`Repository`的实现暴露为REST端点,只要该应用启用Spring MVC。Spring Boot暴露一系列来自`spring.data.rest`命名空间的有用属性来定制化[`RepositoryRestConfiguration`](http://docs.spring.io/spring-data/rest/docs/current/api/org/springframework/data/rest/core/config/RepositoryRestConfiguration.html),你可以使用[`RepositoryRestConfigurer`](http://docs.spring.io/spring-data/rest/docs/current/api/org/springframework/data/rest/webmvc/config/RepositoryRestConfigurer.html)提供其他定制。 - -**注** 如果你不在你自定义的`RepositoryRestConfigurer`上指定顺序,它将会在Spring Boot内部使用的那个之后运行。如果你需要指定顺序,确保它比0高。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.12 Configure a component that is used by JPA.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.12 Configure a component that is used by JPA.md" deleted file mode 100644 index b2fe0547..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.12 Configure a component that is used by JPA.md" +++ /dev/null @@ -1,20 +0,0 @@ -### 77.12 配置JPA使用的组件 - -如果想配置一个JPA使用的组件,你需要确保该组件在JPA之前初始化。组件如果是Spring Boot自动配置的,Spring Boot会为你处理。例如,Flyway是自动配置的,Hibernate依赖于Flyway,这样Hibernate有机会在使用数据库前对其进行初始化。 - -如果自己配置组件,你可以使用`EntityManagerFactoryDependsOnPostProcessor`子类设置必要的依赖,例如,如果你正使用Hibernate搜索,并将Elasticsearch作为它的索引管理器,这样任何`EntityManagerFactory` beans必须设置为依赖`elasticsearchClient` bean: -```java -/** - * {@link EntityManagerFactoryDependsOnPostProcessor} that ensures that - * {@link EntityManagerFactory} beans depend on the {@code elasticsearchClient} bean. - */ -@Configuration -static class ElasticsearchJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { - - ElasticsearchJpaDependencyConfiguration() { - super("elasticsearchClient"); - } - -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.2 Configure Two DataSources.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.2 Configure Two DataSources.md" deleted file mode 100644 index e6a045b4..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.2 Configure Two DataSources.md" +++ /dev/null @@ -1,69 +0,0 @@ -### 77.2 配置两个数据源 - -如果你需要配置多个数据源,你可以应用上一节描述的技巧。但是,你必须把其中的一个`数据源`标注为`@Primary`,因为之后有各种不同的自动配置,至少需要通过类型得到一个。 - -如果你创建了你自己的`数据源`,自动配置将会后退。在下面的例子中,我们提供完全相同的特性,而不是自动配置提供的主要的数据源: -```java -@Bean -@Primary -@ConfigurationProperties("app.datasource.foo") -public DataSourceProperties fooDataSourceProperties() { - return new DataSourceProperties(); -} - -@Bean -@Primary -@ConfigurationProperties("app.datasource.foo") -public DataSource fooDataSource() { - return fooDataSourceProperties().initializeDataSourceBuilder().build(); -} - -@Bean -@ConfigurationProperties("app.datasource.bar") -public BasicDataSource barDataSource() { - return (BasicDataSource) DataSourceBuilder.create() - .type(BasicDataSource.class).build(); -} -``` - -**提示** `fooDataSourceProperties`必须被标记为`@Primary`。这样,数据库初始化器特性会使用你的拷贝(你应当使用它)。 - -两个数据源也都绑定到了高级的自定义。例如你应当如下配置它们: -```properties -app.datasource.foo.type=com.zaxxer.hikari.HikariDataSource -app.datasource.foo.maximum-pool-size=30 - -app.datasource.bar.url=jdbc:mysql://localhost/test -app.datasource.bar.username=dbuser -app.datasource.bar.password=dbpass -app.datasource.bar.max-total=30 -``` -当然,你也可以应用相同的观念到第二个`数据源`: -```java -@Bean -@Primary -@ConfigurationProperties("app.datasource.foo") -public DataSourceProperties fooDataSourceProperties() { - return new DataSourceProperties(); -} - -@Bean -@Primary -@ConfigurationProperties("app.datasource.foo") -public DataSource fooDataSource() { - return fooDataSourceProperties().initializeDataSourceBuilder().build(); -} - -@Bean -@ConfigurationProperties("app.datasource.bar") -public DataSourceProperties barDataSourceProperties() { - return new DataSourceProperties(); -} - -@Bean -@ConfigurationProperties("app.datasource.bar") -public DataSource barDataSource() { - return barDataSourceProperties().initializeDataSourceBuilder().build(); -} -``` -这个最后的例子用相同的逻辑,在自定义的命名空间配置了两个数据源,而没有使用Spring Boot的自动配置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.3 Use Spring Data repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.3 Use Spring Data repositories.md" deleted file mode 100644 index a1b6dd7c..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.3 Use Spring Data repositories.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 77.3 使用Spring Data仓库 - -Spring Data可以为你的`@Repository`接口创建各种风格的实现。Spring Boot会为你处理所有事情,只要那些`@Repositories`接口跟你的`@EnableAutoConfiguration`类处于相同的包(或子包)。 - -对于很多应用来说,你需要做的就是将正确的Spring Data依赖添加到classpath下(JPA对应`spring-boot-starter-data-jpa`,Mongodb对应`spring-boot-starter-data-mongodb`),创建一些repository接口来处理`@Entity`对象,相应示例可参考[JPA sample](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples/spring-boot-sample-data-jpa)或[Mongodb sample](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples/spring-boot-sample-data-mongodb)。 - -Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测你的`@Repository`定义的位置。想要获取更多控制,可以使用`@EnableJpaRepositories`注解(来自Spring Data JPA)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.4 Separate @Entity definitions from Spring configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.4 Separate @Entity definitions from Spring configuration.md" deleted file mode 100644 index bbae22ea..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.4 Separate @Entity definitions from Spring configuration.md" +++ /dev/null @@ -1,13 +0,0 @@ -### 77.4 从Spring配置分离`@Entity`定义 - -Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测`@Entity`定义的位置,想要获取更多控制可以使用`@EntityScan`注解,比如: -```java -@Configuration -@EnableAutoConfiguration -@EntityScan(basePackageClasses=City.class) -public class Application { - - //... - -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.5 Configure JPA properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.5 Configure JPA properties.md" deleted file mode 100644 index cc5b306d..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.5 Configure JPA properties.md" +++ /dev/null @@ -1,14 +0,0 @@ -### 77.5 配置JPA属性 - -Spring Data JPA已经提供了一些独立的配置选项(比如,针对SQL日志),并且Spring Boot会暴露它们,针对hibernate的外部配置属性也更多些。它们中的一些会通过上下文,被自动探测到,所以你不需要设置它们。 - -`spring.jpa.hibernate.ddl-auto`比较特殊,因为它会根据你是(`create-drop`)否(`none`)正在使用一个内嵌的数据库,有不同的默认值。使用的方言也会基于目前的`数据源`被自动地探测到。但是如果你想要在启动时清楚明白,避开这种选择,你可以自己设置`spring.jpa.database`。 - -**提示** 🈯️定一个`数据库`是配置Hibernate方言的一种很好的方式。多个数据库有多种方言,这可能不符合你的需求。在那种情况下,你既可以把`spring.jpa.database`设置为`default`,来让Hibernate搞定一切,也可以使用`spring.jpa.database-platform`属性来设置方言。 - -最常见的选项如下: -```properties -spring.jpa.hibernate.naming.physical-strategy=com.example.MyPhysicalNamingStrategy -spring.jpa.show-sql=true -``` -此外,当本地的`EntityManagerFactory`被创建时,`spring.jpa.properties.*`里的所有属性会作为正常的JPA属性(前缀除去)被传递。 \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.6 Configure Hibernate Naming Strategy.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.6 Configure Hibernate Naming Strategy.md" deleted file mode 100644 index 226f0dd8..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.6 Configure Hibernate Naming Strategy.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 77.6 配置Hibernate命名策略 - -Hibernate 5定义了一个`Physical`和`Implicit`命名策略。Spring Boot默认配置`SpringPhysicalNamingStrategy`,该实现提供跟Hibernate 4相同的表结构:all dots are replaced by underscores and camel cases are replaced by underscores as well. By default, all table names are generated in lower case but it is possible to override that flag if your schema requires it. -Concretely, a TelephoneNumber entity will be mapped to the telephone_number table. -如果你情愿使用Hibernate 5默认的,可以设置以下属性: -```properties -spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl -``` -具体详情可参考[HibernateJpaAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java)和[JpaBaseConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java)。 \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.7 Use a custom EntityManagerFactory.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.7 Use a custom EntityManagerFactory.md" deleted file mode 100644 index 63454797..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.7 Use a custom EntityManagerFactory.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 77.7 使用自定义EntityManagerFactory - -为了完全控制`EntityManagerFactory`的配置,你需要添加一个名为`entityManagerFactory`的`@Bean`,Spring Boot自动配置会根据是否存在该类型的bean来关闭它的实体管理器(entity manager)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.8 Use Two EntityManagers.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.8 Use Two EntityManagers.md" deleted file mode 100644 index 600d52f5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.8 Use Two EntityManagers.md" +++ /dev/null @@ -1,46 +0,0 @@ -### 77.8 使用两个EntityManagers - -即使默认的`EntityManagerFactory`工作的很好,你也需要定义一个新的`EntityManagerFactory`,因为一旦出现第二个该类型的bean,默认的将会被关闭。为了轻松的实现该操作,你可以使用Spring Boot提供的`EntityManagerBuilder`,或者如果你喜欢的话可以直接使用来自Spring ORM的`LocalContainerEntityManagerFactoryBean`。 - -示例: -```java -// add two data sources configured as above - -@Bean -public LocalContainerEntityManagerFactoryBean customerEntityManagerFactory( - EntityManagerFactoryBuilder builder) { - return builder - .dataSource(customerDataSource()) - .packages(Customer.class) - .persistenceUnit("customers") - .build(); -} - -@Bean -public LocalContainerEntityManagerFactoryBean orderEntityManagerFactory( - EntityManagerFactoryBuilder builder) { - return builder - .dataSource(orderDataSource()) - .packages(Order.class) - .persistenceUnit("orders") - .build(); -} -``` -上面的配置靠自己基本可以运行,想要完成作品你还需要为两个`EntityManagers`配置`TransactionManagers`。其中的一个会被Spring Boot默认的`JpaTransactionManager`获取,如果你将它标记为`@Primary`。另一个需要显式注入到一个新实例。或你可以使用一个JTA事物管理器生成它两个。 - -如果使用Spring Data,你需要相应地需要配置`@EnableJpaRepositories`: -```java -@Configuration -@EnableJpaRepositories(basePackageClasses = Customer.class, - entityManagerFactoryRef = "customerEntityManagerFactory") -public class CustomerConfiguration { - ... -} - -@Configuration -@EnableJpaRepositories(basePackageClasses = Order.class, - entityManagerFactoryRef = "orderEntityManagerFactory") -public class OrderConfiguration { - ... -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.9 Use a traditional persistence.xml.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.9 Use a traditional persistence.xml.md" deleted file mode 100644 index 40c3bc70..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/77.9 Use a traditional persistence.xml.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 77.9 使用普通的persistence.xml - -Spring不要求使用XML配置JPA提供者(provider),并且Spring Boot假定你想要充分利用该特性。如果你倾向于使用`persistence.xml`,那你需要定义你自己的id为`entityManagerFactory`的`LocalEntityManagerFactoryBean`类型的`@Bean`,并在那设置持久化单元的名称,默认设置可查看[JpaBaseConfiguration](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78. Database initialization.md" "b/IX. \342\200\230How-to\342\200\231 guides/78. Database initialization.md" deleted file mode 100644 index b30eb3a1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78. Database initialization.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 78. 数据库初始化 - -一个数据库可以使用不同的方式进行初始化,这取决于你的技术栈。或者你可以手动完成该任务,只要数据库是单独的过程。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78. Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/78. Logging.md" new file mode 100644 index 00000000..24f17a0f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/78. Logging.md" @@ -0,0 +1,18 @@ +### 78. 日志 + +除了通常由Spring框架的`spring-jcl`模块提供的Commons Logging API,Spring Boot没有强制的日志依赖关系。想要使用[Logback](http://logback.qos.ch/),你需要包含它及`spring-jcl`。最简单的方式是通过依赖`spring-boot-starter-logging`的starter。对于一个web应用程序,你只需添加`spring-boot-starter-web`依赖,因为它依赖于logging starter。例如,使用Maven: +```xml + + org.springframework.boot + spring-boot-starter-web + +``` + +Spring Boot有一个`LoggingSystem`抽象,用于尝试通过classpath上下文配置日志系统。如果Logback可用,则首选它。如果你唯一需要做的就是设置不同日志级别,那可以通过在`application.properties`中使用`logging.level`前缀实现,比如: +```java +logging.level.org.springframework.web=DEBUG +logging.level.org.hibernate=ERROR +``` +你也可以使用`logging.file`设置日志文件的位置(除控制台之外,默认会输出到控制台)。 + +想要对日志系统进行更细粒度的配置,你需要使用`LoggingSystem`支持的原生配置格式。默认情况下,Spring Boot从系统的默认位置加载原生配置(比如对于Logback为`classpath:logback.xml`),但你可以使用`logging.config`属性设置配置文件的位置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.1 Configure Logback for Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.1 Configure Logback for Logging.md" new file mode 100644 index 00000000..1dd7af05 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/78.1 Configure Logback for Logging.md" @@ -0,0 +1,19 @@ +### 78.1 配置Logback + +如果你将`logback.xml`放到classpath根目录下,那它将会被从这加载(或`logback-spring.xml`充分利用Boot提供的模板特性)。Spring Boot提供一个默认的基本配置,如果你只是设置日志级别,那你可以包含它,比如: +```xml + + + + + +``` +如果查看spring-boot jar中的`base.xml`,你将会看到`LoggingSystem`为你创建的很多有用的系统属性,比如: +- `${PID}`:当前进程ID。 +- `${LOG_FILE}`:是否在Boot外部配置中设置了`logging.file`。 +- `${LOG_PATH}`:是否设置了`logging.path`(表示日志文件产生的目录)。 +- `${LOG_EXCEPTION_CONVERSION_WORD}`:是否在外部配置中设置了`logging.exception-conversion-word`。 + +Spring Boot也提供使用自定义的Logback转换器在控制台上输出一些漂亮的彩色ANSI日志信息(不是日志文件),具体参考默认的`base.xml`配置。 + +如果Groovy在类路径下,你也可以使用`logback.groovy`配置Logback。如果存在,则优先考虑此设置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.1 Initialize a database using JPA.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.1 Initialize a database using JPA.md" deleted file mode 100644 index 2ab671d8..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78.1 Initialize a database using JPA.md" +++ /dev/null @@ -1,6 +0,0 @@ -### 78.1 使用JPA初始化数据库 - -JPA有个生成DDL的特性,并且可以设置为在数据库启动时运行,这可以通过两个外部属性进行控制: - -- `spring.jpa.generate-ddl`(`boolean`)控制该特性的关闭和开启,跟实现者没关系。 -- `spring.jpa.hibernate.ddl-auto`(`enum`)是一个Hibernate特性,用于更细力度的控制该行为,更多详情参考以下内容。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.1.1 Configure Logback for File-only Output.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.1.1 Configure Logback for File-only Output.md" new file mode 100644 index 00000000..2cf160e4 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/78.1.1 Configure Logback for File-only Output.md" @@ -0,0 +1,18 @@ +### 78.1.1 配置logback只输出到文件 + +如果想禁用控制台日志记录,只将输出写入文件中,你需要一个只导入`file-appender.xml`而不是`console-appender.xml`的自定义`logback-spring.xml`: +```xml + + + + + + + + + +``` +你还需要将`logging.file`添加到`application.properties`: +```properties +logging.file=myapplication.log +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.2 Configure Log4j for Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.2 Configure Log4j for Logging.md" new file mode 100644 index 00000000..6cabf767 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/78.2 Configure Log4j for Logging.md" @@ -0,0 +1,29 @@ +### 78.2 配置Log4j + +如果[Log4j 2](https://logging.apache.org/log4j/2.x)出现在类路径下,Spring Boot会将其作为日志配置。如果你正在使用starter进行依赖装配,这意味着你需要排除Logback,然后包含log4j 2。如果不使用starters,除了添加Log4j 2,你还需要提供`spring-jcl`依赖(至少)。 + +最简单的方式可能就是通过starter,尽管它需要排除一些依赖,比如,在Maven中: +```xml + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + +``` + +**注** Log4j starters会收集好依赖以满足普通日志记录的需求(比如,Tomcat中使用`java.util.logging`,但使用Log4j 2作为输出)。具体查看[Actuator Log4j 2](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-actuator-log4j2)的示例,了解如何将它用于实战。 + +**注** 通过设置`java.util.logging.manager`系统属性为`org.apache.logging.log4j.jul.LogManager`,来配置它的[JDK日志适配器](https://logging.apache.org/log4j/2.0/log4j-jul/index.html),确保使用`java.util.logging`执行的调试日志被路由到Log4j 2。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.2 Initialize a database using Hibernate.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.2 Initialize a database using Hibernate.md" deleted file mode 100644 index efea6975..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78.2 Initialize a database using Hibernate.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 78.2 使用Hibernate初始化数据库 - -你可以显式设置`spring.jpa.hibernate.ddl-auto`,标准的Hibernate属性值有`none`,`validate`,`update`,`create`,`create-drop`。Spring Boot根据你的数据库是否为内嵌数据库来选择相应的默认值,如果是内嵌型的则默认值为`create-drop`,否则为`none`。通过查看`Connection`类型可以检查是否为内嵌型数据库,hsqldb,h2和derby是内嵌的,其他都不是。当从内存数据库迁移到一个真正的数据库时,你需要当心,在新的平台中不能对数据库表和数据是否存在进行臆断,你也需要显式设置`ddl-auto`,或使用其他机制初始化数据库。 - -**注** 通过启用`org.hibernate.SQL`记录器,你可以输出模式创建。如果你启用了[debug模式](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#boot-features-logging-console-output),这些会自动完成。 - -此外,如果Hibernate从零开始创建模式(`ddl-auto`属性被设置为`create`或者`create-drop`),启动时处于classpath根目录下的`import.sql`文件会被执行。这在demos或测试时很有用,但在生产环境中你可能不期望这样。这是Hibernate的特性,和Spring没有一点关系。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.2.1 Use YAML or JSON to Configure Log4j 2.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.2.1 Use YAML or JSON to Configure Log4j 2.md" new file mode 100644 index 00000000..90157380 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/78.2.1 Use YAML or JSON to Configure Log4j 2.md" @@ -0,0 +1,8 @@ +### 78.2.1 使用YAML或JSON配置Log4j2 + +除了它的默认XML配置格式,Log4j 2也支持YAML和JSON配置文件。想使用其他配置文件格式配置Log4j 2,你需要添加合适的依赖到classpath,并以匹配所选格式的方式命名配置文件: + +|格式|依赖|文件名| +|:----|:----|:---| +|YAML|`com.fasterxml.jackson.core:jackson-databind` `com.fasterxml.jackson.dataformat:jackson-dataformat-yaml`|`log4j2.yaml` `log4j2.yml`| +|JSON|`com.fasterxml.jackson.core:jackson-databind`|`log4j2.json` `log4j2.jsn`| diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.3 Initialize a database using Spring JDBC.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.3 Initialize a database using Spring JDBC.md" deleted file mode 100644 index 323cf1a0..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78.3 Initialize a database using Spring JDBC.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 78.3 使用Spring JDBC初始化数据库 - -Spring JDBC有一个初始化`DataSource`特性,Spring Boot默认启用该特性,并从标准的位置`schema.sql`和`data.sql`(位于classpath根目录)加载SQL。此外,Spring Boot将加载`schema-${platform}.sql`和`data-${platform}.sql`文件(如果存在),在这里`platform`是`spring.datasource.platform`的值,比如,你可以将它设置为数据库的供应商名称(`hsqldb`, `h2`, `oracle`, `mysql`, `postgresql`等)。Spring Boot默认启用Spring JDBC初始化快速失败特性,所以如果脚本导致异常产生,那应用程序将启动失败。脚本的位置可以通过设置`spring.datasource.schema`和`spring.datasource.data`来改变,如果设置`spring.datasource.initialize=false`则哪个位置都不会被处理。 - -你可以设置`spring.datasource.continue-on-error=true`禁用快速失败特性。一旦应用程序成熟并被部署了很多次,那该设置就很有用,因为脚本可以充当"可怜人的迁移"-例如,插入失败时意味着数据已经存在,也就没必要阻止应用继续运行。 - -如果你想要在一个JPA应用中使用`schema.sql`,那如果Hibernate试图创建相同的表,`ddl-auto=create-drop`将导致错误产生。为了避免那些错误,可以将`ddl-auto`设置为“”(推荐)或`none`。不管是否使用`ddl-auto=create-drop`,你总可以使用`data.sql`初始化新数据。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.4 Initialize a Spring Batch database.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.4 Initialize a Spring Batch database.md" deleted file mode 100644 index 15cbb25e..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78.4 Initialize a Spring Batch database.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 78.4 初始化Spring Batch数据库 - -如果你正在使用Spring Batch,那么它会为大多数的流行数据库平台预装SQL初始化脚本。Spring Boot会检测你的数据库类型,并默认执行那些脚本,在这种情况下将关闭快速失败特性(错误被记录但不会阻止应用启动)。这是因为那些脚本是可信任的,通常不会包含bugs,所以错误会被忽略掉,并且对错误的忽略可以让脚本具有幂等性。你可以使用`spring.batch.initializer.enabled=false`显式关闭初始化功能。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.5 Use a higher level database migration tool.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.5 Use a higher level database migration tool.md" deleted file mode 100644 index 7ffa4a79..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78.5 Use a higher level database migration tool.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 78.5 使用高级数据迁移工具 - -Spring Boot支持两种高级数据迁移工具[Flyway](http://flywaydb.org/)(基于SQL)和[Liquibase](http://www.liquibase.org/)(XML)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.5.1 Execute Flyway database migrations on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.5.1 Execute Flyway database migrations on startup.md" deleted file mode 100644 index cbfd39df..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78.5.1 Execute Flyway database migrations on startup.md" +++ /dev/null @@ -1,19 +0,0 @@ -### 78.5.1 启动时执行Flyway数据库迁移 - -想要在启动时自动运行Flyway数据库迁移,需要将`org.flywaydb:flyway-core`添加到你的classpath下。 - -迁移是一些`V__.sql`格式的脚本(``是一个下划线分割的版本号,比如'1'或'2_1')。默认情况下,它们存放在`classpath:db/migration`文件夹中,但你可以使用`flyway.locations`改变它。你也可以添加一个特殊的`{vendor}`占位符,来使用特殊指定的脚本。假定如下: -```properties -flyway.locations=db/migration/{vendor} -``` -这项配置将会根据数据库的类型设置使用的文件夹(比如MySQL对应的是`db/migration/mysql`),而不是使用`db/migration`。支持的数据库的一览在[`DatabaseDriver`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java). - -详情可参考flyway-core中的`Flyway`类,查看一些可用的配置,比如schemas。Spring Boot在[FlywayProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java)中提供了一个小的属性集,可用于禁止迁移,或关闭位置检测。Spring Boot将调用`Flyway.migrate()`执行数据库迁移,如果想要更多控制可提供一个实现[FlywayMigrationStrategy](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationStrategy.java)的`@Bean`。 - -Flyway支持SQL和Java[回调](http://flywaydb.org/documentation/callbacks.html)。为了使用基于SQL的回调,在`classpath:db/migration`文件夹里放置回调脚本。为了使用基于Java的回调,创建一个或者更多的实现了`FlywayCallback`,或者最好是扩展了`BaseFlywayCallback`的bean。任何这样的bean会自动在`Flyway`注册。它们能够通过使用`@Order`或者实现`Ordered`来指定顺序。 - -默认情况下,Flyway将自动注入(`@Primary`)`DataSource`到你的上下文,并用它进行数据迁移。如果想使用不同的`DataSource`,你可以创建一个,并将它标记为`@FlywayDataSource`的`@Bean`-如果你这样做了,且想要两个数据源,记得创建另一个并将它标记为`@Primary`,或者你可以通过在外部配置文件中设置`flyway.[url,user,password]`来使用Flyway的原生`DataSource`。 - -这是一个[Flyway示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-flyway),你可以作为参考。 - -你也可以使用Flyway来为特定的场景提供数据。例如,你可以在`src/test/resources`放置测试指定的迁移。它们只会在你的应用为测试启动时运行。如果你想要更加的精细,你可以使用profile指定的配置来自定义`flyway.locations`。这样,某些迁移将只会在特定profile激活的时候运行。比如,在`application-dev.properties`里,你可以把`flyway.locations`设置为`classpath:/db/migration, classpath:/dev/db/migration`,在`dev/db/migration`里的迁移将只会在`dev`profile激活的时候运行。 \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.5.2 Execute Liquibase database migrations on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.5.2 Execute Liquibase database migrations on startup.md" deleted file mode 100644 index d4ba43d0..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/78.5.2 Execute Liquibase database migrations on startup.md" +++ /dev/null @@ -1,11 +0,0 @@ -### 78.5.2 启动时执行Liquibase数据库迁移 - -想要在启动时自动运行Liquibase数据库迁移,你需要将`org.liquibase:liquibase-core`添加到classpath下。 - -你可以使用`liquibase.change-log`设置master变化日志位置,默认从`db/changelog/db.changelog-master.yaml`读取。除了YAML,Liquibase还支持JSON, XML和SQL改变日志格式。查看[LiquibaseProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java)获取可用配置,比如上下文,默认schema等。 - -默认情况下Liquibase将会在你的上下文中自动装配(`@Primary`)`数据源`,并使用此数据源进行迁移。如果你想要使用一个不同的`数据源`,你可以创建一个并把它的`@Bean`作为`@LiquibaseDataSource`标记。如果你那样做了,并且你还想要创建两个数据源,记得创建另外一个,并把它标记为`@Primary`。或者你可以通过在外部属性里设置`liquibase.[url,user,password]`的办法,使用Liquibase的本地`数据源`。 - -更多的像上下文、默认的模式之类的细节,请查看[LiquibaseProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java)。 - -这里有个[Liquibase示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-liquibase)可作为参考。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79. Data Access.md" "b/IX. \342\200\230How-to\342\200\231 guides/79. Data Access.md" new file mode 100644 index 00000000..514b5378 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79. Data Access.md" @@ -0,0 +1,3 @@ +### 79. 数据访问 + +Spring Boot包含许多用于处理数据源的starter。本节回答与此相关的问题。 \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79. Messaging.md" "b/IX. \342\200\230How-to\342\200\231 guides/79. Messaging.md" deleted file mode 100644 index e4e63038..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/79. Messaging.md" +++ /dev/null @@ -1 +0,0 @@ -### 79. 消息传送 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.1 Configure a Custom DataSource.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.1 Configure a Custom DataSource.md" new file mode 100644 index 00000000..342a2249 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.1 Configure a Custom DataSource.md" @@ -0,0 +1,96 @@ +### 79.1 配置自定义的数据源 + +在你的配置中自定义那种类型的`@Bean`来配置你自己的`数据源`。需要的时候,Spring Boot将会重复使用你的`数据源`,包括数据库的初始化。如果你需要具体化一些配置,你可以轻松的将你的`数据源`跟环境绑定([24.7.1. 第三方配置](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-3rd-party-configuration))。 + +下面的例子演示了如何在bean中定义数据源: +```java +@Bean +@ConfigurationProperties(prefix="app.datasource") +public DataSource dataSource() { + return new FancyDataSource(); +} +``` + +下面的例子展示了如何通过设置属性来定义一个数据源: +```properties +app.datasource.url=jdbc:h2:mem:mydb +app.datasource.username=sa +app.datasource.pool-size=30 +``` +假设对于这个URL,你的`FancyDataSource`有一个常规的JavaBean属性。用户名和池的大小,这些设置将会在`数据源`对其它组件可用之前,被自动绑定。常规的[数据库初始化](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc)也将会发生(这样,相关的`spring.datasource.*`的子集仍旧可以在你的自定义配置中使用)。 + +如果你正在配置一个自定义的JNDI`数据源`,你可以应用相同的原则: +```java +@Bean(destroyMethod="") +@ConfigurationProperties(prefix="app.datasource") +public DataSource dataSource() throws Exception { + JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); + return dataSourceLookup.getDataSource("java:comp/env/jdbc/YourDS"); +} +``` + +Spring Boot也提供了一个工具生成器类`DataSourceBuilder`,可以被用于生成标准的数据源(如果它在类路径上)。在类路径上哪个可用,生成器就会用哪个。它也会基于JDBC URL自动探测驱动。 + +下面的示例演示如何使用`DataSourceBuilder`创建数据源: +```java +@Bean +@ConfigurationProperties("app.datasource") +public DataSource dataSource() { + return DataSourceBuilder.create().build(); +} +``` +运行一个带有那个`数据源`的应用,只需要连接信息。也可以提供指定池的设置。检查将要在运行时使用的实现,来获取更多细节。 + +下面的例子展示了如何通过设置属性来定义JDBC数据源: +```properties +app.datasource.url=jdbc:mysql://localhost/test +app.datasource.username=dbuser +app.datasource.password=dbpass +app.datasource.pool-size=30 +``` +然而,这里有一个陷阱。因为连接池的实际类型没有被暴露,对于你自定义的`数据源`,在元数据中没有键值生成。同时,在你的IDE中也没有补全的方法(数据源接口没有暴露任何属性)。如果你的类路径里存在Hikari,基本的设置将不会生效,因为Hikari没有`url`参数(但有一个`jdbcUrl`参数)。你将不得不如下重写你的配置: +```properties +app.datasource.jdbc-url=jdbc:mysql://localhost/test +app.datasource.username=dbuser +app.datasource.password=dbpass +app.datasource.maximum-pool-size=30 +``` + +你可以通过强制连接池使用和返回一个专用的实现而不是`数据源`来处理。你将无法在运行时改变实现,但是选项的列表将会明确。 + +下面的示例演示如何使用`DataSourceBuilder`创建`HikariDataSource`: +```java +@Bean +@ConfigurationProperties("app.datasource") +public HikariDataSource dataSource() { + return DataSourceBuilder.create().type(HikariDataSource.class).build(); +} +``` + +通过利用`DataSourceProperties`,你可以走得更远。如果没有URL(带有可感测的用户名和密码)被提供,它提供一个默认的内嵌的数据库。你可以从任何`DataSourceProperties`的状态,轻松地初始化一个`DataSourceBuilder`。这样,你幸好可以注入Spring Boot自动创建的数据源。可是,那将会把你的配置分离为两个命名空间:`spring.datasource`上的url,用户名,密码,类型和驱动,以及在你自定义的命名空间(`app.datasource`)上的剩余部分。为了避免这种情况,你可以在你自定义的命名空间,重新定义一个自定义的`DataSourceProperties`: +```java +@Bean +@Primary +@ConfigurationProperties("app.datasource") +public DataSourceProperties dataSourceProperties() { + return new DataSourceProperties(); +} + +@Bean +@ConfigurationProperties("app.datasource") +public HikariDataSource dataSource(DataSourceProperties properties) { + return properties.initializeDataSourceBuilder().type(HikariDataSource.class) + .build(); +} +``` +这项设置与Spring Boot默认为你做的刚好是一对,除了一个专用的连接池被选择(在代码里),同时它的设置被暴露在相同的命名空间。因为`DataSourceProperties`会为你处理`url`或者`jdbcUrl`的翻译,你可以像这样配置它: +```properties +app.datasource.url=jdbc:mysql://localhost/test +app.datasource.username=dbuser +app.datasource.password=dbpass +app.datasource.maximum-pool-size=30 +``` + +**注** 因为你自定义的配置选择使用Hikari,`app.datasource.type`将会失效。实际上,生成器将会被任何你设置在那儿的值初始化,然后被`.type()`的调用重写。 + +具体详情可参考“Spring Boot特性”章节中的[29.1. 配置数据源](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-configure-datasource)和[`DataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java)类源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.1 Disable transacted JMS session.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.1 Disable transacted JMS session.md" deleted file mode 100644 index b86052e5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/79.1 Disable transacted JMS session.md" +++ /dev/null @@ -1,16 +0,0 @@ -### 79.1 禁用事务JMS会话 - -If your JMS broker does not support transacted session, you will have to disable the support of transactions altogether. If you create your own JmsListenerContainerFactory there is nothing to do since it won’t be transacted by default. If you want to use the DefaultJmsListenerContainerFactoryConfigurer to reuse Spring Boot’s default, you can disable transacted session as follows: - -@Bean -public DefaultJmsListenerContainerFactory jmsListenerContainerFactory( - ConnectionFactory connectionFactory, - DefaultJmsListenerContainerFactoryConfigurer configurer) { - DefaultJmsListenerContainerFactory listenerFactory = - new DefaultJmsListenerContainerFactory(); - configurer.configure(listenerFactory, connectionFactory); - listenerFactory.setTransactionManager(null); - listenerFactory.setSessionTransacted(false); - return listenerFactory; -} -This overrides the default factory and this should be applied to any other factory that your application defines, if any. diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.10 Use Spring Data JPA and Mongo Repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.10 Use Spring Data JPA and Mongo Repositories.md" new file mode 100644 index 00000000..41c75cfa --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.10 Use Spring Data JPA and Mongo Repositories.md" @@ -0,0 +1,7 @@ +### 79.10 使用Spring Data JPA和Mongo仓库 + +Spring Data JPA和Spring Data Mongo都能自动为你创建`Repository`实现。如果它们同时出现在类路径下,你可能需要添加额外的配置来告诉Spring Boot你想要创建哪个仓库。最明确的方式是使用标准的Spring Data `@EnableJpaRepositories`与`@EnableMongoRepositories`,然后提供它你的`Repository`接口的位置。 + +这里也有`spring.data.*.repositories.enabled`与`spring.data.*.repositories.type`标志,可用来在外部配置中开启或关闭仓库的自动配置。这在你想关闭Mongo仓库但仍使用自动配置的`MongoTemplate`时非常有用。 + +相同的障碍和特性也存在于其他自动配置的Spring Data仓库类型(Elasticsearch、Solr等),只需要改变对应注解的名称和标志。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.11 Expose Spring Data Repositories as REST Endpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.11 Expose Spring Data Repositories as REST Endpoint.md" new file mode 100644 index 00000000..820bcc2a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.11 Expose Spring Data Repositories as REST Endpoint.md" @@ -0,0 +1,5 @@ +### 79.11 将Spring Data仓库暴露为REST端点 + +Spring Data REST能够将`Repository`的实现暴露为REST端点,只要该应用启用Spring MVC。Spring Boot暴露一系列来自`spring.data.rest`命名空间的有用属性来定制化[`RepositoryRestConfiguration`](https://docs.spring.io/spring-data/rest/docs/current/api/org/springframework/data/rest/core/config/RepositoryRestConfiguration.html),你可以使用[`RepositoryRestConfigurer`](https://docs.spring.io/spring-data/rest/docs/current/api/org/springframework/data/rest/webmvc/config/RepositoryRestConfigurer.html)提供其他定制。 + +**注** 如果你不在你自定义的`RepositoryRestConfigurer`上指定顺序,它将会在Spring Boot内部使用的那个之后运行。如果你需要指定顺序,确保它比0高。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.12 Configure a Component that is Used by JPA.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.12 Configure a Component that is Used by JPA.md" new file mode 100644 index 00000000..f09004c8 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.12 Configure a Component that is Used by JPA.md" @@ -0,0 +1,20 @@ +### 79.12 配置JPA使用的组件 + +如果想配置一个JPA使用的组件,你需要确保该组件在JPA之前初始化。组件如果是Spring Boot自动配置的,Spring Boot会为你处理。例如,Flyway是自动配置的,Hibernate依赖于Flyway,这样Hibernate有机会在使用数据库前对其进行初始化。 + +如果自己配置组件,你可以使用`EntityManagerFactoryDependsOnPostProcessor`子类设置必要的依赖,例如,如果你正使用Hibernate搜索,并将Elasticsearch作为它的索引管理器,这样任何`EntityManagerFactory` beans必须设置为依赖`elasticsearchClient` bean: +```java +/** + * {@link EntityManagerFactoryDependsOnPostProcessor} that ensures that + * {@link EntityManagerFactory} beans depend on the {@code elasticsearchClient} bean. + */ +@Configuration +static class ElasticsearchJpaDependencyConfiguration + extends EntityManagerFactoryDependsOnPostProcessor { + + ElasticsearchJpaDependencyConfiguration() { + super("elasticsearchClient"); + } + +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.13 Configure jOOQ with Two DataSources.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.13 Configure jOOQ with Two DataSources.md" new file mode 100644 index 00000000..682b0dc7 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.13 Configure jOOQ with Two DataSources.md" @@ -0,0 +1,5 @@ +### 79.13 使用两个数据源配置jOOQ + +如果需要对多个数据源使用jOOQ,应该为每个数据源创建自己的`DSLContext`。更多细节请参考[JooqAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java)。 + +**注** 特别是,可以重用`JooqExceptionTranslator`和`SpringTransactionProvider`来提供与单个`数据源`的自动配置类似的功能。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.2 Configure Two DataSources.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.2 Configure Two DataSources.md" new file mode 100644 index 00000000..39616377 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.2 Configure Two DataSources.md" @@ -0,0 +1,69 @@ +### 79.2 配置两个数据源 + +如果你需要配置多个数据源,你可以应用上一节描述的技巧。但是,你必须把其中的一个`数据源`标注为`@Primary`,因为之后有各种不同的自动配置,至少需要通过类型得到一个。 + +如果你创建了你自己的`数据源`,自动配置将会后退。在下面的例子中,我们提供完全相同的特性,而不是自动配置提供的主要的数据源: +```java +@Bean +@Primary +@ConfigurationProperties("app.datasource.first") +public DataSourceProperties firstDataSourceProperties() { + return new DataSourceProperties(); +} + +@Bean +@Primary +@ConfigurationProperties("app.datasource.first") +public DataSource firstDataSource() { + return firstDataSourceProperties().initializeDataSourceBuilder().build(); +} + +@Bean +@ConfigurationProperties("app.datasource.second") +public BasicDataSource secondDataSource() { + return DataSourceBuilder.create().type(BasicDataSource.class).build(); +} +``` + +**提示** `firstDataSourceProperties`必须被标记为`@Primary`。这样,数据库初始化器特性会使用你的拷贝(如果你使用初始化器)。 + +两个数据源也都绑定到了高级的自定义。例如你应当如下配置它们: +```properties +app.datasource.first.type=com.zaxxer.hikari.HikariDataSource +app.datasource.first.maximum-pool-size=30 + +app.datasource.second.url=jdbc:mysql://localhost/test +app.datasource.second.username=dbuser +app.datasource.second.password=dbpass +app.datasource.second.max-total=30 +``` + +你也可以应用相同的观念到第二个`数据源`: +```java +@Bean +@Primary +@ConfigurationProperties("app.datasource.first") +public DataSourceProperties firstDataSourceProperties() { + return new DataSourceProperties(); +} + +@Bean +@Primary +@ConfigurationProperties("app.datasource.first") +public DataSource firstDataSource() { + return firstDataSourceProperties().initializeDataSourceBuilder().build(); +} + +@Bean +@ConfigurationProperties("app.datasource.second") +public DataSourceProperties secondDataSourceProperties() { + return new DataSourceProperties(); +} + +@Bean +@ConfigurationProperties("app.datasource.second") +public DataSource secondDataSource() { + return secondDataSourceProperties().initializeDataSourceBuilder().build(); +} +``` +这个最后的例子用相同的逻辑,在自定义的命名空间配置了两个数据源,而没有使用Spring Boot的自动配置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.3 Use Spring Data Repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.3 Use Spring Data Repositories.md" new file mode 100644 index 00000000..e121e6c6 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.3 Use Spring Data Repositories.md" @@ -0,0 +1,9 @@ +### 79.3 使用Spring Data仓库 + +Spring Data可以为你的`@Repository`接口创建各种风格的实现。Spring Boot会为你处理所有事情,只要那些`@Repositories`接口跟你的`@EnableAutoConfiguration`类处于相同的包(或子包)。 + +对于很多应用来说,你需要做的就是将正确的Spring Data依赖添加到classpath下(JPA对应`spring-boot-starter-data-jpa`,Mongodb对应`spring-boot-starter-data-mongodb`),创建一些repository接口来处理`@Entity`对象。相应示例可参考[JPA样本](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-data-jpa)与[Mongodb样本](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-data-mongodb)。 + +Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测你的`@Repository`定义的位置。想要获取更多控制,可以使用`@EnableJpaRepositories`注解(来自Spring Data JPA)。 + +有关Spring数据的更多信息,请参见[Spring Data项目页面](https://projects.spring.io/spring-data/)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.4 Separate @Entity Definitions from Spring Configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.4 Separate @Entity Definitions from Spring Configuration.md" new file mode 100644 index 00000000..0ad6d0aa --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.4 Separate @Entity Definitions from Spring Configuration.md" @@ -0,0 +1,13 @@ +### 79.4 从Spring配置分离`@Entity`定义 + +Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测`@Entity`定义的位置,想要获取更多控制可以使用`@EntityScan`注解,比如: +```java +@Configuration +@EnableAutoConfiguration +@EntityScan(basePackageClasses=City.class) +public class Application { + + //... + +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.4.1 Configuring Spring Loaded for use with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.4.1 Configuring Spring Loaded for use with Maven.md" deleted file mode 100644 index 5628b90d..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/79.4.1 Configuring Spring Loaded for use with Maven.md" +++ /dev/null @@ -1,17 +0,0 @@ -### 79.4.1 使用Maven配置Spring Loaded - -为了在Maven命令行下使用Spring Loaded,你只需将它作为依赖添加到Spring Boot插件声明中即可,比如: -```xml - - org.springframework.boot - spring-boot-maven-plugin - - - org.springframework - springloaded - 1.2.0.RELEASE - - - -``` -正常情况下,这在Eclipse和IntelliJ IDEA中工作的相当漂亮,只要它们有相应的,和Maven默认一致的构建配置(Eclipse m2e对此支持的更好,开箱即用)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.4.2 Configuring Spring Loaded for use with Gradle and IntelliJ.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.4.2 Configuring Spring Loaded for use with Gradle and IntelliJ.md" deleted file mode 100644 index 4dfa5964..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/79.4.2 Configuring Spring Loaded for use with Gradle and IntelliJ.md" +++ /dev/null @@ -1,28 +0,0 @@ -### 79.4.2 使用Gradle和IntelliJ IDEA配置Spring Loaded - -如果想将Spring Loaded和Gradle,IntelliJ IDEA结合起来,那你需要付出代价。默认情况下,IntelliJ IDEA将类编译到一个跟Gradle不同的位置,这会导致Spring Loaded监控失败。 - -为了正确配置IntelliJ IDEA,你可以使用`idea` Gradle插件: -```gradle -buildscript { - repositories { jcenter() } - dependencies { - classpath "org.springframework.boot:spring-boot-gradle-plugin:2.0.0.M5" - classpath 'org.springframework:springloaded:1.2.0.RELEASE' - } -} - -apply plugin: 'idea' - -idea { - module { - inheritOutputDirs = false - outputDir = file("$buildDir/classes/main/") - } -} - -// ... -``` -**注** IntelliJ IDEA必须配置跟命令行Gradle任务相同的Java版本,并且`springloaded`必须作为一个`buildscript`依赖被包含进去。 - -此外,你也可以启用Intellij IDEA内部的`Make Project Automatically`,这样不管什么时候只要文件被保存都会自动编译。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.5 Configure JPA Properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.5 Configure JPA Properties.md" new file mode 100644 index 00000000..321bb7fc --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.5 Configure JPA Properties.md" @@ -0,0 +1,16 @@ +### 79.5 配置JPA属性 + +Spring Data JPA已经提供了一些独立的配置选项(比如,针对SQL日志),并且Spring Boot会暴露它们,针对Hibernate的外部配置属性也更多些。它们中的一些会通过上下文,被自动探测到,所以你不需要设置它们。 + +`spring.jpa.hibernate.ddl-auto`比较特殊。因为根据运行条件的不同,它会有不同的默认值。如果使用嵌入式数据库,而没有模式管理器(如Liquibase或Flyway)处理`数据源`,则默认为`create-drop`。在所有其他情况下,它默认为`none`。使用的方言也会基于目前的`数据源`被自动地探测到。但是如果你想要在启动时清楚明白,避开这种选择,你可以自己设置`spring.jpa.database`。 + +**注** 指定一个`数据库`是配置Hibernate方言的一种很好的方式。多个数据库有多种方言,这可能不符合你的需求。在那种情况下,你既可以把`spring.jpa.database`设置为`default`,来让Hibernate搞定一切,也可以使用`spring.jpa.database-platform`属性来设置方言。 + +最常见的选项如下: +```properties +spring.jpa.hibernate.naming.physical-strategy=com.example.MyPhysicalNamingStrategy +spring.jpa.show-sql=true +``` +此外,当本地的`EntityManagerFactory`被创建时,`spring.jpa.properties.*`里的所有属性会作为正常的JPA属性(前缀除去)被传递。 + +**注** 如果需要对Hibernate属性应用高级定制,可以考虑注册一个`HibernatePropertiesCustomizer` bean。它将在创建`EntityManagerFactory`之前被调用。这优先于自动配置所应用的任何内容。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.6 Configure Hibernate Naming Strategy.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.6 Configure Hibernate Naming Strategy.md" new file mode 100644 index 00000000..87df1652 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.6 Configure Hibernate Naming Strategy.md" @@ -0,0 +1,22 @@ +### 79.6 配置Hibernate命名策略 + +Hibernate使用[两种不同的命名策略](https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#naming)将对象模型的名称映射到相应的数据库名称。可以通过设置`spring.jpa.hibernate.naming.physical-strategy`和`spring.jpa.hibernate.naming.implicit-strategy`属性来配置物理和隐式策略实现的完全限定类名。或者,如果应用程序上下文中有`ImplicitNamingStrategy`或`PhysicalNamingStrategy` bean可用,Hibernate将自动配置为使用它们。 + +默认情况下,Spring Boot使用`SpringPhysicalNamingStrategy`配置物理命名策略。这个实现提供了与Hibernate 4相同的表结构:所有的点都用下划线替换,驼峰式大小写也用下划线替换。默认情况下,所有表名都是用小写字母生成的,但是如果您的模式需要,可以覆盖该标志。 + +例如,`TelephoneNumber`实体映射到`telephone_number`表。 + +如果你更喜欢使用Hibernate 5的默认设置,设置如下属性: +```properties +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl +``` + +或者,你可以配置以下bean: +```java +@Bean +public PhysicalNamingStrategy physicalNamingStrategy() { + return new PhysicalNamingStrategyStandardImpl(); +} +``` + +具体详情可参考[HibernateJpaAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java)和[JpaBaseConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.7 Use a Custom EntityManagerFactory.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.7 Use a Custom EntityManagerFactory.md" new file mode 100644 index 00000000..6e872c9c --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.7 Use a Custom EntityManagerFactory.md" @@ -0,0 +1,3 @@ +### 79.7 使用自定义EntityManagerFactory + +为了完全控制`EntityManagerFactory`的配置,你需要添加一个名为`entityManagerFactory`的`@Bean`。Spring Boot自动配置会根据是否存在该类型的bean来关闭它的实体管理器(entity manager)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.8 Use Two EntityManagers.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.8 Use Two EntityManagers.md" new file mode 100644 index 00000000..9690b8df --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.8 Use Two EntityManagers.md" @@ -0,0 +1,46 @@ +### 79.8 使用两个EntityManagers + +即使默认的`EntityManagerFactory`工作的很好,你也需要定义一个新的`EntityManagerFactory`,因为一旦出现第二个该类型的bean,默认的将会被关闭。为了轻松的实现该操作,你可以使用Spring Boot提供的`EntityManagerBuilder`,或者如果你喜欢的话可以直接使用来自Spring ORM的`LocalContainerEntityManagerFactoryBean`。 + +示例: +```java +// add two data sources configured as above + +@Bean +public LocalContainerEntityManagerFactoryBean customerEntityManagerFactory( + EntityManagerFactoryBuilder builder) { + return builder + .dataSource(customerDataSource()) + .packages(Customer.class) + .persistenceUnit("customers") + .build(); +} + +@Bean +public LocalContainerEntityManagerFactoryBean orderEntityManagerFactory( + EntityManagerFactoryBuilder builder) { + return builder + .dataSource(orderDataSource()) + .packages(Order.class) + .persistenceUnit("orders") + .build(); +} +``` +上面的配置靠自己基本可以运行,想要完成作品你还需要为两个`EntityManagers`配置`TransactionManagers`。其中的一个会被Spring Boot默认的`JpaTransactionManager`获取,如果你将它标记为`@Primary`。另一个需要显式注入到一个新实例。或你可以使用一个JTA事物管理器生成它两个。 + +如果使用Spring Data,你需要相应地需要配置`@EnableJpaRepositories`: +```java +@Configuration +@EnableJpaRepositories(basePackageClasses = Customer.class, + entityManagerFactoryRef = "customerEntityManagerFactory") +public class CustomerConfiguration { + ... +} + +@Configuration +@EnableJpaRepositories(basePackageClasses = Order.class, + entityManagerFactoryRef = "orderEntityManagerFactory") +public class OrderConfiguration { + ... +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.9 Use a Traditional persistence.xml File.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.9 Use a Traditional persistence.xml File.md" new file mode 100644 index 00000000..73ff36ae --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.9 Use a Traditional persistence.xml File.md" @@ -0,0 +1,3 @@ +### 79.9 使用传统的persistence.xml文件 + +Spring不要求使用XML配置JPA提供者(provider),并且Spring Boot假定你想要充分利用该特性。如果你倾向于使用`persistence.xml`,那你需要定义你自己的ID为`entityManagerFactory`的`LocalEntityManagerFactoryBean`类型的`@Bean`,并在那设置持久化单元的名称,默认设置可查看[JpaBaseConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80. Batch applications.md" "b/IX. \342\200\230How-to\342\200\231 guides/80. Batch applications.md" deleted file mode 100644 index 533743dc..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/80. Batch applications.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 80. 批处理应用 - -默认的,批处理应用需要一个`数据源`来存储job细节。如果你想要脱离那个,你将会需要实现`BatchConfigurer`,查看[`@EnableBatchProcessing`的Javadoc](https://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html) 获取更多细节。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80. Database Initialization.md" "b/IX. \342\200\230How-to\342\200\231 guides/80. Database Initialization.md" new file mode 100644 index 00000000..eaf5bf38 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80. Database Initialization.md" @@ -0,0 +1,3 @@ +### 80. 数据库初始化 + +一个数据库可以使用不同的方式进行初始化,这取决于你的技术栈。当然,你可以手动完成该任务,只要数据库是单独的过程。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.1 Execute Spring Batch jobs on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.1 Execute Spring Batch jobs on startup.md" deleted file mode 100644 index d5574285..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/80.1 Execute Spring Batch jobs on startup.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 80.1 在启动时执行Spring Batch作业 - -你可以在上下文的某个地方添加`@EnableBatchProcessing`来启用Spring Batch的自动配置功能。 - -默认情况下,在启动时它会执行应用的所有作业(Jobs),具体查看[JobLauncherCommandLineRunner](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java)。你可以通过指定`spring.batch.job.names`(多个作业名以逗号分割)来缩小到一个特定的作业或多个作业。 - -如果应用上下文包含一个`JobRegistry`,那么处于`spring.batch.job.names`中的作业将会从registry中查找,而不是从上下文中自动装配。这是复杂系统中常见的一个模式,在这些系统中多个作业被定义在子上下文和注册中心。 - -详情可参考[BatchAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java)和[@EnableBatchProcessing](https://github.com/spring-projects/spring-batch/blob/master/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.1 Initialize a Database Using JPA.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.1 Initialize a Database Using JPA.md" new file mode 100644 index 00000000..b60c14b0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.1 Initialize a Database Using JPA.md" @@ -0,0 +1,6 @@ +### 80.1 使用JPA初始化数据库 + +JPA有个生成DDL的特性,并且可以设置为在数据库启动时运行,这可以通过两个外部属性进行控制: + +- `spring.jpa.generate-ddl`(`boolean`)控制该特性的关闭和开启,跟实现者没关系。 +- `spring.jpa.hibernate.ddl-auto`(`enum`)是一个Hibernate特性,用于更细力度的控制该行为。更多详情参考以下内容。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.2 Initialize a Database Using Hibernate.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.2 Initialize a Database Using Hibernate.md" new file mode 100644 index 00000000..42c0a967 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.2 Initialize a Database Using Hibernate.md" @@ -0,0 +1,7 @@ +### 80.2 使用Hibernate初始化数据库 + +你可以显式设置`spring.jpa.hibernate.ddl-auto`。标准的Hibernate属性值有`none`、`validate`、`update`、`create`与`create-drop`。Spring Boot根据你的数据库是否为内嵌数据库来选择相应的默认值。如果是内嵌型的则默认值为`create-drop`,否则为`none`。通过查看`Connection`类型可以检查是否为内嵌型数据库。hsqldb、h2和derby是内嵌的,其他都不是。当从内存数据库迁移到一个真正的数据库时,你需要当心,在新的平台中不能对数据库表和数据是否存在进行臆断,你也需要显式设置`ddl-auto`,或使用其他机制初始化数据库。 + +**注** 通过启用`org.hibernate.SQL`记录器,你可以输出模式创建。如果你启用了[debug模式](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-logging-console-output),这些会自动完成。 + +此外,如果Hibernate从零开始创建模式(`ddl-auto`属性被设置为`create`或者`create-drop`),启动时处于classpath根目录下的`import.sql`文件会被执行。这在demos或测试时很有用,但在生产环境中你可能不期望这样。这是Hibernate的特性,和Spring没有一点关系。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.3 Initialize a Database.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.3 Initialize a Database.md" new file mode 100644 index 00000000..82301fbf --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.3 Initialize a Database.md" @@ -0,0 +1,9 @@ +### 80.3 初始化数据库 + +Spring Boot可以自动创建`数据源`的模式(DDL脚本)并初始化它(DML脚本)。它从标准的根类路径位置加载SQL(`schema.sql`与`data.sql`)。此外,Spring Boot处理`schema-${platform}.sql`和`data-${platform}.sql`文件(如果存在),其中`platform`是`spring.datasource.platform`的值。这允许你在必要时切换到特定于数据库的脚本。例如,你可以选择将其设置为数据库的供应商名称(`hsqldb`、`h2`、`oracle`、`mysql`、`postgresql`等)。 + +Spring Boot自动创建嵌入式`数据源`的模式。可以通过使用`spring.datasource.initialization-mode`属性定制此行为(也可以是`always`或`never`)。 + +默认情况下,Spring Boot支持Spring JDBC初始化器的故障快速特性。这意味着,如果脚本导致异常,应用程序将无法启动。你可以通过设置`spring.datasource.continue-on-error`来调整该行为。 + +**注** 在基于JPA的应用程序中,你可以选择让Hibernate创建模式或使用`schema.sql`。但你不能两者都做。如果使用`schema.sql`,请确保禁用`spring.jpa.hibernate.ddl-auto`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.4 Initialize a Spring Batch Database.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.4 Initialize a Spring Batch Database.md" new file mode 100644 index 00000000..6ea23dac --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.4 Initialize a Spring Batch Database.md" @@ -0,0 +1,8 @@ +### 80.4 初始化Spring Batch数据库 + +如果你使用Spring Batch,它会预先打包为大多数流行数据库平台的SQL初始化脚本。Spring Boot可以检测数据库类型,并在启动时执行这些脚本。如果使用嵌入式数据库,这是默认情况。你也可以为任何数据库类型启用它,如下所示: +```properties +spring.batch.initialize-schema=always +``` + +你还可以通过设置`spring.batch.initialize-schema=never`来显式地关闭初始化。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.5 Use a Higher-level Database Migration Tool.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.5 Use a Higher-level Database Migration Tool.md" new file mode 100644 index 00000000..2fbe185f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.5 Use a Higher-level Database Migration Tool.md" @@ -0,0 +1,3 @@ +### 80.5 使用高级数据迁移工具 + +Spring Boot支持两种高级数据迁移工具[Flyway](https://flywaydb.org/)和[Liquibase](http://www.liquibase.org/)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.5.1 Execute Flyway Database Migrations on Startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.5.1 Execute Flyway Database Migrations on Startup.md" new file mode 100644 index 00000000..71e1b6c3 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.5.1 Execute Flyway Database Migrations on Startup.md" @@ -0,0 +1,24 @@ +### 80.5.1 启动时执行Flyway数据库迁移 + +想要在启动时自动运行Flyway数据库迁移,需要将`org.flywaydb:flyway-core`添加到你的classpath下。 + +迁移是一些`V__.sql`格式的脚本(``是一个下划线分割的版本号,比如'1'或'2_1')。默认情况下,它们存放在`classpath:db/migration`文件夹中,但你可以设置`spring.flyway.locations`改变它。你也可以添加一个特殊的`{vendor}`占位符,来使用特殊指定的脚本。假定如下: +```properties +spring.flyway.locations=db/migration/{vendor} +``` +这项配置将会根据数据库的类型设置使用的文件夹(比如MySQL对应的是`db/migration/mysql`),而不是使用`db/migration`。支持的数据库的一览在[`DatabaseDriver`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java). + +详情可参考flyway-core中的`Flyway`类,查看一些可用的配置,比如schemas。Spring Boot在[FlywayProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java)中提供了一个小的属性集,可用于禁止迁移,或关闭位置检测。Spring Boot将调用`Flyway.migrate()`执行数据库迁移,如果想要更多控制可提供一个实现[FlywayMigrationStrategy](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationStrategy.java)的`@Bean`。 + +Flyway支持SQL和Java[回调](https://flywaydb.org/documentation/callbacks.html)。为了使用基于SQL的回调,在`classpath:db/migration`文件夹里放置回调脚本。为了使用基于Java的回调,创建一个或者更多的实现了`FlywayCallback`,或者最好是扩展了`BaseFlywayCallback`的bean。任何这样的bean会自动在`Flyway`注册。它们能够通过使用`@Order`或者实现`Ordered`来指定顺序。 + +默认情况下,Flyway将自动注入(`@Primary`)`DataSource`到你的上下文,并用它进行数据迁移。如果想使用不同的`DataSource`,你可以创建一个,并将它标记为`@FlywayDataSource`的`@Bean`。如果你这样做了,且想要两个数据源,记得创建另一个并将它标记为`@Primary`,或者你可以通过在外部配置文件中设置`spring.flyway.[url,user,password]`来使用Flyway的原生`数据源`。设置`spring.flyway.url`或`spring.flyway.user`足以导致Flyway使用自己的`数据源`。如果没有设置这三个属性中的任何一个,则将使用与其等效的`spring.datasource`属性的值。 + +这是一个[Flyway示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-flyway),你可以作为参考。 + +你也可以使用Flyway来为特定的场景提供数据。例如,你可以在`src/test/resources`放置测试指定的迁移。它们只会在你的应用为测试启动时运行。如果你想要更加的精细,你可以使用profile指定的配置来自定义`spring.flyway.locations`。这样,某些迁移将只会在特定profile激活的时候运行。比如,在`application-dev.properties`里,你可能指定了如下设置: +```properties +spring.flyway.locations=classpath:/db/migration,classpath:/dev/db/migration +``` + +这样配置了以后,在`dev/db/migration`里的迁移将只会在`dev` profile激活的时候运行。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.5.2 Execute Liquibase Database Migrations on Startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.5.2 Execute Liquibase Database Migrations on Startup.md" new file mode 100644 index 00000000..74121afc --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.5.2 Execute Liquibase Database Migrations on Startup.md" @@ -0,0 +1,11 @@ +### 80.5.2 启动时执行Liquibase数据库迁移 + +想要在启动时自动运行Liquibase数据库迁移,你需要将`org.liquibase:liquibase-core`添加到classpath下。 + +默认从`db/changelog/db.changelog-master.yaml`读取master变化日志。你可以设置`spring.liquibase.change-log`改变位置。除了YAML,Liquibase还支持JSON、XML和SQL改变日志格式。 + +默认情况下Liquibase将会在你的上下文中自动装配(`@Primary`)`数据源`,并使用此数据源进行迁移。如果你想要使用一个不同的`数据源`,你可以创建一个并把它的`@Bean`作为`@LiquibaseDataSource`标记。如果你那样做了,并且你还想要创建两个数据源,记得创建另外一个,并把它标记为`@Primary`。或者你可以通过在外部属性里设置`spring.liquibase.[url,user,password]`,使用Liquibase的本地`数据源`。设置`spring.flyway.url`或`spring.flyway.user`足以导致Liquibase使用自己的`数据源`。如果没有设置这三个属性中的任何一个,则将使用与其等效的`spring.datasource`属性的值。 + +更多的像上下文、默认的模式之类的细节,请查看[LiquibaseProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java)。 + +这里有个[Liquibase示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-liquibase)可作为参考。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/81. Actuator.md" "b/IX. \342\200\230How-to\342\200\231 guides/81. Actuator.md" deleted file mode 100644 index 313cdfcb..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/81. Actuator.md" +++ /dev/null @@ -1 +0,0 @@ -### 81. 执行器(Actuator) diff --git "a/IX. \342\200\230How-to\342\200\231 guides/81. Messaging.md" "b/IX. \342\200\230How-to\342\200\231 guides/81. Messaging.md" new file mode 100644 index 00000000..8bf8d108 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/81. Messaging.md" @@ -0,0 +1,3 @@ +### 81. 消息传送 + +Spring Boot提供了许多starter,包括消息传递。本节回答在Spring Boot中使用消息传递时出现的问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/81.1 Change the HTTP port or address of the actuator endpoints.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.1 Change the HTTP port or address of the actuator endpoints.md" deleted file mode 100644 index 20a6abbc..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/81.1 Change the HTTP port or address of the actuator endpoints.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 81.1 改变HTTP端口或执行器端点的地址 - -在一个单独的应用中,执行器的HTTP端口默认和主HTTP端口相同。想要让应用监听不同的端口,你可以设置外部属性`management.port`。为了监听一个完全不同的网络地址(比如,你有一个用于管理的内部网络和一个用于用户应用程序的外部网络),你可以将`management.address`设置为一个可用的IP地址,然后将服务器绑定到该地址。 - -更多详情可查看[ManagementServerProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java)源码和'Production-ready特性'章节中的[Section 49.3, “Customizing the management server port”](../V. Spring Boot Actuator/49.3 Customizing the management server port.md)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/81.1 Disable Transacted JMS Session.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.1 Disable Transacted JMS Session.md" new file mode 100644 index 00000000..142be48b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/81.1 Disable Transacted JMS Session.md" @@ -0,0 +1,17 @@ +### 81.1 禁用事务JMS会话 + +如果你的JMS代理不支持事务会话,则必须完全禁用事务支持。如果你创建自己的`JmsListenerContainerFactory`,则不需要做任何事情,因为它在默认情况下不能进行事务处理。如果你想使用`DefaultJmsListenerContainerFactoryConfigurer`来重用Spring Boot的默认值,你可以禁用事务会话。如下所示: +```java +@Bean +public DefaultJmsListenerContainerFactory jmsListenerContainerFactory( + ConnectionFactory connectionFactory, + DefaultJmsListenerContainerFactoryConfigurer configurer) { + DefaultJmsListenerContainerFactory listenerFactory = + new DefaultJmsListenerContainerFactory(); + configurer.configure(listenerFactory, connectionFactory); + listenerFactory.setTransactionManager(null); + listenerFactory.setSessionTransacted(false); + return listenerFactory; +} +``` +前面的示例覆盖了默认工厂,如果应用程序定义了其它工厂,则应该将其应用于其它工厂。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/81.2 Customize the \342\200\230whitelabel\342\200\231 error page.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.2 Customize the \342\200\230whitelabel\342\200\231 error page.md" deleted file mode 100644 index 8004ba28..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/81.2 Customize the \342\200\230whitelabel\342\200\231 error page.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 81.2 自定义WhiteLabel错误页面 - -Spring Boot安装了一个'whitelabel'错误页面,如果你遇到一个服务器错误(机器客户端消费的是JSON,其他媒体类型则会看到一个具有正确错误码的合乎情理的响应),那就能在客户端浏览器中看到该页面。你可以设置`error.whitelabel.enabled=false`来关闭该功能,但通常你想要添加自己的错误页面来取代whitelabel。确切地说,如何实现取决于你使用的模板技术。例如,你正在使用Thymeleaf,你将添加一个`error.html`模板。如果你正在使用FreeMarker,那你将添加一个`error.ftl`模板。通常,你需要的只是一个名称为`error`的`View`,或一个处理`/error`路径的`@Controller`。除非你替换了一些默认配置,否则你将在你的`ApplicationContext`中找到一个`BeanNameViewResolver`,所以一个id为`error`的`@Bean`可能是完成该操作的一个简单方式,详情可参考[ErrorMvcAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration.java)。 - -查看[Error Handling](../IV. Spring Boot features/27.1.8 Error Handling.md)章节,了解如何将处理器(handlers)注册到servlet容器中。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/81.3 Actuator and Jersey.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.3 Actuator and Jersey.md" deleted file mode 100644 index def46133..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/81.3 Actuator and Jersey.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 81.3 Actuator和Jersey - -执行器HTTP端点只有在基于Spring MVC的应用才可用,如果想使用Jersey和执行器,你需要启用Spring MVC(添加`spring-boot-starter-web`依赖)。默认情况下,Jersey和 Spring MVC分发器servlet被映射到相同路径(`/`)。你需要改变它们中的某个路径(Spring MVC可以配置`server.servlet.path`,Jersey可以配置`spring.jersey.application-path`)。例如,如果你在`application.properties`中添加`server.servlet.path=/system`,你将在`/system`访问执行器HTTP端点。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/82. Batch Applications.md" "b/IX. \342\200\230How-to\342\200\231 guides/82. Batch Applications.md" new file mode 100644 index 00000000..4f482415 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/82. Batch Applications.md" @@ -0,0 +1,7 @@ +### 82. 批处理应用 + +本节回答在Spring Boot中使用Spring Batch时出现的问题。 + +**注** 默认的,批处理应用需要一个`数据源`来存储job细节。如果你想要脱离那个,你将会需要实现`BatchConfigurer`,查看[`@EnableBatchProcessing`的Javadoc](https://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html) 获取更多细节。 + +有关Spring Batch的更多信息,请参见[Spring Batch项目页面](https://projects.spring.io/spring-batch/)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/82. Security.md" "b/IX. \342\200\230How-to\342\200\231 guides/82. Security.md" deleted file mode 100644 index adf45395..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/82. Security.md" +++ /dev/null @@ -1 +0,0 @@ -### 82. 安全 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/82.1 Execute Spring Batch Jobs on Startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/82.1 Execute Spring Batch Jobs on Startup.md" new file mode 100644 index 00000000..1a69c1a8 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/82.1 Execute Spring Batch Jobs on Startup.md" @@ -0,0 +1,9 @@ +### 82.1 在启动时执行Spring Batch作业 + +你可以在上下文的某个地方添加`@EnableBatchProcessing`来启用Spring Batch的自动配置功能。 + +默认情况下,在启动时它会执行应用的所有作业(Jobs),具体查看[JobLauncherCommandLineRunner](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunner.java)。你可以通过指定`spring.batch.job.names`(多个作业名以逗号分割)来缩小到一个特定的作业或多个作业。 + +如果应用上下文包含一个`JobRegistry`,那么处于`spring.batch.job.names`中的作业将会从registry中查找,而不是从上下文中自动装配。这是复杂系统中常见的一个模式,在这些系统中多个作业被定义在子上下文和注册中心。 + +详情可参考[BatchAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java)和[@EnableBatchProcessing](https://github.com/spring-projects/spring-batch/blob/master/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/82.1 Switch off the Spring Boot security configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/82.1 Switch off the Spring Boot security configuration.md" deleted file mode 100644 index e0aec8ef..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/82.1 Switch off the Spring Boot security configuration.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 82.1 关闭Spring Boot安全配置 - -不管你在应用的什么地方定义了一个使用`@EnableWebSecurity`注解的`@Configuration`,它都会关闭Spring Boot中的默认webapp安全设置。想要调整默认值,你可以尝试设置`security.*`属性(具体查看[SecurityProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java)和[常见应用属性](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties-security)的SECURITY章节)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/82.2 Change the AuthenticationManager and add user accounts.md" "b/IX. \342\200\230How-to\342\200\231 guides/82.2 Change the AuthenticationManager and add user accounts.md" deleted file mode 100644 index 49eef0d0..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/82.2 Change the AuthenticationManager and add user accounts.md" +++ /dev/null @@ -1,33 +0,0 @@ -### 82.2 改变AuthenticationManager并添加用户账号 - -如果你提供了一个`AuthenticationManager`类型的`@Bean`,那么默认的就不会被创建了,所以你可以获得Spring Security可用的全部特性(比如,[不同的认证选项](http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authentication))。 - -Spring Security也提供了一个方便的`AuthenticationManagerBuilder`,用于构建具有常见选项的`AuthenticationManager`。在一个webapp中,推荐将它注入到`WebSecurityConfigurerAdapter`的一个void方法中,比如: -```java -@Configuration -public class SecurityConfiguration extends WebSecurityConfigurerAdapter { - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("barry").password("password").roles("USER"); // ... etc. - } - - // ... other stuff for application security -} -``` -如果把它放到一个内部类或一个单独的类中,你将得到最好的结果(也就是不跟很多其他`@Beans`混合在一起将允许你改变实例化的顺序)。[secure web sample](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-secure)是一个有用的参考模板。 - -如果你遇到了实例化问题(比如,使用JDBC或JPA进行用户详细信息的存储),那将`AuthenticationManagerBuilder`回调提取到一个`GlobalAuthenticationConfigurerAdapter`(放到`init()`方法内以防其他地方也需要authentication manager)可能是个不错的选择,比如: -```java -@Configuration -public class AuthenticationManagerConfiguration extends - - GlobalAuthenticationConfigurerAdapter { - @Override - public void init(AuthenticationManagerBuilder auth) { - auth.inMemoryAuthentication() // ... etc. - } - -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/82.3 Enable HTTPS when running behind a proxy server.md" "b/IX. \342\200\230How-to\342\200\231 guides/82.3 Enable HTTPS when running behind a proxy server.md" deleted file mode 100644 index fa717552..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/82.3 Enable HTTPS when running behind a proxy server.md" +++ /dev/null @@ -1,12 +0,0 @@ -### 82.3 当前端使用代理服务器时启用HTTPS - -对于任何应用来说,确保所有的主端点(URL)都只在HTTPS下可用是个重要的苦差事。如果你使用Tomcat作为servlet容器,那Spring Boot如果发现一些环境设置的话,它将自动添加Tomcat自己的`RemoteIpValve`,你也可以依赖于`HttpServletRequest`来报告是否请求是安全的(即使代理服务器的downstream处理真实的SSL终端)。这个标准行为取决于某些请求头是否出现(`x-forwarded-for`和`x-forwarded-proto`),这些请求头的名称都是约定好的,所以对于大多数前端和代理都是有效的。 - -你可以向`application.properties`添加以下设置开启该功能,比如: -```yml -server.tomcat.remote_ip_header=x-forwarded-for -server.tomcat.protocol_header=x-forwarded-proto -``` -(这些属性出现一个就会开启该功能,或者你可以通过添加一个`TomcatServletWebServerFactory` bean自己添加`RemoteIpValve`)。 - -Spring Security也可以配置成针对所有或某些请求需要一个安全渠道(channel)。想要在一个Spring Boot应用中开启它,你只需将`application.properties`中的`security.require_ssl`设置为`true`即可。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83. Actuator.md" "b/IX. \342\200\230How-to\342\200\231 guides/83. Actuator.md" new file mode 100644 index 00000000..868d8f0e --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/83. Actuator.md" @@ -0,0 +1,3 @@ +### 83. 执行器(Actuator) + +Spring Boot包括Spring Boot Actuator。本节回答了在使用过程中经常出现的问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83. Hot swapping.md" "b/IX. \342\200\230How-to\342\200\231 guides/83. Hot swapping.md" deleted file mode 100644 index 80b90468..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83. Hot swapping.md" +++ /dev/null @@ -1 +0,0 @@ -### 83. 热交换 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.1 Change the HTTP Port or Address of the Actuator Endpoints.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.1 Change the HTTP Port or Address of the Actuator Endpoints.md" new file mode 100644 index 00000000..3d980591 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/83.1 Change the HTTP Port or Address of the Actuator Endpoints.md" @@ -0,0 +1,5 @@ +### 83.1 改变HTTP端口或执行器端点的地址 + +在一个单独的应用中,执行器的HTTP端口默认和主HTTP端口相同。想要让应用监听不同的端口,你可以设置外部属性`management.server.port`。为了监听一个完全不同的网络地址(比如,你有一个用于管理的内部网络和一个用于用户应用程序的外部网络),你可以将`management.server.address`设置为一个可用的IP地址,然后将服务器绑定到该地址。 + +更多详情可查看[ManagementServerProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerProperties.java)源码和'Production-ready特性'章节中的[51.2 自定义管理服务器端口](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-customizing-management-server-port)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.1 Reload static content.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.1 Reload static content.md" deleted file mode 100644 index 72b2543d..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83.1 Reload static content.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 83.1 重新加载静态内容 - -Spring Boot有很多用于热加载的选项,不过推荐使用[spring-boot-devtools](../III. Using Spring Boot/20. Developer tools.md),因为它提供了其他开发时特性,比如快速应用重启和LiveReload,还有开发时敏感的配置加载(比如,模板缓存)。Devtools通过监控类路径上的变化工作。这意味着静态资源的改变必须“生成”才能生效。默认的,当你保存你的改变时,这在Eclipse里会自动发生。在IntelliJ IDEA里,生成项目将会触发必要的构建。由于[默认的重启排除](../III. Using Spring Boot/20.2.1. Excluding resources.md),静态资源的改变将不会触发应用的重启。但是,它们会触发LiveReload。 - -此外,使用IDE开发也是一个不错的方式,特别是需要调试的时候(所有的现代IDEs都允许重新加载静态资源,通常也支持对变更的Java类进行热交换)。 - -最后,[Maven和Gradle插件](../VIII. Build tool plugins/README.md)也支持命令行下的静态文件热加载。如果你使用其他高级工具编写css/js,并使用外部的css/js编译器,那你就可以充分利用该功能。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.2 Customize the \342\200\230whitelabel\342\200\231 Error Page.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.2 Customize the \342\200\230whitelabel\342\200\231 Error Page.md" new file mode 100644 index 00000000..cf026b99 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/83.2 Customize the \342\200\230whitelabel\342\200\231 Error Page.md" @@ -0,0 +1,5 @@ +### 83.2 自定义WhiteLabel错误页面 + +Spring Boot安装了一个'whitelabel'错误页面,如果你遇到一个服务器错误(机器客户端消费的是JSON,其他媒体类型则会看到一个具有正确错误码的合乎情理的响应),那就能在客户端浏览器中看到该页面。你可以设置`error.whitelabel.enabled=false`来关闭该功能,但通常你想要添加自己的错误页面来取代whitelabel。确切地说,如何实现取决于你使用的模板技术。例如,你正在使用Thymeleaf,你将添加一个`error.html`模板。如果你正在使用FreeMarker,那你将添加一个`error.ftl`模板。通常,你需要的只是一个名称为`error`的`View`,或一个处理`/error`路径的`@Controller`。除非你替换了一些默认配置,否则你将在你的`ApplicationContext`中找到一个`BeanNameViewResolver`,所以一个名为`error`的`@Bean`可能是完成该操作的一个简单方式,详情可参考[ErrorMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java)。 + +查看[Error Handling](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-error-handling)章节,了解如何将处理器(handlers)注册到servlet容器中。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.2. Reload templates without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.2. Reload templates without restarting the container.md" deleted file mode 100644 index f69b81b4..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83.2. Reload templates without restarting the container.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 83.2. 在不重启容器的情况下重新加载模板 - -Spring Boot支持的大多数模板技术包含一个禁用缓存的配置选项,如果你正在使用`spring-boot-devtools`模块,Spring Boot在开发期间会自动为你[配置那些属性](../III. Using Spring Boot/20.1 Property defaults.md)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.2.1 Thymeleaf templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.2.1 Thymeleaf templates.md" deleted file mode 100644 index 73b3ea62..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83.2.1 Thymeleaf templates.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 83.2.1 Thymeleaf模板 - -如果你正在使用Thymeleaf,那就将`spring.thymeleaf.cache`设置为`false`,查看[ThymeleafAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java)可以获取其他Thymeleaf自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.2.2 FreeMarker templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.2.2 FreeMarker templates.md" deleted file mode 100644 index f2485eab..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83.2.2 FreeMarker templates.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 83.2.2 FreeMarker模板 - -如果你正在使用FreeMarker,那就将`spring.freemarker.cache`设置为`false`,查看[FreeMarkerAutoConfiguration ](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java)可以获取其他FreeMarker自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.2.3 Groovy templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.2.3 Groovy templates.md" deleted file mode 100644 index 3e80cbce..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83.2.3 Groovy templates.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 83.2.3 Groovy模板 - -如果你正在使用Groovy模板,那就将`spring.groovy.template.cache`设置为`false`,查看[GroovyTemplateAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java)可以获取其他Groovy自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.3 Fast application restarts.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.3 Fast application restarts.md" deleted file mode 100644 index 4721d565..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83.3 Fast application restarts.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 83.3 应用快速重启 - -`spring-boot-devtools`模块包括应用自动重启支持,虽然没有其他技术快,比如[JRebel](http://zeroturnaround.com/software/jrebel/),但比"冷启动"快。在研究其他复杂重启选项时,你最好自己先试下,更多详情可参考[Chapter 20, Developer tools](../III. Using Spring Boot/20. Developer tools.md)章节。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/83.4 Reload Java classes without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/83.4 Reload Java classes without restarting the container.md" deleted file mode 100644 index 2b978736..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/83.4 Reload Java classes without restarting the container.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 83.4 在不重启容器的情况下重新加载Java类 - -现代IDEs(Eclipse, IDEA等)都支持字节码的热交换,所以如果你做了一个没有影响类或方法签名的改变,它会利索地重新加载并没有任何影响。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84. Build.md" "b/IX. \342\200\230How-to\342\200\231 guides/84. Build.md" deleted file mode 100644 index 9eeb85a5..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84. Build.md" +++ /dev/null @@ -1 +0,0 @@ -### 84. 构建 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84. Security.md" "b/IX. \342\200\230How-to\342\200\231 guides/84. Security.md" new file mode 100644 index 00000000..f0b27527 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/84. Security.md" @@ -0,0 +1,5 @@ +### 84. 安全 + +本节讨论在使用Spring Boot时有关安全性的问题,包括在Spring Boot中使用Spring Security时产生的问题。 + +有关Spring安全性的更多信息,请参见[Spring Security项目页面](https://projects.spring.io/spring-security/)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.1 Generate build information.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.1 Generate build information.md" deleted file mode 100644 index fe516262..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.1 Generate build information.md" +++ /dev/null @@ -1,41 +0,0 @@ -### 84.1 生成构建信息 - -Maven和Gradle都支持产生包含项目版本,坐标,名称的构建信息,该插件可以通过配置添加其他属性。当这些文件出现时,Spring Boot自动配置一个`BuildProperties` bean。 - -为了让Maven生成构建信息,你需要为`build-info` goal添加一个execution: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - 2.0.0.M5 - - - - build-info - - - - - - -``` -**注** 更多详情查看[Spring Boot Maven插件文档](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin/)。 - -使用Gradle实现同样效果: -```gradle -springBoot { - buildInfo() -} -``` -可以使用DSL添加其他属性: -```gradle -springBoot { - buildInfo { - additionalProperties = [ - 'foo': 'bar' - ] - } -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.1 Switch off the Spring Boot Security Configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.1 Switch off the Spring Boot Security Configuration.md" new file mode 100644 index 00000000..063f7636 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/84.1 Switch off the Spring Boot Security Configuration.md" @@ -0,0 +1,3 @@ +### 84.1 关闭Spring Boot安全配置 + +如果你在应用里使用`WebSecurityConfigurerAdapter`定义了一个`@Configuration`,它都会关闭Spring Boot中的默认webapp安全设置。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.2 Change the AuthenticationManager and Add User Accounts.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.2 Change the AuthenticationManager and Add User Accounts.md" new file mode 100644 index 00000000..797458b5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/84.2 Change the AuthenticationManager and Add User Accounts.md" @@ -0,0 +1,5 @@ +### 84.2 改变AuthenticationManager并添加用户账号 + +如果你提供了一个`AuthenticationManager`、`AuthenticationProvider`、`UserDetailsService`类型的`@Bean`,那么默认的用于`InMemoryUserDetailsManager`的`@Bean`就不会被创建了,所以你可以获得Spring Security可用的全部特性(比如,[不同的认证选项](https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authentication))。 + +添加用户帐户的最简单方法是提供你自己的`UserDetailsService` bean。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.2 Generate git information.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.2 Generate git information.md" deleted file mode 100644 index 3399cfad..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.2 Generate git information.md" +++ /dev/null @@ -1,19 +0,0 @@ -### 84.2 生成Git信息 - -Maven和Gradle都支持生成一个`git.properties`文件,该文件包含项目构建时`git`源码的仓库状态。对于Maven用户来说,`spring-boot-starter-parent` POM包含一个预配置的插件去产生一个`git.properties`文件,只需简单的将以下声明添加到POM中: -```xml - - - - pl.project13.maven - git-commit-id-plugin - - - -``` -Gradle用户可以使用[gradle-git-properties](https://plugins.gradle.org/plugin/com.gorylenko.gradle-git-properties)插件实现相同效果: -```gralde -plugins { - id "com.gorylenko.gradle-git-properties" version "1.4.17" -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.3 Customize dependency versions.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.3 Customize dependency versions.md" deleted file mode 100644 index 0477727b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.3 Customize dependency versions.md" +++ /dev/null @@ -1,11 +0,0 @@ -### 84.3 自定义依赖版本 - -如果你使用Maven进行一个直接或间接继承`spring-boot-dependencies`(比如`spring-boot-starter-parent`)的构建,并想覆盖一个特定的第三方依赖,那你可以添加合适的``元素。浏览[spring-boot-dependencies](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-dependencies/pom.xml) POM可以获取一个全面的属性列表。例如,想要选择一个不同的`slf4j`版本,你可以添加以下内容: -```xml - - 1.7.5 - -``` -**注** 这只在你的Maven项目继承(直接或间接)自`spring-boot-dependencies`才有用。如果你使用`import`,将`spring-boot-dependencies`添加到自己的`dependencyManagement`片段,那你必须自己重新定义artifact而不是覆盖属性。 - -**注** 每个Spring Boot发布都是基于一些特定的第三方依赖集进行设计和测试的,覆盖版本可能导致兼容性问题。 \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.3 Enable HTTPS When Running behind a Proxy Server.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.3 Enable HTTPS When Running behind a Proxy Server.md" new file mode 100644 index 00000000..86281e78 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/84.3 Enable HTTPS When Running behind a Proxy Server.md" @@ -0,0 +1,22 @@ +### 84.3 当前端使用代理服务器时启用HTTPS + +对于任何应用来说,确保所有的主端点(URL)都只在HTTPS下可用是个重要的苦差事。如果你使用Tomcat作为servlet容器,那Spring Boot如果发现一些环境设置的话,它将自动添加Tomcat自己的`RemoteIpValve`,你也可以依赖于`HttpServletRequest`来报告是否请求是安全的(即使代理服务器的downstream处理真实的SSL终端)。这个标准行为取决于某些请求头是否出现(`x-forwarded-for`和`x-forwarded-proto`),这些请求头的名称都是约定好的,所以对于大多数前端和代理都是有效的。你可以向`application.properties`添加以下设置开启该功能,比如: +```properties +server.tomcat.remote-ip-header=x-forwarded-for +server.tomcat.protocol-header=x-forwarded-proto +``` +(这些属性出现一个就会开启该功能,或者你可以通过添加一个`TomcatServletWebServerFactory` bean自己添加`RemoteIpValve`)。 + +要将Spring Security配置为所有(或部分)请求都需要一个安全通道,请考虑添加你自己的`WebSecurityConfigurerAdapter`,它将添加以下`HttpSecurity`配置: +``` +@Configuration +public class SslWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // Customize the application security + http.requiresChannel().anyRequest().requiresSecure(); + } + +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.4 Create an executable JAR with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.4 Create an executable JAR with Maven.md" deleted file mode 100644 index bc36fda1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.4 Create an executable JAR with Maven.md" +++ /dev/null @@ -1,33 +0,0 @@ -### 84.4 使用Maven创建可执行JAR - -`spring-boot-maven-plugin`能够用来创建可执行的'胖'JAR。如果正在使用`spring-boot-starter-parent` POM,你可以简单地声明该插件,然后你的jar将被重新打包: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - - -``` -如果没有使用parent POM,你仍旧可以使用该插件。不过,你需要另外添加一个``片段: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - 2.0.0.M5 - - - - repackage - - - - - - -``` -查看[插件文档](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin/usage.html)获取详细的用例。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.5 Use a Spring Boot application as a dependency.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.5 Use a Spring Boot application as a dependency.md" deleted file mode 100644 index e182764c..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.5 Use a Spring Boot application as a dependency.md" +++ /dev/null @@ -1,22 +0,0 @@ -### 84.5 将Spring Boot应用作为依赖 - -跟war包一样,Spring Boot应用不是用来作为依赖的。如果你的应用包含需要跟其他项目共享的类,最好的方式是将代码放到单独的模块,然后其他项目及你的应用都可以依赖该模块。 - -如果不能按照上述推荐的方式重新组织代码,你需要配置Spring Boot的Maven和Gradle插件去产生一个单独的artifact,以适合于作为依赖。可执行存档不能用于依赖,因为[可执行jar格式](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#executable-jar-jar-file-structure)将应用class打包到`BOOT-INF/classes`,也就意味着可执行jar用于依赖时会找不到。 - -为了产生两个artifacts(一个用于依赖,一个用于可执行jar),你需要指定classifier。classifier用于可执行存档的name,默认存档用于依赖。 - -可以使用以下配置Maven中classifier的`exec`: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.6 Extract specific libraries when an executable jar runs.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.6 Extract specific libraries when an executable jar runs.md" deleted file mode 100644 index 674effd9..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.6 Extract specific libraries when an executable jar runs.md" +++ /dev/null @@ -1,23 +0,0 @@ -### 84.6 在可执行jar运行时提取特定的版本 - -在一个可执行jar中,为了运行,多数内嵌的库不需要拆包(unpacked),然而有一些库可能会遇到问题。例如,JRuby包含它自己的内嵌jar,它假定`jruby-complete.jar`本身总是能够直接作为文件访问的。 - -为了处理任何有问题的库,你可以标记那些特定的内嵌jars,让它们在可执行jar第一次运行时自动解压到一个临时文件夹中。例如,为了将JRuby标记为使用Maven插件拆包,你需要添加如下的配置: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.jruby - jruby-complete - - - - - - -``` \ No newline at end of file diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.7 Create a non-executable JAR with exclusions.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.7 Create a non-executable JAR with exclusions.md" deleted file mode 100644 index 0cc2190b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.7 Create a non-executable JAR with exclusions.md" +++ /dev/null @@ -1,33 +0,0 @@ -### 84.7 使用排除创建不可执行的JAR - -如果你构建的产物既有可执行的jar和非可执行的jar,那你常常需要为可执行的版本添加额外的配置文件,而这些文件在一个library jar中是不需要的。比如,`application.yml`配置文件可能需要从非可执行的JAR中排除。 - -`maven-jar-plugin`过去一直会暴露`forceCreation`属性。一旦`repackage`目标执行,就可以再一次创建jar。可以说,这就有些脆弱。因为它依靠plugin executions的顺序。在Maven里,可执行的jar必须是主要的artifact,并且你可以为类库加入一个分类的jar: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - - maven-jar-plugin - - - lib - package - - jar - - - lib - - application.yml - - - - - - - -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.8 Remote debug a Spring Boot application started with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.8 Remote debug a Spring Boot application started with Maven.md" deleted file mode 100644 index 358fdf2f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.8 Remote debug a Spring Boot application started with Maven.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 84.8 远程调试使用Maven启动的Spring Boot项目 - -想要为使用Maven启动的Spring Boot应用添加一个远程调试器,你可以使用[mave插件](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin/)的jvmArguments属性,详情参考[示例](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin/examples/run-debug.html)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/84.9 Build an executable archive from Ant without using spring-boot-antlib.md" "b/IX. \342\200\230How-to\342\200\231 guides/84.9 Build an executable archive from Ant without using spring-boot-antlib.md" deleted file mode 100644 index 252015f0..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/84.9 Build an executable archive from Ant without using spring-boot-antlib.md" +++ /dev/null @@ -1,42 +0,0 @@ -### 84.9 使用Ant构建可执行存档(不使用spring-boot-antlib) - -想要使用Ant进行构建,你需要抓取依赖,编译,然后像通常那样创建一个jar或war存档。为了让它可以执行,你可以使用`spring-boot-antlib`,也可以使用以下指令: - -1. 如果构建jar,你需要将应用的类和资源打包进内嵌的`BOOT-INF/classes`目录。如果构建war,你需要将应用的类打包进内嵌的`WEB-INF/classes`目录。 -2. 对于jar,添加运行时依赖到内嵌的`BOOT-INF/lib`目录。对于war,则添加到`WEB-INF/lib`目录。注意不能压缩存档中的实体。 -3. 对于jar,添加`provided`依赖到内嵌的`BOOT-INF/lib`目录。对于war,则添加到`WEB-INF/lib-provided`目录。注意不能压缩存档中的实体。 -4. 在存档的根目录添加`spring-boot-loader`类(这样`Main-Class`就可用了)。 -5. 使用恰当的启动器,比如对于jar使用`JarLauncher`作为manifest的`Main-Class`属性,指定manifest的其他属性,特别是`Start-Class`。 - -示例: -```xml - - - - - - - - - - - - - - - - - - - - - -``` -该[Ant示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples/spring-boot-sample-ant)中有一个`build.xml`文件及`manual`任务,可以使用以下命令来运行: -```shell -$ ant -lib clean manual -``` -在上述操作之后,你可以使用以下命令运行该应用: -```shell -$ java -jar target/*.jar -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85. Hot Swapping.md" "b/IX. \342\200\230How-to\342\200\231 guides/85. Hot Swapping.md" new file mode 100644 index 00000000..ea952cd8 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85. Hot Swapping.md" @@ -0,0 +1,3 @@ +### 85. 热交换 + +Spring Boot支持热交换。本节回答关于它如何工作的问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85. Traditional deployment.md" "b/IX. \342\200\230How-to\342\200\231 guides/85. Traditional deployment.md" deleted file mode 100644 index b8ebc19f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/85. Traditional deployment.md" +++ /dev/null @@ -1 +0,0 @@ -### 85. 传统部署 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.1 Create a deployable war file.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.1 Create a deployable war file.md" deleted file mode 100644 index f6b74989..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/85.1 Create a deployable war file.md" +++ /dev/null @@ -1,53 +0,0 @@ -### 85.1 创建可部署的war文件 - -产生一个可部署war包的第一步是提供一个`SpringBootServletInitializer`子类,并覆盖它的`configure`方法,这充分利用了Spring框架对Servlet 3.0的支持,并允许你在应用通过servlet容器启动时配置它。通常,你只需把应用的主类改为继承`SpringBootServletInitializer`即可: -```java -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Application.class); - } - - public static void main(String[] args) throws Exception { - SpringApplication.run(Application.class, args); - } - -} -``` -下一步是更新你的构建配置,这样你的项目将产生一个war包而不是jar包。如果你使用Maven,并使用`spring-boot-starter-parent`(为了配置Maven的war插件),所有你需要做的就是更改`pom.xml`的打包方式为`war`: -```xml -war -``` -如果你使用Gradle,你需要修改`build.gradle`来将war插件应用到项目上: -```gradle -apply plugin: 'war' -``` -该过程最后的一步是确保内嵌的servlet容器不能干扰war包将部署的servlet容器。为了达到这个目的,你需要将内嵌容器的依赖标记为`provided`。 - -如果使用Maven: -```xml - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - -``` -如果使用Gradle: -```gradle -dependencies { - // … - providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' - // … -} -``` -**注** `providedRuntime`更适合Gradle的`compileOnly`配置,因为`compileOnly`依赖不在测试类路径上,所以任何基于web的综合测试都会失败。 - -如果你使用[Spring Boot构建工具](../VIII. Build tool plugins/README.md),将内嵌容器依赖标记为`provided`将产生一个可执行war包,在`lib-provided`目录有该war包的`provided`依赖。这意味着,除了部署到servlet容器,你还可以通过使用命令行`java -jar`命令来运行应用。 - -**提示** 查看Spring Boot基于以上配置的一个[Maven示例应用](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-traditional/pom.xml)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.1 Reload Static Content.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.1 Reload Static Content.md" new file mode 100644 index 00000000..368f31a9 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85.1 Reload Static Content.md" @@ -0,0 +1,7 @@ +### 85.1 重新加载静态内容 + +Spring Boot有很多用于热加载的选项,不过推荐使用[spring-boot-devtools](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-devtools),因为它提供了其他开发时特性,比如快速应用重启和LiveReload,还有开发时敏感的配置加载(比如,模板缓存)。Devtools通过监控类路径上的变化工作。这意味着静态资源的改变必须“生成”才能生效。默认的,当你保存你的改变时,这在Eclipse里会自动发生。在IntelliJ IDEA里,生成项目命令会触发必要的构建。由于[默认的重启排除](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-devtools-restart-exclude),静态资源的改变将不会触发应用的重启。但是,它们会触发LiveReload。 + +此外,使用IDE开发也是一个不错的方式,特别是需要调试的时候(所有的现代IDEs都允许重新加载静态资源,通常也允许对变更的Java类进行热交换)。 + +最后,[Maven和Gradle插件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#build-tool-plugins)也支持命令行下的静态文件热加载。如果你使用其他高级工具编写css/js,并使用外部的css/js编译器,那你就可以充分利用该功能。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.2 Create a deployable war file for older servlet containers.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.2 Create a deployable war file for older servlet containers.md" deleted file mode 100644 index 67c1b4e6..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/85.2 Create a deployable war file for older servlet containers.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 85.2 为老的servlet容器创建可部署的war文件 - -老的Servlet容器不支持在Servlet 3.0中使用的`ServletContextInitializer`启动处理。你仍旧可以在这些容器使用Spring和Spring Boot,但你需要为应用添加一个`web.xml`,并将它配置为通过一个`DispatcherServlet`加载一个`ApplicationContext`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.2. Reload Templates without Restarting the Container.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.2. Reload Templates without Restarting the Container.md" new file mode 100644 index 00000000..6fa51d38 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85.2. Reload Templates without Restarting the Container.md" @@ -0,0 +1,3 @@ +### 85.2. 在不重启容器的情况下重新加载模板 + +Spring Boot支持的大多数模板技术包含一个禁用缓存的配置选项,如果你正在使用`spring-boot-devtools`模块,Spring Boot在开发期间会自动为你[配置那些属性](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-devtools-property-defaults)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.2.1 Thymeleaf Templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.2.1 Thymeleaf Templates.md" new file mode 100644 index 00000000..c467ee3b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85.2.1 Thymeleaf Templates.md" @@ -0,0 +1,3 @@ +### 85.2.1 Thymeleaf模板 + +如果你正在使用Thymeleaf,那就将`spring.thymeleaf.cache`设置为`false`,查看[ThymeleafAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java)可以获取其他Thymeleaf自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.2.2 FreeMarker Templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.2.2 FreeMarker Templates.md" new file mode 100644 index 00000000..ab30bd51 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85.2.2 FreeMarker Templates.md" @@ -0,0 +1,3 @@ +### 85.2.2 FreeMarker模板 + +如果你正在使用FreeMarker,那就将`spring.freemarker.cache`设置为`false`,查看[FreeMarkerAutoConfiguration ](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java)可以获取其他FreeMarker自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.2.3 Groovy Templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.2.3 Groovy Templates.md" new file mode 100644 index 00000000..ebf8b3f3 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85.2.3 Groovy Templates.md" @@ -0,0 +1,3 @@ +### 85.2.3 Groovy模板 + +如果你正在使用Groovy模板,那就将`spring.groovy.template.cache`设置为`false`,查看[GroovyTemplateAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java)可以获取其他Groovy自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.3 Convert an existing application to Spring Boot.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.3 Convert an existing application to Spring Boot.md" deleted file mode 100644 index a29c9c74..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/85.3 Convert an existing application to Spring Boot.md" +++ /dev/null @@ -1,68 +0,0 @@ -### 85.3 将现有的应用转换为Spring Boot - -对于一个非web项目,转换为Spring Boot应用很容易(抛弃创建`ApplicationContext`的代码,取而代之的是调用`SpringApplication`或`SpringApplicationBuilder`)。Spring MVC web应用通常先创建一个可部署的war应用,然后将它迁移为一个可执行的war或jar,建议阅读[Getting Started Guide on Converting a jar to a war.](http://spring.io/guides/gs/convert-jar-to-war/)。 - -通过继承`SpringBootServletInitializer`创建一个可执行war(比如,在一个名为`Application`的类中),然后添加Spring Boot的`@SpringBootApplication`注解,示例: -```java -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - // Customize the application or call application.sources(...) to add sources - // Since our example is itself a @Configuration class (via @SpringBootApplication) - // we actually don't need to override this method. - return application; - } - -} -``` -记住不管你往`sources`放什么东西,它仅是一个Spring `ApplicationContext`,正常情况下,任何生效的在这里也会起作用。有一些beans你可以先移除,然后让Spring Boot提供它的默认实现,不过有可能需要先完成一些事情。 - -静态资源可以移到classpath根目录下的`/public`(或`/static`,`/resources`,`/META-INF/resources`)。同样的方式也适合于`messages.properties`(Spring Boot在classpath根目录下自动发现这些配置)。 - -美妙的(Vanilla usage of)Spring `DispatcherServlet`和Spring Security不需要改变。如果你的应用有其他特性,比如使用其他servlets或filters,那你可能需要添加一些配置到你的`Application`上下文中,按以下操作替换`web.xml`的那些元素: - -- 在容器中安装一个`Servlet`或`ServletRegistrationBean`类型的`@Bean`,就好像`web.xml`中的``和``。 -- 同样的添加一个`Filter`或`FilterRegistrationBean`类型的`@Bean`(类似于``和``)。 -- 在XML文件中的`ApplicationContext`可以通过`@ImportResource`添加到你的`Application`中。简单的情况下,大量使用注解配置可以在几行内定义`@Bean`定义。 - -一旦war可以使用,我们就通过添加一个main方法到`Application`来让它可以执行,比如: -```java -public static void main(String[] args) { - SpringApplication.run(Application.class, args); -} -``` - -**注** 如果你想要把你的应用作为war或者可执行的应用来启动,你需要在一个方法里面共享构建器的配置。那个方法要对`SpringBootServletInitializer`回调和`main`方法都可用,就像这样: -```java -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { - return configureApplication(builder); - } - - public static void main(String[] args) { - configureApplication(new SpringApplicationBuilder()).run(args); - } - - private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) { - return builder.sources(Application.class).bannerMode(Banner.Mode.OFF); - } - -} -``` -应用可以划分为多个类别: - -- 没有web.xml的Servlet 3.0+应用 -- 有web.xml的应用 -- 有上下文层次的应用 -- 没有上下文层次的应用 - -所有这些都可以进行适当的转化,但每个可能需要稍微不同的技巧。 - -Servlet 3.0+的应用转化的相当简单,如果它们已经使用Spring Servlet 3.0+初始化器辅助类。通常所有来自一个存在的`WebApplicationInitializer`的代码可以移到一个`SpringBootServletInitializer`中。如果一个存在的应用有多个`ApplicationContext`(比如,如果它使用`AbstractDispatcherServletInitializer`),那你可以将所有上下文源放进一个单一的`SpringApplication`。你遇到的主要难题可能是如果那样不能工作,那你就要维护上下文层次。参考示例[entry on building a hierarchy](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-build-an-application-context-hierarchy)。一个存在的包含web相关特性的父上下文通常需要分解,这样所有的`ServletContextAware`组件都处于子上下文中。 - -对于还不是Spring应用的应用来说,上面的指南有助于你把应用转换为一个Spring Boot应用,但你也可以选择其他方式。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.3 Fast Application Restarts.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.3 Fast Application Restarts.md" new file mode 100644 index 00000000..4d989a77 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85.3 Fast Application Restarts.md" @@ -0,0 +1,5 @@ +### 85.3 应用快速重启 + +`spring-boot-devtools`模块包括应用自动重启支持,虽然没有其他技术快,比如[JRebel](http://zeroturnaround.com/software/jrebel/),但比"冷启动"快。在研究其他复杂重启选项时,你最好自己先试下。 + +更多详情可参考[20. 开发者工具](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-devtools)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.4 Deploying a WAR to Weblogic.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.4 Deploying a WAR to Weblogic.md" deleted file mode 100644 index f848e4fb..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/85.4 Deploying a WAR to Weblogic.md" +++ /dev/null @@ -1,32 +0,0 @@ -### 85.4 部署WAR到Weblogic - -想要将Spring Boot应用部署到Weblogic,你需要确保你的servlet初始化器直接实现`WebApplicationInitializer`(即使你继承的基类已经实现了它)。 - -一个传统的Weblogic初始化器可能如下所示: -```java -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; -import org.springframework.web.WebApplicationInitializer; - -@SpringBootApplication -public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer { - -} -``` -如果使用logback,你需要告诉Weblogic你倾向使用的打包版本而不是服务器预装的版本。你可以通过添加一个具有如下内容的`WEB-INF/weblogic.xml`实现该操作: -```xml - - - - - org.slf4j - - - -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.4 Reload Java Classes without Restarting the Container.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.4 Reload Java Classes without Restarting the Container.md" new file mode 100644 index 00000000..86f30997 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/85.4 Reload Java Classes without Restarting the Container.md" @@ -0,0 +1,3 @@ +### 85.4 在不重启容器的情况下重新加载Java类 + +许多现代IDE(Eclipse、IDEA等)都支持字节码的热交换。所以如果你做了一个没有影响类或方法签名的改变,它会利索地重新加载并没有任何影响。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.5 Deploying a WAR in an Old\357\274\210Servlet 2.5\357\274\211Container.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.5 Deploying a WAR in an Old\357\274\210Servlet 2.5\357\274\211Container.md" deleted file mode 100644 index e7086bed..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/85.5 Deploying a WAR in an Old\357\274\210Servlet 2.5\357\274\211Container.md" +++ /dev/null @@ -1,46 +0,0 @@ -### 85.5 部署WAR到老的(Servlet2.5)容器 - -Spring Boot使用 Servlet 3.0 APIs初始化`ServletContext`(注册`Servlets`等),所以你不能在一个Servlet 2.5的容器中原封不动的使用同样的应用。使用一些特定的工具也是可以在老的容器中运行Spring Boot应用的。如果添加了`org.springframework.boot:spring-boot-legacy`依赖,你只需要创建一个`web.xml`,声明一个用于创建应用上下文的上下文监听器,过滤器和servlets。上下文监听器是专用于Spring Boot的,其他的都是一个Servlet 2.5的Spring应用所具有的。示例: -```xml - - - - - contextConfigLocation - demo.Application - - - - org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener - - - - metricFilter - org.springframework.web.filter.DelegatingFilterProxy - - - - metricFilter - /* - - - - appServlet - org.springframework.web.servlet.DispatcherServlet - - contextAttribute - org.springframework.web.context.WebApplicationContext.ROOT - - 1 - - - - appServlet - / - - - -``` -在该示例中,我们使用一个单一的应用上下文(通过上下文监听器创建的),然后使用一个init参数将它附加到`DispatcherServlet`。这在一个Spring Boot应用中是很正常的(你通常只有一个应用上下文)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/85.6 Use Lettuce instead of Jedis.md" "b/IX. \342\200\230How-to\342\200\231 guides/85.6 Use Lettuce instead of Jedis.md" deleted file mode 100644 index a1d0ce1b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/85.6 Use Lettuce instead of Jedis.md" +++ /dev/null @@ -1,37 +0,0 @@ -### 85.6 使用Lettuce来代替Jedis - -Spring Boot starter(`spring-boot-starter-data-redis`)默认使用[Jedis](https://github.com/xetorthio/jedis/)。你需要排除那个依赖,并把[Lettuce](https://github.com/lettuce-io/lettuce-core/)的依赖加入进来。你还需要`commons-pool2`。Spring Boot管理这些依赖,使这些步骤尽可能容易。 - -Maven的例子: -```xml - - org.springframework.boot - spring-boot-starter-data-redis - - - redis.clients - jedis - - - - - io.lettuce - lettuce-core - - - org.apache.commons - commons-pool2 - -``` -Gradle的例子: -```gradle -configurations { - compile.exclude module: "jedis" -} - -dependencies { - compile("io.lettuce:lettuce-core") - compile("org.apache.commons:commons-pool2") - // ... -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86. Build.md" "b/IX. \342\200\230How-to\342\200\231 guides/86. Build.md" new file mode 100644 index 00000000..47189481 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86. Build.md" @@ -0,0 +1,3 @@ +### 86. 构建 + +Spring Boot包含Maven和Gradle的构建插件。本节回答关于这些插件的常见问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.1 Generate Build Information.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.1 Generate Build Information.md" new file mode 100644 index 00000000..e8c5234f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.1 Generate Build Information.md" @@ -0,0 +1,32 @@ +### 86.1 生成构建信息 + +Maven插件和Gradle插件都支持产生包含项目版本、坐标、名称的构建信息。该插件可以通过配置添加其他属性。当这些文件出现时,Spring Boot自动配置一个`BuildProperties` bean。 + +为了让Maven生成构建信息,你需要为`build-info` goal添加一个execution: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + 2.0.0.RELEASE + + + + build-info + + + + + + +``` +**注** 更多详情查看[Spring Boot Maven插件文档](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin)。 + +使用Gradle实现同样效果: +```gradle +springBoot { + buildInfo() +} +``` +**注** 更多详情查看[Spring Boot Gradle插件文档](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/gradle-plugin/reference/html/#integrating-with-actuator-build-info)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.2 Generate Git Information.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.2 Generate Git Information.md" new file mode 100644 index 00000000..b848e1aa --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.2 Generate Git Information.md" @@ -0,0 +1,21 @@ +### 86.2 生成Git信息 + +Maven和Gradle都支持生成一个`git.properties`文件,该文件包含项目构建时`git`源码的仓库状态。对于Maven用户来说,`spring-boot-starter-parent` POM包含一个预配置的插件去产生一个`git.properties`文件,只需简单的将以下声明添加到POM中: +```xml + + + + pl.project13.maven + git-commit-id-plugin + + + +``` +Gradle用户可以使用[gradle-git-properties](https://plugins.gradle.org/plugin/com.gorylenko.gradle-git-properties)插件实现相同效果: +```gralde +plugins { + id "com.gorylenko.gradle-git-properties" version "1.4.17" +} +``` + +**注** `git.properties`中的提交时间需要符合以下格式:`yyyy-MM-dd’T’HH:mm:ssZ`。这是上面列出的两个插件的默认格式。使用这种格式可以将时间解析为`Date`,并将其格式序列化为JSON时,由Jackson的日期序列化配置设置控制。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.3 Customize Dependency Versions.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.3 Customize Dependency Versions.md" new file mode 100644 index 00000000..7384745d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.3 Customize Dependency Versions.md" @@ -0,0 +1,11 @@ +### 86.3 自定义依赖版本 + +如果你使用Maven进行一个直接或间接继承`spring-boot-dependencies`(比如`spring-boot-starter-parent`)的构建,并想覆盖一个特定的第三方依赖,那你可以添加合适的``元素。浏览[spring-boot-dependencies](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-dependencies/pom.xml) POM可以获取一个全面的属性列表。例如,想要选择一个不同的`slf4j`版本,你可以添加以下内容: +```xml + + 1.7.5 + +``` +**注** 这只在你的Maven项目继承(直接或间接)自`spring-boot-dependencies`才有用。如果你使用`import`,将`spring-boot-dependencies`添加到自己的`dependencyManagement`片段,那你必须自己重新定义artifact而不是覆盖属性。 + +**注** 每个Spring Boot发布都是基于一些特定的第三方依赖集进行设计和测试的,覆盖版本可能导致兼容性问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.4 Create an Executable JAR with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.4 Create an Executable JAR with Maven.md" new file mode 100644 index 00000000..c2813619 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.4 Create an Executable JAR with Maven.md" @@ -0,0 +1,33 @@ +### 86.4 使用Maven创建可执行JAR + +`spring-boot-maven-plugin`能够用来创建可执行的'胖'JAR。如果正在使用`spring-boot-starter-parent` POM,你可以简单地声明该插件,然后你的jar将被重新打包: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + + + +``` +如果没有使用parent POM,你仍旧可以使用该插件。不过,你需要另外添加一个``片段: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + 2.0.0.RELEASE + + + + repackage + + + + + + +``` +查看[插件文档](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin/usage.html)获取详细的用例。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.5 Use a Spring Boot Application as a Dependency.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.5 Use a Spring Boot Application as a Dependency.md" new file mode 100644 index 00000000..a02abf2a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.5 Use a Spring Boot Application as a Dependency.md" @@ -0,0 +1,22 @@ +### 86.5 将Spring Boot应用作为依赖 + +跟war包一样,Spring Boot应用不是用来作为依赖的。如果你的应用包含需要跟其他项目共享的类,最好的方式是将代码放到单独的模块,然后其他项目及你的应用都可以依赖该模块。 + +如果不能按照上述推荐的方式重新组织代码,你需要配置Spring Boot的Maven和Gradle插件去产生一个单独的artifact,以适合于作为依赖。可执行存档不能用于依赖,因为[可执行jar格式](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#executable-jar-jar-file-structure)将应用class打包到`BOOT-INF/classes`,也就意味着可执行jar用于依赖时会找不到。 + +为了产生两个artifacts(一个用于依赖,一个用于可执行jar),你需要指定classifier。classifier用于可执行存档的name,默认存档用于依赖。 + +可以使用以下配置Maven中classifier的`exec`: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + + exec + + + + +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.6 Extract Specific Libraries When an Executable Jar Runs.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.6 Extract Specific Libraries When an Executable Jar Runs.md" new file mode 100644 index 00000000..9430397c --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.6 Extract Specific Libraries When an Executable Jar Runs.md" @@ -0,0 +1,23 @@ +### 86.6 在可执行jar运行时提取特定的版本 + +在一个可执行jar中,为了运行,多数内嵌的库不需要拆包(unpacked),然而有一些库可能会遇到问题。例如,JRuby包含它自己的内嵌jar,它假定`jruby-complete.jar`本身总是能够直接作为文件访问的。 + +为了处理任何有问题的库,你可以标记那些特定的内嵌jars,让它们在可执行jar第一次运行时自动解压到一个临时文件夹中。例如,为了将JRuby标记为使用Maven插件拆包,你需要添加如下的配置: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.jruby + jruby-complete + + + + + + +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.7 Create a Non-executable JAR with Exclusions.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.7 Create a Non-executable JAR with Exclusions.md" new file mode 100644 index 00000000..949ba469 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.7 Create a Non-executable JAR with Exclusions.md" @@ -0,0 +1,33 @@ +### 86.7 使用排除创建不可执行的JAR + +如果你构建的两个单独的产物既有可执行的jar和非可执行的jar,那你常常需要为可执行的版本添加额外的配置文件,而这些文件在一个library jar中是不需要的。比如,`application.yml`配置文件可能需要从非可执行的JAR中排除。 + +在Maven里,可执行的jar必须是主要的artifact,并且你可以为类库加入一个分类的jar: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + + + maven-jar-plugin + + + lib + package + + jar + + + lib + + application.yml + + + + + + + +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.8 Remote Debug a Spring Boot Application Started with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.8 Remote Debug a Spring Boot Application Started with Maven.md" new file mode 100644 index 00000000..445a00c8 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.8 Remote Debug a Spring Boot Application Started with Maven.md" @@ -0,0 +1,4 @@ +### 86.8 远程调试使用Maven启动的Spring Boot项目 + +想要为使用Maven启动的Spring Boot应用添加一个远程调试器,你可以使用[mave插件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin)的jvmArguments属性。 +详情参考[示例](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin/examples/run-debug.html)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/86.9 Build an Executable Archive from Ant without Using spring-boot-antlib.md" "b/IX. \342\200\230How-to\342\200\231 guides/86.9 Build an Executable Archive from Ant without Using spring-boot-antlib.md" new file mode 100644 index 00000000..53171e15 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/86.9 Build an Executable Archive from Ant without Using spring-boot-antlib.md" @@ -0,0 +1,42 @@ +### 86.9 使用Ant构建可执行存档(不使用spring-boot-antlib) + +想要使用Ant进行构建,你需要抓取依赖,编译,然后像通常那样创建一个jar或war存档。为了让它可以执行,你可以使用`spring-boot-antlib`,也可以使用以下指令: + +1. 如果构建jar,你需要将应用的类和资源打包进内嵌的`BOOT-INF/classes`目录。如果构建war,你需要将应用的类打包进内嵌的`WEB-INF/classes`目录。 +2. 对于jar,添加运行时依赖到内嵌的`BOOT-INF/lib`目录。对于war,则添加到`WEB-INF/lib`目录。注意不能压缩存档中的实体。 +3. 对于jar,添加`provided`依赖到内嵌的`BOOT-INF/lib`目录。对于war,则添加到`WEB-INF/lib-provided`目录。注意不能压缩存档中的实体。 +4. 在存档的根目录添加`spring-boot-loader`类(这样`Main-Class`就可用了)。 +5. 使用恰当的启动器,比如对于jar使用`JarLauncher`作为manifest的`Main-Class`属性,指定manifest的其他属性,特别是设置`Start-Class`属性。 + +示例: +```xml + + + + + + + + + + + + + + + + + + + + + +``` +该[Ant示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-ant)中有一个`build.xml`文件及`manual`任务,可以使用以下命令来运行: +```shell +$ ant -lib clean manual +``` +在上述操作之后,你可以使用以下命令运行该应用: +```shell +$ java -jar target/*.jar +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/87. Traditional Deployment.md" "b/IX. \342\200\230How-to\342\200\231 guides/87. Traditional Deployment.md" new file mode 100644 index 00000000..1af7e516 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/87. Traditional Deployment.md" @@ -0,0 +1,3 @@ +### 87. 传统部署 + +Spring Boot支持传统部署和更现代的部署形式。本节回答关于传统部署的常见问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/87.1 Create a Deployable War File.md" "b/IX. \342\200\230How-to\342\200\231 guides/87.1 Create a Deployable War File.md" new file mode 100644 index 00000000..526608da --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/87.1 Create a Deployable War File.md" @@ -0,0 +1,53 @@ +### 87.1 创建可部署的war文件 + +产生一个可部署war包的第一步是提供一个`SpringBootServletInitializer`子类,并覆盖它的`configure`方法,这充分利用了Spring框架对Servlet 3.0的支持,并允许你在应用通过servlet容器启动时配置它。通常,你只需把应用的主类改为继承`SpringBootServletInitializer`即可: +```java +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(Application.class, args); + } + +} +``` +下一步是更新你的构建配置,这样你的项目将产生一个war包而不是jar包。如果你使用Maven,并使用`spring-boot-starter-parent`(为了配置Maven的war插件),所有你需要做的就是更改`pom.xml`的打包方式为`war`: +```xml +war +``` +如果你使用Gradle,你需要修改`build.gradle`来将war插件应用到项目上: +```gradle +apply plugin: 'war' +``` +该过程最后的一步是确保内嵌的servlet容器不能干扰war包将部署的servlet容器。为了达到这个目的,你需要将内嵌容器的依赖标记为`provided`。 + +如果你使用Maven,下面的示例将servlet容器(本例中为Tomcat)标记为提供: +```xml + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + +``` +如果你使用Gradle,下面的示例将servlet容器(本例中为Tomcat)标记为提供: +```gradle +dependencies { + // … + providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' + // … +} +``` +**注** `providedRuntime`更适合Gradle的`compileOnly`配置,因为`compileOnly`依赖不在测试类路径上,所以任何基于web的综合测试都会失败。 + +如果你使用[Spring Boot构建工具](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#build-tool-plugins),将内嵌容器依赖标记为`provided`将产生一个可执行war包,在`lib-provided`目录有该war包的`provided`依赖。这意味着,除了部署到servlet容器,你还可以通过使用命令行`java -jar`命令来运行应用。 + +**提示** 查看Spring Boot基于以上配置的一个[Maven示例应用](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples/spring-boot-sample-traditional/pom.xml)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/87.2 Create a Deployable War File for Older Servlet Containers.md" "b/IX. \342\200\230How-to\342\200\231 guides/87.2 Create a Deployable War File for Older Servlet Containers.md" new file mode 100644 index 00000000..611e3f1c --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/87.2 Create a Deployable War File for Older Servlet Containers.md" @@ -0,0 +1,3 @@ +### 87.2 为老的servlet容器创建可部署的war文件 + +老的Servlet容器不支持在Servlet 3.0中使用的`ServletContextInitializer`启动处理。你仍旧可以在这些容器使用Spring和Spring Boot,但你需要为应用添加一个`web.xml`,并将它配置为通过一个`DispatcherServlet`加载一个`ApplicationContext`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/87.3 Convert an Existing Application to Spring Boot.md" "b/IX. \342\200\230How-to\342\200\231 guides/87.3 Convert an Existing Application to Spring Boot.md" new file mode 100644 index 00000000..423fa4a9 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/87.3 Convert an Existing Application to Spring Boot.md" @@ -0,0 +1,68 @@ +### 87.3 将现有的应用转换为Spring Boot + +对于一个非web项目,转换为Spring Boot应用很容易(抛弃创建`ApplicationContext`的代码,取而代之的是调用`SpringApplication`或`SpringApplicationBuilder`)。Spring MVC web应用通常先创建一个可部署的war应用,然后将它迁移为一个可执行的war或jar。建议阅读[Getting Started Guide on Converting a jar to a war.](https://spring.io/guides/gs/convert-jar-to-war/)。 + +通过继承`SpringBootServletInitializer`创建一个可执行war(比如,在一个名为`Application`的类中),然后添加Spring Boot的`@SpringBootApplication`注解,示例: +```java +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + // Customize the application or call application.sources(...) to add sources + // Since our example is itself a @Configuration class (via @SpringBootApplication) + // we actually don't need to override this method. + return application; + } + +} +``` +记住不管你往`sources`放什么东西,它仅是一个Spring `ApplicationContext`,正常情况下,任何生效的在这里也会起作用。有一些beans你可以先移除,然后让Spring Boot提供它的默认实现,不过有可能需要先完成一些事情。 + +静态资源可以移到classpath根目录下的`/public`(或`/static`,`/resources`,`/META-INF/resources`)。同样的方式也适合于`messages.properties`(Spring Boot在classpath根目录下自动发现这些配置)。 + +美妙的(Vanilla usage of)Spring `DispatcherServlet`和Spring Security不需要改变。如果你的应用有其他特性,比如使用其他servlets或filters,那你可能需要添加一些配置到你的`Application`上下文中,按以下操作替换`web.xml`的那些元素: + +- 在容器中安装一个`Servlet`或`ServletRegistrationBean`类型的`@Bean`,就好像`web.xml`中的``和``。 +- 同样的添加一个`Filter`或`FilterRegistrationBean`类型的`@Bean`(类似于``和``)。 +- 在XML文件中的`ApplicationContext`可以通过`@ImportResource`添加到你的`Application`中。简单的情况下,大量使用注解配置可以在几行内定义`@Bean`定义。 + +一旦war可以使用,我们就通过添加一个main方法到`Application`来让它可以执行,比如: +```java +public static void main(String[] args) { + SpringApplication.run(Application.class, args); +} +``` + +**注** 如果你想要把你的应用作为war或者可执行的应用来启动,你需要在一个方法里面共享构建器的配置。那个方法要对`SpringBootServletInitializer`回调和`main`方法都可用,就像这样: +```java +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return configureApplication(builder); + } + + public static void main(String[] args) { + configureApplication(new SpringApplicationBuilder()).run(args); + } + + private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) { + return builder.sources(Application.class).bannerMode(Banner.Mode.OFF); + } + +} +``` +应用可以划分为多个类别: + +- 没有web.xml的Servlet 3.0+应用 +- 有web.xml的应用 +- 有上下文层次的应用 +- 没有上下文层次的应用 + +所有这些都可以进行适当的转化,但每个可能需要稍微不同的技术。 + +Servlet 3.0+的应用转化的相当简单,如果它们已经使用Spring Servlet 3.0+初始化器辅助类。通常所有来自一个存在的`WebApplicationInitializer`的代码可以移到一个`SpringBootServletInitializer`中。如果一个存在的应用有多个`ApplicationContext`(比如,如果它使用`AbstractDispatcherServletInitializer`),那你可以将所有上下文源放进一个单一的`SpringApplication`。你遇到的主要难题可能是如果那样不能工作,那你就要维护上下文层次。参考示例[entry on building a hierarchy](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-build-an-application-context-hierarchy)。一个存在的包含web相关特性的父上下文通常需要分解,这样所有的`ServletContextAware`组件都处于子上下文中。 + +对于还不是Spring应用的应用来说,上面的指南有助于你把应用转换为一个Spring Boot应用。然而,你可能会遇到一些问题。在这种情况下,我们建议[使用spring-boot标签在Stack Overflow上提问](https://stackoverflow.com/questions/tagged/spring-boot)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/87.4 Deploying a WAR to Weblogic.md" "b/IX. \342\200\230How-to\342\200\231 guides/87.4 Deploying a WAR to Weblogic.md" new file mode 100644 index 00000000..0fb4f5b7 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/87.4 Deploying a WAR to Weblogic.md" @@ -0,0 +1,32 @@ +### 87.4 部署WAR到Weblogic + +想要将Spring Boot应用部署到Weblogic,你需要确保你的servlet初始化器直接实现`WebApplicationInitializer`(即使你继承的基类已经实现了它)。 + +一个传统的Weblogic初始化器可能如下所示: +```java +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.web.WebApplicationInitializer; + +@SpringBootApplication +public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer { + +} +``` +如果使用Logback,你需要告诉Weblogic你倾向使用的打包版本而不是服务器预装的版本。你可以通过添加一个具有如下内容的`WEB-INF/weblogic.xml`实现该操作: +```xml + + + + + org.slf4j + + + +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/87.5 Deploying a WAR in an Old\357\274\210Servlet 2.5\357\274\211Container.md" "b/IX. \342\200\230How-to\342\200\231 guides/87.5 Deploying a WAR in an Old\357\274\210Servlet 2.5\357\274\211Container.md" new file mode 100644 index 00000000..e982dd76 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/87.5 Deploying a WAR in an Old\357\274\210Servlet 2.5\357\274\211Container.md" @@ -0,0 +1,46 @@ +### 87.5 部署WAR到老的(Servlet2.5)容器 + +Spring Boot使用 Servlet 3.0 APIs初始化`ServletContext`(注册`Servlets`等),所以你不能在一个Servlet 2.5的容器中原封不动的使用同样的应用。使用一些特定的工具也是可以在老的容器中运行Spring Boot应用的。如果添加了`org.springframework.boot:spring-boot-legacy`依赖,你只需要创建一个`web.xml`,声明一个用于创建应用上下文的上下文监听器,过滤器和servlets。上下文监听器是专用于Spring Boot的,其他的都是一个Servlet 2.5的Spring应用所具有的。示例: +```xml + + + + + contextConfigLocation + demo.Application + + + + org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener + + + + metricFilter + org.springframework.web.filter.DelegatingFilterProxy + + + + metricFilter + /* + + + + appServlet + org.springframework.web.servlet.DispatcherServlet + + contextAttribute + org.springframework.web.context.WebApplicationContext.ROOT + + 1 + + + + appServlet + / + + + +``` +在该示例中,我们使用一个单一的应用上下文(通过上下文监听器创建的),然后使用一个init参数将它附加到`DispatcherServlet`。这在一个Spring Boot应用中是很正常的(你通常只有一个应用上下文)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/87.6 Use Jedis Instead of Lettuce.md" "b/IX. \342\200\230How-to\342\200\231 guides/87.6 Use Jedis Instead of Lettuce.md" new file mode 100644 index 00000000..54ba1b38 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/87.6 Use Jedis Instead of Lettuce.md" @@ -0,0 +1,32 @@ +### 87.6 使用Jedis来代替Lettuce + +Spring Boot starter(`spring-boot-starter-data-redis`)默认使用[Lettuce](https://github.com/lettuce-io/lettuce-core/)。你需要排除那个依赖,并把[Jedis](https://github.com/xetorthio/jedis/)的依赖加入进来。Spring Boot管理这些依赖,使这些步骤尽可能容易。 + +Maven的例子: +```xml + + org.springframework.boot + spring-boot-starter-data-redis + + + io.lettuce + lettuce-core + + + + + redis.clients + jedis + +``` +Gradle的例子: +```gradle +configurations { + compile.exclude module: "lettuce" +} + +dependencies { + compile("redis.clients:jedis") + // ... +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/README.md" "b/IX. \342\200\230How-to\342\200\231 guides/README.md" index 5df2a394..0df2b670 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/README.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/README.md" @@ -2,6 +2,6 @@ 本章节将回答一些常见的"我该怎么做"类型的问题,这些问题在我们使用Spring Boot时经常遇到。这虽然不是一个详尽的列表,但它覆盖了很多方面。 -如果遇到一个特殊的我们没有覆盖的问题,你可以查看[stackoverflow.com](http://stackoverflow.com/tags/spring-boot),看是否已经有人给出了答案;这也是一个很好的提新问题的地方(请使用`spring-boot`标签)。 +如果遇到一个特殊的我们没有覆盖的问题,你可以查看[stackoverflow.com](https://stackoverflow.com/tags/spring-boot),看是否已经有人给出了答案。这也是一个很好的提新问题的地方(请使用`spring-boot`标签)。 -我们也乐意扩展本章节;如果想添加一个'how-to',你可以给我们发一个[pull请求](http://github.com/spring-projects/spring-boot/tree/master)。 +我们也乐意扩展本章节。如果想添加一个'how-to',你可以给我们发一个[合并请求](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE)。 diff --git a/README.md b/README.md index 4ad1e8fe..2fad938c 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,21 @@ # Spring-Boot-Reference-Guide + +![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg) + Spring Boot Reference Guide 2.0 中文翻译 -《Spring Boot参考指南》 说明: -本文档翻译的版本:[2.0.0.RELEASE](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/) +本文档翻译的版本:[2.0.0.RELEASE](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/) -GitBook : [Spring Boot参考指南](https://jack80342.gitbooks.io/spring-boot/content/) +GitBook : [Spring Boot参考指南](https://jack80342.gitbook.io/spring-boot/) GitHub : [Spring Boot参考指南](https://github.com/jack80342/Spring-Boot-Reference-Guide) -我和小白住在东京。 -我们花了好多个周末,将这本参考指南翻译到最新的版本。 -如果你想支持我们的工作🙃,你可以给小白买几条小鱼干🐟。 + 我从二零一七年夏天开始翻译这份文档。这份文档在[qibaoguang](https://github.com/qibaoguang)的1.4.1版本上新增了Spring Boot 2.0.0版本的内容,对修改的地方也做了更新。 -|WeChatPay|ALipay|Paypal| -|:----|:----|:----| -|![ALiPay](https://github.com/jack80342/Materials/raw/master/Spring-Boot-Reference-Guide/alipay.jpg)|![WeChatPay](https://github.com/jack80342/Materials/raw/master/Spring-Boot-Reference-Guide/wechatpay.jpg)|![PayPal](https://github.com/jack80342/Materials/raw/master/Spring-Boot-Reference-Guide/paypal.jpg)| +如果这份文档帮到了你🙃,你可以给我家的小白买几条小鱼干🐟。 -附上小白午睡的照片🐈 -![小白](https://github.com/jack80342/Materials/raw/master/Spring-Boot-Reference-Guide/xiaobai.jpg) +|WeChatPay|ALipay|[Paypal](https://www.paypal.me/jack8034)| +|:----|:----|:----| +|![WeChatPay](https://github.com/jack80342/Materials/blob/master/wechatpay.jpg)|![ALiPay](https://github.com/jack80342/Materials/blob/master/alipay.jpg)|![PayPal](https://github.com/jack80342/Materials/blob/master/paypal.PNG)| diff --git a/SUMMARY.md b/SUMMARY.md index 59bde7e0..db9038c7 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -1,554 +1,596 @@ -# Summary - -* [I. Spring Boot文档](I. Spring Boot Documentation/README.md) - * [1. 关于本文档](I. Spring Boot Documentation/1. About the documentation.md) - * [2. 获取帮助](I. Spring Boot Documentation/2. Getting help.md) - * [3. 第一步](I. Spring Boot Documentation/3. First steps.md) - * [4. 使用Spring Boot](I. Spring Boot Documentation/4. Working with Spring Boot.md) - * [5. 了解Spring Boot特性](I. Spring Boot Documentation/5. Learning about Spring Boot features.md) - * [6. 迁移到生产环境](I. Spring Boot Documentation/6. Moving to production.md) - * [7. 高级主题](I. Spring Boot Documentation/7. Advanced topics.md) -* [II. 开始](II. Getting started/README.md) - * [8. Spring Boot介绍](II. Getting started/8. Introducing Spring Boot.md) - * [9. 系统要求](II. Getting started/9. System Requirements.md) - * [9.1. Servlet容器](II. Getting started/9.1. Servlet containers.md) - * [10. Spring Boot安装](II. Getting started/10. Installing Spring Boot.md) - * [10.1. 为Java开发者准备的安装指南](II. Getting started/10.1. Installation instructions for the Java developer.md) - * [10.1.1. Maven安装](II. Getting started/10.1.1. Maven installation.md) - * [10.1.2. Gradle安装](II. Getting started/10.1.2. Gradle installation.md) - * [10.2. Spring Boot CLI安装](II. Getting started/10.2. Installing the Spring Boot CLI.md) - * [10.2.1. 手动安装](II. Getting started/10.2.1. Manual installation.md) - * [10.2.2. 使用SDKMAN进行安装](II. Getting started/10.2.2. Installation with SDKMAN.md) - * [10.2.3. 使用OSX Homebrew进行安装](II. Getting started/10.2.3. OSX Homebrew installation.md) - * [10.2.4. 使用MacPorts进行安装](II. Getting started/10.2.4. MacPorts installation.md) - * [10.2.5. 命令行实现](II. Getting started/10.2.5. Command-line completion.md) - * [10.2.6. Spring CLI示例快速入门](II. Getting started/10.2.6. Quick start Spring CLI example.md) - * [10.3. 从Spring Boot早期版本升级](II. Getting started/10.3. Upgrading from an earlier version of Spring Boot.md) - * [11. 开发你的第一个Spring Boot应用](II. Getting started/11. Developing your first Spring Boot application.md) - * [11.1. 创建POM](II. Getting started/11.1. Creating the POM.md) - * [11.2. 添加classpath依赖](II. Getting started/11.2. Adding classpath dependencies.md) - * [11.3. 编写代码](II. Getting started/11.3. Writing the code.md) - * [11.3.1. @RestController和@RequestMapping注解](II. Getting started/11.3.1. The @RestController and @RequestMapping annotations.md) - * [11.3.2. @EnableAutoConfiguration注解](II. Getting started/11.3.2. The @EnableAutoConfiguration annotation.md) - * [11.3.3. main方法](II. Getting started/11.3.3. The “main” method.md) - * [11.4. 运行示例](II. Getting started/11.4. Running the example.md) - * [11.5. 创建一个可执行jar](II. Getting started/11.5. Creating an executable jar.md) - * [12. 接下来阅读什么](II. Getting started/12. What to read next.md) -* [III. 使用Spring Boot](III. Using Spring Boot/README.md) - * [13. 构建系统](III. Using Spring Boot/13. Build systems.md) - * [13.1. 依赖管理](III. Using Spring Boot/13.1. Dependency management.md) - * [13.2. Maven](III. Using Spring Boot/13.2. Maven.md) - * [13.2.1. 继承starter parent](III. Using Spring Boot/13.2.1. Inheriting the starter parent.md) - * [13.2.2. 在不使用parent POM的情况下玩转Spring Boot](III. Using Spring Boot/13.2.2. Using Spring Boot without the parent POM.md) - * [13.2.3. 使用Spring Boot Maven插件](III. Using Spring Boot/13.2.3. Using the Spring Boot Maven plugin.md) - * [13.3. Gradle](III. Using Spring Boot/13.3. Gradle.md) - * [13.4. Ant](III. Using Spring Boot/13.4. Ant.md) - * [13.5. Starters](III. Using Spring Boot/13.5. Starters.md) - * [14. 组织你的代码](III. Using Spring Boot/14. Structuring your code.md) - * [14.1. 使用"default"包](III. Using Spring Boot/14.1. Using the “default” package.md) - * [14.2. 放置应用的main类](III. Using Spring Boot/14.2. Locating the main application class.md) - * [15. 配置类](III. Using Spring Boot/15. Configuration classes.md) - * [15.1. 导入其他配置类](III. Using Spring Boot/15.1. Importing additional configuration classes.md) - * [15.2. 导入XML配置](III. Using Spring Boot/15.2. Importing XML configuration.md) - * [16. 自动配置](III. Using Spring Boot/16. Auto-configuration.md) - * [16.1. 逐步替换自动配置](III. Using Spring Boot/16.1. Gradually replacing auto-configuration.md) - * [16.2. 禁用特定的自动配置](III. Using Spring Boot/16.2. Disabling specific auto-configuration.md) - * [17. Spring Beans和依赖注入](III. Using Spring Boot/17. Spring Beans and dependency injection.md) - * [18. 使用@SpringBootApplication注解](III. Using Spring Boot/18. Using the @SpringBootApplication annotation.md) - * [19. 运行应用程序](III. Using Spring Boot/19. Running your application.md) - * [19.1. 从IDE中运行](III. Using Spring Boot/19.1. Running from an IDE.md) - * [19.2. 作为一个打包后的应用运行](III. Using Spring Boot/19.2. Running as a packaged application.md) - * [19.3. 使用Maven插件运行](III. Using Spring Boot/19.3. Using the Maven plugin.md) - * [19.4. 使用Gradle插件运行](III. Using Spring Boot/19.4. Using the Gradle plugin.md) - * [19.5. 热交换](III. Using Spring Boot/19.5. Hot swapping.md) - * [20. 开发者工具](III. Using Spring Boot/20. Developer tools.md) - * [20.1. 默认属性](III. Using Spring Boot/20.1. Property defaults.md) - * [20.2. 自动重启](III. Using Spring Boot/20.2. Automatic restart.md) - * [20.2.1. 排除资源](III. Using Spring Boot/20.2.1. Excluding resources.md) - * [20.2.2. 查看其他路径](III. Using Spring Boot/20.2.2. Watching additional paths.md) - * [20.2.3. 禁用重启](III. Using Spring Boot/20.2.3. Disabling restart.md) - * [20.2.4. 使用触发器文件](III. Using Spring Boot/20.2.4. Using a trigger file.md) - * [20.2.5. 自定义restart类加载器](III. Using Spring Boot/20.2.5. Customizing the restart classloader.md) - * [20.2.6. 已知限制](III. Using Spring Boot/20.2.6. Known limitations.md) - * [20.3. LiveReload](III. Using Spring Boot/20.3. LiveReload.md) - * [20.4. 全局设置](III. Using Spring Boot/20.4. Global settings.md) - * [20.5. 远程应用](III. Using Spring Boot/20.5. Remote applications.md) - * [20.5.1. 运行远程客户端应用](III. Using Spring Boot/20.5.1. Running the remote client application.md) - * [20.5.2. 远程更新](III. Using Spring Boot/20.5.2. Remote update.md) - * [21. 打包用于生产的应用](III. Using Spring Boot/21. Packaging your application for production.md) - * [22. 接下来阅读什么](III. Using Spring Boot/22. What to read next.md) -* [IV. Spring Boot特性](IV. Spring Boot features/README.md) - * [23. SpringApplication](IV. Spring Boot features/23. SpringApplication.md) - * [23.1. 启动失败](IV. Spring Boot features/23.1. Startup failure.md) - * [23.2. 自定义Banner](IV. Spring Boot features/23.2. Customizing the Banner.md) - * [23.3. 自定义SpringApplication](IV. Spring Boot features/23.3. Customizing SpringApplication.md) - * [23.4. 流式构建API](IV. Spring Boot features/23.4. Fluent builder API.md) - * [23.5. Application事件和监听器](IV. Spring Boot features/23.5. Application events and listeners.md) - * [23.6. Web环境](IV. Spring Boot features/23.6. Web environment.md) - * [23.7. 访问应用参数](IV. Spring Boot features/23.7. Accessing application arguments.md) - * [23.8. 使用ApplicationRunner或CommandLineRunner](IV. Spring Boot features/23.8. Using the ApplicationRunner or CommandLineRunner.md) - * [23.9. Application退出](IV. Spring Boot features/23.9. Application exit.md) - * [23.10. Admin特性](IV. Spring Boot features/23.10. Admin features.md) - * [24.外化配置](IV. Spring Boot features/24. Externalized Configuration.md) - * [24.1. 配置随机值](IV. Spring Boot features/24.1. Configuring random values.md) - * [24.2. 访问命令行属性](IV. Spring Boot features/24.2. Accessing command line properties.md) - * [24.3. Application属性文件](IV. Spring Boot features/24.3. Application property files.md) - * [24.4. Profile-specific属性](IV. Spring Boot features/24.4. Profile-specific properties.md) - * [24.5. 属性占位符](IV. Spring Boot features/24.5. Placeholders in properties.md) - * [24.6. 使用YAML代替Properties](IV. Spring Boot features/24.6. Using YAML instead of Properties.md) - * [24.6.1. 加载YAML](IV. Spring Boot features/24.6.1. Loading YAML.md) - * [24.6.2. 在Spring环境中使用YAML暴露属性](IV. Spring Boot features/24.6.2. Exposing YAML as properties in the Spring Environment.md) - * [24.6.3. Multi-profile YAML文档](IV. Spring Boot features/24.6.3. Multi-profile YAML documents.md) - * [24.6.4. YAML缺点](IV. Spring Boot features/24.6.4. YAML shortcomings.md) - * [24.6.5. 合并YAML列表](IV. Spring Boot features/24.6.5. Merging YAML lists.md) - * [24.7. 类型安全的配置属性](IV. Spring Boot features/24.7. Type-safe Configuration Properties.md) - * [24.7.1. 第三方配置](IV. Spring Boot features/24.7.1. Third-party configuration.md) - * [24.7.2. Relaxed绑定](IV. Spring Boot features/24.7.2. Relaxed binding.md) - * [24.7.3. 属性转换](IV. Spring Boot features/24.7.3. Properties conversion.md) - * [24.7.4. @ConfigurationProperties校验](IV. Spring Boot features/24.7.4. @ConfigurationProperties Validation.md) - * [24.7.5. @ConfigurationProperties vs @Value](IV. Spring Boot features/24.7.5. @ConfigurationProperties vs. @Value.md) - * [25. Profiles](IV. Spring Boot features/25. Profiles.md) - * [25.1. 添加激活的profiles](IV. Spring Boot features/25.1. Adding active profiles.md) - * [25.2.以编程方式设置profiles](IV. Spring Boot features/25.2. Programmatically setting profiles.md) - * [25.3. Profile-specific配置文件](IV. Spring Boot features/25.3. Profile specific configuration files.md) - * [26. 日志](IV. Spring Boot features/26. Logging.md) - * [26.1. 日志格式](IV. Spring Boot features/26.1. Log format.md) - * [26.2. 控制台输出](IV. Spring Boot features/26.2. Console output.md) - * [26.2.1. Color-coded输出](IV. Spring Boot features/26.2.1. Color-coded output.md) - * [26.3. 文件输出](IV. Spring Boot features/26.3. File output.md) - * [26.4. 日志级别](IV. Spring Boot features/26.4. Log Levels.md) - * [26.5. 自定义日志配置](IV. Spring Boot features/26.5. Custom log configuration.md) - * [26.6. Logback扩展](IV. Spring Boot features/26.6. Logback extensions.md) - * [26.6.1. Profile-specific配置](IV. Spring Boot features/26.6.1. Profile-specific configuration.md) - * [26.6.2. Environment属性](IV. Spring Boot features/26.6.2. Environment properties.md) - * [27. 开发Web应用](IV. Spring Boot features/27. Developing web applications.md) - * [27.1. Spring Web MVC框架](IV. Spring Boot features/27.1. The ‘Spring Web MVC framework’.md) - * [27.1.1. Spring MVC自动配置](IV. Spring Boot features/27.1.1. Spring MVC auto-configuration.md) - * [27.1.2. HttpMessageConverters](IV. Spring Boot features/27.1.2. HttpMessageConverters.md) - * [27.1.3. 自定义JSON序列化器和反序列化器](IV. Spring Boot features/27.1.3. Custom JSON Serializers and Deserializers.md) - * [27.1.4. MessageCodesResolver](IV. Spring Boot features/27.1.4. MessageCodesResolver.md) - * [27.1.5. 静态内容](IV. Spring Boot features/27.1.5. Static Content.md) - * [27.1.6. 定制网站图标](IV. Spring Boot features/27.1.6. Custom Favicon.md) - * [27.1.7. ConfigurableWebBindingInitializer](IV. Spring Boot features/27.1.7. ConfigurableWebBindingInitializer.md) - * [27.1.8. 模板引擎](IV. Spring Boot features/27.1.8. Template engines.md) - * [27.1.9. 错误处理](IV. Spring Boot features/27.1.9. Error Handling.md) - * [27.1.10. Spring HATEOAS](IV. Spring Boot features/27.1.10. Spring HATEOAS.md) - * [27.1.11. CORS支持](IV. Spring Boot features/27.1.11. CORS support.md) - * [27.2 The ‘Spring WebFlux framework’](IV. Spring Boot features/27.2 The ‘Spring WebFlux framework’.md) - * [27.2.1 Spring WebFlux auto-configuration](IV. Spring Boot features/27.2.1 Spring WebFlux auto-configuration.md) - * [27.2.2 HTTP codecs with HttpMessageReaders and HttpMessageWriters](IV. Spring Boot features/27.2.2 HTTP codecs with HttpMessageReaders and HttpMessageWriters.md) - * [27.2.3 Static Content](IV. Spring Boot features/27.2.3 Static Content.md) - * [27.2.4 Template engines](IV. Spring Boot features/27.2.4 Template engines.md) - * [27.3. JAX-RS和Jersey](IV. Spring Boot features/27.3. JAX-RS and Jersey.md) - * [27.4 内嵌servlet容器支持](IV. Spring Boot features/27.4 Embedded servlet container support.md) - * [27.4.1 Servlets, Filters和listeners](IV. Spring Boot features/27.4.1 Servlets, Filters, and listeners.md) - * [27.4.2 Servlet上下文初始化](IV. Spring Boot features/27.4.2 Servlet Context Initialization.md) - * [27.4.3 ServletWebServerApplicationContext](IV. Spring Boot features/27.4.3 The ServletWebServerApplicationContext.md) - * [27.4.4 自定义内嵌servlet容器](IV. Spring Boot features/27.4.4 Customizing embedded servlet containers.md) - * [27.4.5 JSP的限制](IV. Spring Boot features/27.4.5 JSP limitations.md) - * [28. 安全](IV. Spring Boot features/28. Security.md) - * [28.1 OAuth2](IV. Spring Boot features/28.1 OAuth2.md) - * [28.1.1 授权服务器](IV. Spring Boot features/28.1.1 Authorization Server.md) - * [28.1.2 资源服务器](IV. Spring Boot features/28.1.2 Resource Server.md) - * [28.2 User Info中的Token类型](IV. Spring Boot features/28.2 Token Type in User Info.md) - * [28.3 自定义User Info RestTemplate](IV. Spring Boot features/28.3 Customizing the User Info RestTemplate.md) - * [28.3.1 客户端](IV. Spring Boot features/28.3.1 Client.md) - * [28.3.2 单点登陆](IV. Spring Boot features/28.3.2 Single Sign On.md) - * [28.4 Actuator安全](IV. Spring Boot features/28.4 Actuator Security.md) - * [29. 使用SQL数据库](IV. Spring Boot features/29. Working with SQL databases.md) - * [29.1. 配置DataSource](IV. Spring Boot features/29.1. Configure a DataSource.md) - * [29.1.1. 对内嵌数据库的支持](IV. Spring Boot features/29.1.1. Embedded Database Support.md) - * [29.1.2. 连接生产环境数据库](IV. Spring Boot features/29.1.2. Connection to a production database.md) - * [29.1.3. 连接JNDI数据库](IV. Spring Boot features/29.1.3. Connection to a JNDI DataSource.md) - * [29.2. 使用JdbcTemplate](IV. Spring Boot features/29.2. Using JdbcTemplate.md) - * [29.3. JPA和Spring Data](IV. Spring Boot features/29.3. JPA and ‘Spring Data’.md) - * [29.3.1. 实体类](IV. Spring Boot features/29.3.1. Entity Classes.md) - * [29.3.2. Spring Data JPA仓库](IV. Spring Boot features/29.3.2. Spring Data JPA Repositories.md) - * [29.3.3. 创建和删除JPA数据库](IV. Spring Boot features/29.3.3. Creating and dropping JPA databases.md) - * [29.3.4. 在视图中打开实体管理器](IV. Spring Boot features/29.3.4. Open EntityManager in View.md) - * [29.4 使用H2的web控制台](IV. Spring Boot features/29.4 Using H2’s web console.md) - * [29.4.1 改变H2控制台路径](IV. Spring Boot features/29.4.1 Changing the H2 console’s path.md) - * [29.4.2 保护H2控制台](IV. Spring Boot features/29.4.2 Securing the H2 console.md) - * [29.5 使用jOOQ](IV. Spring Boot features/29.5 Using jOOQ.md) - * [29.5.1 代码生成](IV. Spring Boot features/29.5.1 Code Generation.md) - * [29.5.2 使用DSLContext](IV. Spring Boot features/29.5.2 Using DSLContext.md) - * [29.5.3 jOOQ SQL方言](IV. Spring Boot features/29.5.3 jOOQ SQL dialect.md) - * [29.5.4 自定义jOOQ](IV. Spring Boot features/29.5.4 Customizing jOOQ.md) - * [30. 使用NoSQL技术](IV. Spring Boot features/30. Working with NoSQL technologies.md) - * [30.1. Redis](IV. Spring Boot features/30.1. Redis.md) - * [30.1.1. 连接Redis](IV. Spring Boot features/30.1.1. Connecting to Redis.md) - * [30.2. MongoDB](IV. Spring Boot features/30.2. MongoDB.md) - * [30.2.1. 连接MongoDB数据库](IV. Spring Boot features/30.2.1. Connecting to a MongoDB database.md) - * [30.2.2. MongoDBTemplate](IV. Spring Boot features/30.2.2. MongoTemplate.md) - * [30.2.3. Spring Data MongoDB仓库](IV. Spring Boot features/30.2.3. Spring Data MongoDB repositories.md) - * [30.2.4 内嵌的Mongo](IV. Spring Boot features/30.2.4 Embedded Mongo.md) - * [30.3 Neo4j](IV. Spring Boot features/30.3 Neo4j.md) - * [30.3.1 连接Neo4j数据库](IV. Spring Boot features/30.3.1 Connecting to a Neo4j database.md) - * [30.3.2 使用内嵌模式](IV. Spring Boot features/30.3.2 Using the embedded mode.md) - * [30.3.3 Neo4jSession](IV. Spring Boot features/30.3.3 Neo4jSession.md) - * [30.3.4 Spring Data Neo4j仓库](IV. Spring Boot features/30.3.4 Spring Data Neo4j repositories.md) - * [30.3.5 仓库示例](IV. Spring Boot features/30.3.5 Repository example.md) - * [30.4 Gemfire](IV. Spring Boot features/30.4 Gemfire.md) - * [30.5 Solr](IV. Spring Boot features/30.5 Solr.md) - * [30.5.1 连接Solr](IV. Spring Boot features/30.5.1 Connecting to Solr.md) - * [30.5.2 Spring Data Solr仓库](IV. Spring Boot features/30.5.2 Spring Data Solr repositories.md) - * [30.6 Elasticsearch](IV. Spring Boot features/30.6 Elasticsearch.md) - * [30.6.1 使用Jest连接Elasticsearch](IV. Spring Boot features/30.6.1 Connecting to Elasticsearch using Jest.md) - * [30.6.2 使用Spring Data连接Elasticsearch](IV. Spring Boot features/30.6.2 Connecting to Elasticsearch using Spring Data.md) - * [30.6.3 Spring Data Elasticseach仓库](IV. Spring Boot features/30.6.3 Spring Data Elasticsearch repositories.md) - * [30.7 Cassandra](IV. Spring Boot features/30.7 Cassandra.md) - * [30.7.1 连接Cassandra](IV. Spring Boot features/30.7.1 Connecting to Cassandra.md) - * [30.7.2 Spring Data Cassandra仓库](IV. Spring Boot features/30.7.2 Spring Data Cassandra repositories.md) - * [30.8 Couchbase](IV. Spring Boot features/30.8 Couchbase.md) - * [30.8.1 连接Couchbase](IV. Spring Boot features/30.8.1 Connecting to Couchbase.md) - * [30.8.2 Spring Data Couchbase仓库](IV. Spring Boot features/30.8.2 Spring Data Couchbase repositories.md) - * [30.9 LDAP](IV. Spring Boot features/30.9 LDAP.md) - * [30.9.1 连接LDAP服务器](IV. Spring Boot features/30.9.1 Connecting to an LDAP server.md) - * [30.9.2 Spring Data LDAP仓库](IV. Spring Boot features/30.9.2 Spring Data LDAP repositories.md) - * [30.9.3 嵌入式内存中LDAP服务器](IV. Spring Boot features/30.9.3 Embedded in-memory LDAP server.md) - * [30.10 InfluxDB](IV. Spring Boot features/30.10 InfluxDB.md) - * [30.10.1 连接InfluxDB](IV. Spring Boot features/30.10.1 Connecting to InfluxDB.md) - * [31. 缓存](IV. Spring Boot features/31. Caching.md) - * [31.1 支持的缓存提供商](IV. Spring Boot features/31.1 Supported cache providers.md) - * [31.1.1 Generic](IV. Spring Boot features/31.1.1 Generic.md) - * [31.1.2 JCache (JSR-107)](IV. Spring Boot features/31.1.2 JCache(JSR-107).md) - * [31.1.3 EhCache 2.x](IV. Spring Boot features/31.1.3 EhCache 2.x.md) - * [31.1.4 Hazelcast](IV. Spring Boot features/31.1.4 Hazelcast.md) - * [31.1.5 Infinispan](IV. Spring Boot features/31.1.5 Infinispan.md) - * [31.1.6 Couchbase](IV. Spring Boot features/31.1.6 Couchbase.md) - * [31.1.7 Redis](IV. Spring Boot features/31.1.7 Redis.md) - * [31.1.8 Caffeine](IV. Spring Boot features/31.1.8 Caffeine.md) - * [31.1.9 Simple](IV. Spring Boot features/31.1.9 Simple.md) - * [31.1.10 None](IV. Spring Boot features/31.1.10 None.md) - * [32. 消息](IV. Spring Boot features/32. Messaging.md) - * [32.1. JMS](IV. Spring Boot features/32.1. JMS.md) - * [32.1.1 ActiveQ支持](IV. Spring Boot features/32.1.1 ActiveMQ support.md) - * [32.1.2 Artemis支持](IV. Spring Boot features/32.1.2 Artemis support.md) - * [32.1.3 使用JNDI ConnectionFactory](IV. Spring Boot features/32.1.3 Using a JNDI ConnectionFactory.md) - * [32.1.4 发送消息](IV. Spring Boot features/32.1.4 Sending a message.md) - * [32.1.5 接收消息](IV. Spring Boot features/32.1.5 Receiving a message.md) - * [32.2 AMQP](IV. Spring Boot features/32.2 AMQP.md) - * [32.2.1 RabbitMQ支持](IV. Spring Boot features/32.2.1 RabbitMQ support.md) - * [32.2.2 发送消息](IV. Spring Boot features/32.2.2 Sending a message.md) - * [32.2.3 接收消息](IV. Spring Boot features/32.2.3 Receiving a message.md) - * [32.3 Apache Kafka支持](IV. Spring Boot features/32.3 Apache Kafka Support.md) - * [32.3.1 发送消息](IV. Spring Boot features/32.3.1 Sending a Message.md) - * [32.3.2 接收消息](IV. Spring Boot features/32.3.2 Receiving a Message.md) - * [32.3.3 其它的Kafka属性](IV. Spring Boot features/32.3.3 Additional Kafka Properties.md) - * [33. 调用REST服务](IV. Spring Boot features/33. Calling REST services.md) - * [33.1 自定义RestTemplate](IV. Spring Boot features/33.1 RestTemplate customization.md) - * [34. 验证](IV. Spring Boot features/34. Validation.md) - * [35. 发送邮件](IV. Spring Boot features/35. Sending email.md) - * [36. 使用JTA处理分布式事务](IV. Spring Boot features/36. Distributed Transactions with JTA.md) - * [36.1 使用Atomikos事务管理器](IV. Spring Boot features/36.1 Using an Atomikos transaction manager.md) - * [36.2 使用Bitronix事务管理器](IV. Spring Boot features/36.2 Using a Bitronix transaction manager.md) - * [36.3 使用Narayana事务管理器](IV. Spring Boot features/36.3 Using a Narayana transaction manager.md) - * [36.4 使用J2EE管理的事务管理器](IV. Spring Boot features/36.4 Using a Java EE managed transaction manager.md) - * [36.5 混合XA和non-XA的JMS连接](IV. Spring Boot features/36.5 Mixing XA and non-XA JMS connections.md) - * [36.6 支持可替代的内嵌事务管理器](IV. Spring Boot features/36.6 Supporting an alternative embedded transaction manager.md) - * [37. Hazelcast](IV. Spring Boot features/37. Hazelcast.md) - * [38. Quartz调度器](IV. Spring Boot features/38. Quartz Scheduler.md) - * [39. Spring集成](IV. Spring Boot features/39. Spring Integration.md) - * [40. Spring Session](IV. Spring Boot features/40. Spring Session.md) - * [41. 基于JMX的监控和管理](IV. Spring Boot features/41. Monitoring and management over JMX.md) - * [42. 测试](IV. Spring Boot features/42. Testing.md) - * [42.1 测试作用域依赖](IV. Spring Boot features/42.1 Test scope dependencies.md) - * [42.2 测试Spring应用](IV. Spring Boot features/42.2 Testing Spring applications.md) - * [42.3 测试Spring Boot应用](IV. Spring Boot features/42.3 Testing Spring Boot applications.md) - * [42.3.1 发现测试配置](IV. Spring Boot features/42.3.1 Detecting test configuration.md) - * [42.3.2 排除测试配置](IV. Spring Boot features/42.3.2 Excluding test configuration.md) - * [42.3.3 使用随机端口](IV. Spring Boot features/42.3.3 Working with random ports.md) - * [42.3.4 模拟和监视beans](IV. Spring Boot features/42.3.4 Mocking and spying beans.md) - * [42.3.5 自动配置测试](IV. Spring Boot features/42.3.5 Auto-configured tests.md) - * [42.3.6 自动配置的JSON测试](IV. Spring Boot features/42.3.6 Auto-configured JSON tests.md) - * [42.3.7 自动配置的Spring MVC测试](IV. Spring Boot features/42.3.7 Auto-configured Spring MVC tests.md) - * [42.3.8 自动配置的Data JPA测试](IV. Spring Boot features/42.3.8 Auto-configured Data JPA tests.md) - * [42.3.9 自动配置的JDBC测试](IV. Spring Boot features/42.3.9 Auto-configured JDBC tests.md) - * [42.3.10 自动配置的jOOQ测试](IV. Spring Boot features/42.3.10 Auto-configured jOOQ tests.md) - * [42.3.11 自动配置的Data MongoDB测试](IV. Spring Boot features/42.3.11 Auto-configured Data MongoDB tests.md) - * [42.3.12 自动配置的Data Neo4j测试](IV. Spring Boot features/42.3.12 Auto-configured Data Neo4j tests.md) - * [42.3.13 自动配置的Data Redis测试](IV. Spring Boot features/42.3.13 Auto-configured Data Redis tests.md) - * [42.3.14 自动配置的Data LDAP测试](IV. Spring Boot features/42.3.14 Auto-configured Data LDAP tests.md) - * [42.3.15 自动配置的REST客户端](IV. Spring Boot features/42.3.15 Auto-configured REST clients.md) - * [42.3.16 自动配置的Spring REST Docs测试](IV. Spring Boot features/42.3.16 Auto-configured Spring REST Docs tests.md) - * [42.3.17 使用Spock测试Spring Boot应用](IV. Spring Boot features/42.3.17 Using Spock to test Spring Boot applications.md) - * [42.4 测试工具类](IV. Spring Boot features/42.4 Test utilities.md) - * [42.4.1 ConfigFileApplicationContextInitializer](IV. Spring Boot features/42.4.1 ConfigFileApplicationContextInitializer.md) - * [42.4.2 EnvironmentTestUtils](IV. Spring Boot features/42.4.2 EnvironmentTestUtils.md) - * [42.4.3 OutputCapture](IV. Spring Boot features/42.4.3 OutputCapture.md) - * [42.4.4 TestRestTemplate](IV. Spring Boot features/42.4.4 TestRestTemplate.md) - * [43. WebSockets](IV. Spring Boot features/43. WebSockets.md) - * [44. Web Services](IV. Spring Boot features/44. Web Services.md) - * [45. 创建自己的auto-configuration](IV. Spring Boot features/45. Creating your own auto-configuration.md) - * [45.1 理解自动配置的beans](IV. Spring Boot features/45.1 Understanding auto-configured beans.md) - * [45.2 定位自动配置候选者](IV. Spring Boot features/45.2 Locating auto-configuration candidates.md) - * [45.3 条件注解](IV. Spring Boot features/45.3 Condition annotations.md) - * [45.3.1 Class条件](IV. Spring Boot features/45.3.1 Class conditions.md) - * [45.3.2 Bean条件](IV. Spring Boot features/45.3.2 Bean conditions.md) - * [45.3.3 Property条件](IV. Spring Boot features/45.3.3 Property conditions.md) - * [45.3.4 Resource条件](IV. Spring Boot features/45.3.4 Resource conditions.md) - * [45.3.5 Web Application条件](IV. Spring Boot features/45.3.5 Web Application Conditions.md) - * [45.3.6 SpEL表达式条件](IV. Spring Boot features/45.3.6 SpEL expression conditions.md) - * [45.4 创建自己的starter](IV. Spring Boot features/45.4 Creating your own starter.md) - * [45.4.1 命名](IV. Spring Boot features/45.4.1 Naming.md) - * [45.4.2 自动配置模块](IV. Spring Boot features/45.4.2 Autoconfigure module.md) - * [45.4.3 Starter模块](IV. Spring Boot features/45.4.3 Starter module.md) - * [46. 接下来阅读什么](IV. Spring Boot features/46. What to read next.md) -* [V. Spring Boot执行器: Production-ready特性](V. Spring Boot Actuator/README.md) - * [47. 开启production-ready特性](V. Spring Boot Actuator/47. Enabling production-ready features.md) - * [48. 端点](V. Spring Boot Actuator/48. Endpoints.md) - * [48.1 自定义端点](V. Spring Boot Actuator/48.1 Customizing endpoints.md) - * [48.2 执行器MVC端点的超媒体支持](V. Spring Boot Actuator/48.2 Hypermedia for actuator MVC endpoints.md) - * [48.3 CORS支持](V. Spring Boot Actuator/48.3 CORS support.md) - * [48.4 添加自定义端点](V. Spring Boot Actuator/48.4 Adding custom endpoints.md) - * [48.5 健康信息](V. Spring Boot Actuator/48.5 Health information.md) - * [48.6 安全与HealthIndicators](V. Spring Boot Actuator/48.6 Security with HealthIndicators.md) - * [48.6.1 自动配置的HealthIndicators](V. Spring Boot Actuator/48.6.1 Auto-configured-HealthIndicators.md) - * [48.6.2 编写自定义HealthIndicators](V. Spring Boot Actuator/48.6.2 Writing custom HealthIndicators.md) - * [48.7 应用信息](V. Spring Boot Actuator/48.7 Application information.md) - * [48.7.1 自动配置的InfoContributors](V. Spring Boot Actuator/48.7.1 Auto-configured InfoContributors.md) - * [48.7.2 自定义应用info信息](V. Spring Boot Actuator/48.7.2 Custom application info information.md) - * [48.7.3 Git提交信息](V. Spring Boot Actuator/48.7.3 Git commit information.md) - * [48.7.4 构建信息](V. Spring Boot Actuator/48.7.4 Build information.md) - * [48.7.5 编写自定义的InfoContributors](V. Spring Boot Actuator/48.7.5 Writing custom InfoContributors.md) - * [49. 基于HTTP的监控和管理](V. Spring Boot Actuator/49. Monitoring and management over HTTP.md) - * [49.1 访问敏感端点](V. Spring Boot Actuator/49.1 Accessing sensitive endpoints.md) - * [49.2 自定义管理端点路径](V. Spring Boot Actuator/49.2 Customizing the management endpoint paths.md) - * [49.3 自定义管理服务器端口](V. Spring Boot Actuator/49.3 Customizing the management server port.md) - * [49.4 配置管理相关的SSL](V. Spring Boot Actuator/49.4 Configuring management-specific SSL.md) - * [49.5 自定义管理服务器地址](V. Spring Boot Actuator/49.5 Customizing the management server address.md) - * [49.6 禁用HTTP端点](V. Spring Boot Actuator/49.6 Disabling HTTP endpoints.md) - * [49.7 HTTP health端点访问限制](V. Spring Boot Actuator/49.7 HTTP Health endpoint access restrictions.md) - * [50. 基于JMX的监控和管理](V. Spring Boot Actuator/50. Monitoring and management over JMX.md) - * [50.1 自定义MBean名称](V. Spring Boot Actuator/50.1 Customizing MBean names.md) - * [50.2 禁用JMX端点](V. Spring Boot Actuator/50.2 Disabling JMX endpoints.md) - * [50.3 使用Jolokia通过HTTP实现JMX远程管理](V. Spring Boot Actuator/50.3 Using Jolokia for JMX over HTTP.md) - * [50.3.1 自定义Jolokia](V. Spring Boot Actuator/50.3.1 Customizing Jolokia.md) - * [50.3.2 禁用Jolokia](V. Spring Boot Actuator/50.3.2 Disabling Jolokia.md) - * [51. 记录器](V. Spring Boot Actuator/51. Loggers.md) - * [51.1 配置记录器](V. Spring Boot Actuator/51.1 Configure a Logger.md) - * [52. 度量指标](V. Spring Boot Actuator/52. Metrics.md) - * [52.1 系统指标](V. Spring Boot Actuator/52.1 System metrics.md) - * [52.2 数据源指标](V. Spring Boot Actuator/52.2 DataSource metrics.md) - * [52.3 缓存指标](V. Spring Boot Actuator/52.3 Cache metrics.md) - * [52.4 Tomcat session指标](V. Spring Boot Actuator/52.4 Tomcat session metrics.md) - * [52.5 记录自己的指标](V. Spring Boot Actuator/52.5 Recording your own metrics.md) - * [52.6 添加自己的公共指标](V. Spring Boot Actuator/52.6 Adding your own public metrics.md) - * [52.7 指标写入,导出和聚合](V. Spring Boot Actuator/52.7 Metric writers, exporters and aggregation.md) - * [52.7.1 示例: 导出到Redis](V. Spring Boot Actuator/52.7.1 Export to Redis.md) - * [52.7.2 示例: 导出到Open TSDB](V. Spring Boot Actuator/52.7.2 Export to Open TSDB.md) - * [52.7.3 示例: 导出到Statsd](V. Spring Boot Actuator/52.7.3 Export to Statsd.md) - * [52.7.4 示例: 导出到JMX](V. Spring Boot Actuator/52.7.4 Export to JMX.md) - * [52.8 聚合多个来源的指标](V. Spring Boot Actuator/52.8 Aggregating metrics from multiple sources.md) - * [52.9 Dropwizard指标](V. Spring Boot Actuator/52.9 Dropwizard Metrics.md) - * [52.10 消息渠道集成](V. Spring Boot Actuator/52.10 Message channel integration.md) - * [53. 审计](V. Spring Boot Actuator/53. Auditing.md) - * [54. 追踪](V. Spring Boot Actuator/54. Tracing.md) - * [54.1 自定义追踪](V. Spring Boot Actuator/54.1 Custom tracing.md) - * [55. 进程监控](V. Spring Boot Actuator/55. Process monitoring.md) - * [55.1 扩展配置](V. Spring Boot Actuator/55.1 Extend configuration.md) - * [55.2 以编程方式](V. Spring Boot Actuator/55.2 Programmatically.md) - * [56. Cloud Foundry支持](V. Spring Boot Actuator/56. Cloud Foundry support.md) - * [56.1 禁用扩展的Cloud Foundry执行器支持](V. Spring Boot Actuator/56.1 Disabling extended Cloud Foundry actuator support.md) - * [56.2 Cloud Foundry自签名证书](V. Spring Boot Actuator/56.2 Cloud Foundry self signed certificates.md) - * [56.3 自定义安全配置](V. Spring Boot Actuator/56.3 Custom security configuration.md) - * [57. 接下来阅读什么](V. Spring Boot Actuator/57. What to read next.md) -* [VI. 部署到云端](VI. Deploying Spring Boot applications/README.md) - * [58. 部署到云端](VI. Deploying Spring Boot applications/58. Deploying to the cloud.md) - * [58.1 Cloud Foundry](VI. Deploying Spring Boot applications/58.1 Cloud Foundry.md) - * [58.1.1 绑定服务](VI. Deploying Spring Boot applications/58.1.1 Binding to services.md) - * [58.2 Heroku](VI. Deploying Spring Boot applications/58.2 Heroku.md) - * [58.3 Openshift](VI. Deploying Spring Boot applications/58.3 Openshift.md) - * [58.4 亚马逊网络服务(AWS)](VI. Deploying Spring Boot applications/58.4 Amazon Web Services(AWS).md) - * [58.4.1 AWS Elastic Beanstalk](VI. Deploying Spring Boot applications/58.4.1 AWS Elastic Beanstalk.md) - * [58.4.2 总结](VI. Deploying Spring Boot applications/58.4.2 Summary.md) - * [58.5 Boxfuse和亚马逊网络服务](VI. Deploying Spring Boot applications/58.5 Boxfuse and Amazon Web Services.md) - * [58.6 Google App Engine](VI. Deploying Spring Boot applications/58.6 Google App Engine.md) - * [59. 安装Spring Boot应用](VI. Deploying Spring Boot applications/59. Installing Spring Boot applications.md) - * [59.1 支持的操作系统](VI. Deploying Spring Boot applications/59.1 Supported operating systems.md) - * [59.2 Unix/Linux服务](VI. Deploying Spring Boot applications/59.2 Unix&Linux services.md) - * [59.2.1 安装为init.d服务(System V)](VI. Deploying Spring Boot applications/59.2.1 Installation as an init.d service(System V).md) - * [59.2.2 安装为Systemd服务](VI. Deploying Spring Boot applications/59.2.2 Installation as a systemd service.md) - * [59.2.3 自定义启动脚本](VI. Deploying Spring Boot applications/59.2.3 Customizing the startup script.md) - * [59.3 Microsoft Windows服务](VI. Deploying Spring Boot applications/59.3 Microsoft Windows services.md) - * [60. 接下来阅读什么](VI. Deploying Spring Boot applications/60. What to read next.md) -* [VII. Spring Boot CLI](VII. Spring Boot CLI/README.md) - * [61. 安装CLI](VII. Spring Boot CLI/61. Installing the CLI.md) - * [62. 使用CLI](VII. Spring Boot CLI/62. Using the CLI.md) - * [62.1 使用CLI运行应用](VII. Spring Boot CLI/62.1. Running applications using the CLI.md) - * [62.1.1 推断"grab"依赖](VII. Spring Boot CLI/62.1.1 Deduced “grab” dependencies.md) - * [62.1.2 推断"grab"坐标](VII. Spring Boot CLI/62.1.2 Deduced “grab” coordinates.md) - * [62.1.3 默认import语句](VII. Spring Boot CLI/62.1.3 Default import statements.md) - * [62.1.4 自动创建main方法](VII. Spring Boot CLI/62.1.4 Automatic main method.md) - * [62.1.5 自定义依赖管理](VII. Spring Boot CLI/62.1.5 Custom dependency management.md) - * [62.2 多源文件应用](VII. Spring Boot CLI/62.2 Applications with multiple source files.md) - * [62.3 应用打包](VII. Spring Boot CLI/62.3 Packaging your application.md) - * [62.4 初始化新工程](VII. Spring Boot CLI/62.4 Initialize a new project.md) - * [62.5 使用内嵌shell](VII. Spring Boot CLI/62.5 Using the embedded shell.md) - * [62.6 为CLI添加扩展](VII. Spring Boot CLI/62.6 Adding extensions to the CLI.md) - * [63. 使用Groovy beans DSL开发应用](VII. Spring Boot CLI/63. Developing application with the Groovy beans DSL.md) - * [64. 使用settings.xml配置CLI](VII. Spring Boot CLI/64. Configuring the CLI with settings.xml.md) - * [65. 接下来阅读什么](VII. Spring Boot CLI/65. What to read next.md) -* [VIII. 构建工具插件](VIII. Build tool plugins/README.md) - * [66. Spring Boot Maven插件](VIII. Build tool plugins/66. Spring Boot Maven plugin.md) - * [66.1 包含该插件](VIII. Build tool plugins/66.1 Including the plugin.md) - * [66.2 打包可执行jar和war文件](VIII. Build tool plugins/66.2 Packaging executable jar and war files.md) - * [67. Spring Boot Gradle插件](VIII. Build tool plugins/67. Spring Boot Gradle plugin.md) - * [68. Spring Boot AntLib模块](VIII. Build tool plugins/68. Spring Boot AntLib module.md) - * [68.1. Spring Boot Ant任务](VIII. Build tool plugins/68.1. Spring Boot Ant tasks.md) - * [68.1.1. spring-boot:exejar](VIII. Build tool plugins/68.1.1. spring-boot:exejar.md) - * [68.1.2. 示例](VIII. Build tool plugins/68.1.2. Examples.md) - * [68.2. spring-boot:findmainclass](VIII. Build tool plugins/68.2. spring-boot:findmainclass.md) - * [68.2.1. 示例](VIII. Build tool plugins/68.2.1. Examples.md) -   * [69. 对其他构建系统的支持](VIII. Build tool plugins/69. Supporting other build systems.md) - * [69.1. 重新打包存档](VIII. Build tool plugins/69.1. Repackaging archives.md) - * [69.2. 内嵌库](VIII. Build tool plugins/69.2.Nested libraries.md) - * [69.3. 查找main类](VIII. Build tool plugins/69.3. Finding a main class.md) - * [69.4. repackage实现示例](VIII. Build tool plugins/69.4. Example repackage implementation.md) - * [70. 接下来阅读什么](VIII. Build tool plugins/70. What to read next.md) -* [IX. How-to指南](IX. ‘How-to’ guides/README.md) - * [71. Spring Boot应用](IX. ‘How-to’ guides/71. Spring Boot application.md) - * [71.1 创建自己的FailureAnalyzer](IX. ‘How-to’ guides/71.1 Create your own FailureAnalyzer.md) - * [71.2 解决自动配置问题](IX. ‘How-to’ guides/71.2 Troubleshoot auto-configuration.md) - * [71.3 启动前自定义Environment或ApplicationContext](IX. ‘How-to’ guides/71.3 Customize the Environment or ApplicationContext before it starts.md) - * [71.4 构建ApplicationContext层次结构](IX. ‘How-to’ guides/71.4 Build an ApplicationContext hierarchy(adding a parent or root context).md) - * [71.5 创建no-web应用](IX. ‘How-to’ guides/71.5 Create a non-web application.md) - * [72. 属性&配置](IX. ‘How-to’ guides/72. Properties & configuration.md) - * [72.1. 运行时暴露属性](IX. ‘How-to’ guides/72.1. Automatically expand properties at build time.md) - * [72.1.1. 使用Maven自动暴露属性](IX. ‘How-to’ guides/72.1.1. Automatic property expansion using Maven.md) - * [72.1.2. 使用Gradle自动暴露属性](IX. ‘How-to’ guides/72.1.2. Automatic property expansion using Gradle.md) - * [72.2. 外部化SpringApplication配置](IX. ‘How-to’ guides/72.2. Externalize the configuration of SpringApplication.md) - * [72.3 改变应用程序外部配置文件的位置](IX. ‘How-to’ guides/72.3 Change the location of external properties of an application.md) - * [72.4 使用'short'命令行参数](IX. ‘How-to’ guides/72.4 Use ‘short’ command line arguments.md) - * [72.5 使用YAML配置外部属性](IX. ‘How-to’ guides/72.5 Use YAML for external properties.md) - * [72.6 设置生效的Spring profiles](IX. ‘How-to’ guides/72.6 Set the active Spring profiles.md) - * [72.7 根据环境改变配置](IX. ‘How-to’ guides/72.7 Change configuration depending on the environment.md) - * [72.8 发现外部属性的内置选项](IX. ‘How-to’ guides/72.8 Discover built-in options for external properties.md) - * [73. 内嵌servlet容器](IX. ‘How-to’ guides/73. Embedded servlet containers.md) - * [73.1 为应用添加Servlet,Filter或Listener](IX. ‘How-to’ guides/73.1 Add a Servlet, Filter or ServletContextListener to an application.md) - * [73.1.1 使用Spring bean添加Servlet, Filter或Listener](IX. ‘How-to’ guides/73.1.1 Add a Servlet, Filter or Listener using a Spring bean.md) - * [73.1.2 使用classpath扫描添加Servlets, Filters和Listeners](IX. ‘How-to’ guides/73.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md) - * [73.2 改变HTTP端口](IX. ‘How-to’ guides/73.2 Change the HTTP port.md) - * [73.3 使用随机未分配的HTTP端口](IX. ‘How-to’ guides/73.3 Use a random unassigned HTTP port.md) - * [73.4 发现运行时的HTTP端口](IX. ‘How-to’ guides/73.4 Discover the HTTP port at runtime.md) - * [73.5 配置SSL](IX. ‘How-to’ guides/73.5 Configure SSL.md) - * [73.6 配置访问日志](IX. ‘How-to’ guides/73.6 Configure Access Logging.md) - * [73.7 在前端代理服务器后使用](IX. ‘How-to’ guides/73.7 Use behind a front-end proxy server.md) - * [73.7.1 自定义Tomcat代理配置](IX. ‘How-to’ guides/73.7.1 Customize Tomcat’s proxy configuration.md) - * [73.8 配置Tomcat](IX. ‘How-to’ guides/73.8 Configure Tomcat.md) - * [73.9 启用Tomcat的多连接器](IX. ‘How-to’ guides/73.9 Enable Multiple Connectors with Tomcat.md) - * [73.10 使用Tomcat的LegacyCookieProcessor](IX. ‘How-to’ guides/73.10 Use Tomcat’s LegacyCookieProcessor.md) - * [73.11 使用Jetty替代Tomcat](IX. ‘How-to’ guides/73.11 Use Jetty instead of Tomcat.md) - * [73.12 配置Jetty](IX. ‘How-to’ guides/73.12 Configure Jetty.md) - * [73.13 使用Undertow替代Tomcat](IX. ‘How-to’ guides/73.13 Use Undertow instead of Tomcat.md) - * [73.14 配置Undertow](IX. ‘How-to’ guides/73.14 Configure Undertow.md) - * [73.15 启用Undertow的多监听器](IX. ‘How-to’ guides/73.15 Enable Multiple Listeners with Undertow.md) - * [73.16 使用@ServerEndpoint创建WebSocket端点](IX. ‘How-to’ guides/73.16 Create WebSocket endpoints using @ServerEndpoint.md) - * [73.17 启用HTTP响应压缩](IX. ‘How-to’ guides/73.17 Enable HTTP response compression.md) - * [74. Spring MVC](IX. ‘How-to’ guides/74. Spring MVC.md) - * [74.1 编写JSON REST服务](IX. ‘How-to’ guides/74.1 Write a JSON REST service.md) - * [74.2 编写XML REST服务](IX. ‘How-to’ guides/74.2 Write an XML REST service.md) - * [74.3 自定义Jackson ObjectMapper](IX. ‘How-to’ guides/74.3 Customize the Jackson ObjectMapper.md) - * [74.4 自定义@ResponseBody渲染](IX. ‘How-to’ guides/74.4 Customize the @ResponseBody rendering.md) - * [74.5 处理Multipart文件上传](IX. ‘How-to’ guides/74.5 Handling Multipart File Uploads.md) - * [74.6 关闭Spring MVC DispatcherServlet](IX. ‘How-to’ guides/74.6 Switch off the Spring MVC DispatcherServlet.md) - * [74.7 关闭默认的MVC配置](IX. ‘How-to’ guides/74.7 Switch off the Default MVC configuration.md) - * [74.8 自定义ViewResolvers](IX. ‘How-to’ guides/74.8 Customize ViewResolvers.md) - * [75. HTTP客户端](IX. ‘How-to’ guides/75. HTTP clients.md) - * [75.1 配置RestTemplate使用代理](IX. ‘How-to’ guides/75.1 Configure RestTemplate to use a proxy.md) - * [76. 日志](IX. ‘How-to’ guides/76. Logging.md) - * [76.1 配置Logback](IX. ‘How-to’ guides/76.1 Configure Logback for logging.md) - * [76.1.1 配置logback只输出到文件](IX. ‘How-to’ guides/76.1.1 Configure logback for file only output.md) - * [76.2 配置Log4j](IX. ‘How-to’ guides/76.2 Configure Log4j for logging.md) - * [76.2.1 使用YAML或JSON配置Log4j2](IX. ‘How-to’ guides/76.2.1 Use YAML or JSON to configure Log4j 2.md) - * [77. 数据访问](IX. ‘How-to’ guides/77. Data Access.md) - * [77.1 配置自定义的数据源](IX. ‘How-to’ guides/77.1 Configure a custom DataSource.md) - * [77.2 配置两个数据源](IX. ‘How-to’ guides/77.2 Configure Two DataSources.md) - * [77.3 使用Spring Data仓库](IX. ‘How-to’ guides/77.3 Use Spring Data repositories.md) - * [77.4 从Spring配置分离@Entity定义](IX. ‘How-to’ guides/77.4 Separate @Entity definitions from Spring configuration.md) - * [77.5 配置JPA属性](IX. ‘How-to’ guides/77.5 Configure JPA properties.md) - * [77.6 配置Hibernate命名策略](IX. ‘How-to’ guides/77.6 Configure Hibernate Naming Strategy.md) - * [77.7 使用自定义EntityManagerFactory](IX. ‘How-to’ guides/77.7 Use a custom EntityManagerFactory.md) - * [77.8 使用两个EntityManagers](IX. ‘How-to’ guides/77.8 Use Two EntityManagers.md) - * [77.9 使用普通的persistence.xml](IX. ‘How-to’ guides/77.9 Use a traditional persistence.xml.md) - * [77.10 使用Spring Data JPA和Mongo仓库](IX. ‘How-to’ guides/77.10 Use Spring Data JPA and Mongo repositories.md) - * [77.11 将Spring Data仓库暴露为REST端点](IX. ‘How-to’ guides/77.11 Expose Spring Data repositories as REST endpoint.md) - * [77.12 配置JPA使用的组件](IX. ‘How-to’ guides/77.12 Configure a component that is used by JPA.md) - * [78. 数据库初始化](IX. ‘How-to’ guides/78. Database initialization.md) - * [78.1 使用JPA初始化数据库](IX. ‘How-to’ guides/78.1 Initialize a database using JPA.md) - * [78.2 使用Hibernate初始化数据库](IX. ‘How-to’ guides/78.2 Initialize a database using Hibernate.md) - * [78.3 使用Spring JDBC初始化数据库](IX. ‘How-to’ guides/78.3 Initialize a database using Spring JDBC.md) - * [78.4 初始化Spring Batch数据库](IX. ‘How-to’ guides/78.4 Initialize a Spring Batch database.md) - * [78.5 使用高级数据迁移工具](IX. ‘How-to’ guides/78.5 Use a higher level database migration tool.md) - * [78.5.1 启动时执行Flyway数据库迁移](IX. ‘How-to’ guides/78.5.1 Execute Flyway database migrations on startup.md) - * [78.5.2 启动时执行Liquibase数据库迁移](IX. ‘How-to’ guides/78.5.2 Execute Liquibase database migrations on startup.md) - * [79. 消息传送](IX. ‘How-to’ guides/79. Messaging.md) - * [79.1 禁用事务JMS会话](IX. ‘How-to’ guides/79.1 Disable transacted JMS session.md) - * [80. 批处理应用](IX. ‘How-to’ guides/80. Batch applications.md) - * [80.1 在启动时执行Spring Batch作业](IX. ‘How-to’ guides/80.1 Execute Spring Batch jobs on startup.md) - * [81. 执行器](IX. ‘How-to’ guides/81. Actuator.md) - * [81.1 改变HTTP端口或执行器端点的地址](IX. ‘How-to’ guides/81.1 Change the HTTP port or address of the actuator endpoints.md) - * [81.2 自定义WhiteLabel错误页面](IX. ‘How-to’ guides/81.2 Customize the ‘whitelabel’ error page.md) - * [81.3 Actuator和Jersey](IX. ‘How-to’ guides/81.3 Actuator and Jersey.md) - * [82. 安全](IX. ‘How-to’ guides/82. Security.md) - * [82.1 关闭Spring Boot安全配置](IX. ‘How-to’ guides/82.1 Switch off the Spring Boot security configuration.md) - * [82.2 改变AuthenticationManager并添加用户账号](IX. ‘How-to’ guides/82.2 Change the AuthenticationManager and add user accounts.md) - * [82.3 当前端使用代理服务器时启用HTTPS](IX. ‘How-to’ guides/82.3 Enable HTTPS when running behind a proxy server.md) - * [83. 热交换](IX. ‘How-to’ guides/83. Hot swapping.md) - * [83.1 重新加载静态内容](IX. ‘How-to’ guides/83.1 Reload static content.md) - * [83.2. 在不重启容器的情况下重新加载模板](IX. ‘How-to’ guides/83.2. Reload templates without restarting the container.md) - * [83.2.1 Thymeleaf模板](IX. ‘How-to’ guides/83.2.1 Thymeleaf templates.md) - * [83.2.2 FreeMarker模板](IX. ‘How-to’ guides/83.2.2 FreeMarker templates.md) - * [83.2.3 Groovy模板](IX. ‘How-to’ guides/83.2.3 Groovy templates.md) - * [83.3 应用快速重启](IX. ‘How-to’ guides/83.3 Fast application restarts.md) - * [83.4 在不重启容器的情况下重新加载Java类](IX. ‘How-to’ guides/83.4 Reload Java classes without restarting the container.md) - * [84. 构建](IX. ‘How-to’ guides/84. Build.md) - * [84.1 生成构建信息](IX. ‘How-to’ guides/84.1 Generate build information.md) - * [84.2 生成Git信息](IX. ‘How-to’ guides/84.2 Generate git information.md) - * [84.3 自定义依赖版本](IX. ‘How-to’ guides/84.3 Customize dependency versions.md) - * [84.4 使用Maven创建可执行JAR](IX. ‘How-to’ guides/84.4 Create an executable JAR with Maven.md) - * [84.5 将Spring Boot应用作为依赖](IX. ‘How-to’ guides/84.5 Use a Spring Boot application as a dependency.md) - * [84.6 在可执行jar运行时提取特定的版本](IX. ‘How-to’ guides/84.6 Extract specific libraries when an executable jar runs.md) - * [84.7 使用排除创建不可执行的JAR](IX. ‘How-to’ guides/84.7 Create a non-executable JAR with exclusions.md) - * [84.8 远程调试使用Maven启动的Spring Boot项目](IX. ‘How-to’ guides/84.8 Remote debug a Spring Boot application started with Maven.md) - * [84.9 使用Ant构建可执行存档(不使用spring-boot-antlib)](IX. ‘How-to’ guides/84.9 Build an executable archive from Ant without using spring-boot-antlib.md) - * [85. 传统部署](IX. ‘How-to’ guides/85. Traditional deployment.md) - * [85.1 创建可部署的war文件](IX. ‘How-to’ guides/85.1 Create a deployable war file.md) - * [85.2 为老的servlet容器创建可部署的war文件](IX. ‘How-to’ guides/85.2 Create a deployable war file for older servlet containers.md) - * [85.3 将现有的应用转换为Spring Boot](IX. ‘How-to’ guides/85.3 Convert an existing application to Spring Boot.md) - * [85.4 部署WAR到Weblogic](IX. ‘How-to’ guides/85.4 Deploying a WAR to Weblogic.md) - * [85.5 部署WAR到老的(Servlet2.5)容器](IX. ‘How-to’ guides/85.5 Deploying a WAR in an Old(Servlet 2.5)Container.md) - * [85.6 使用Lettuce来代替Jedis](IX. ‘How-to’ guides/85.6 Use Lettuce instead of Jedis.md) -* [X.附录](X. Appendices/README.md) - * [附录A. 常见应用属性](X. Appendices/A. Common application properties.md) - * [附录B. 配置元数据](X. Appendices/B. Configuration meta-data.md) - * [附录B.1. 元数据格式](X. Appendices/B.1. Meta-data format.md) - * [附录B.1.1. Group属性](X. Appendices/B.1.1. Group Attributes.md) - * [附录B.1.2. Property属性](X. Appendices/B.1.2. Property Attributes.md) - * [附录B.1.3. Hint属性](X. Appendices/B.1.3 Hint Attributes.md) - * [附录B.1.4. 可重复的元数据节点](X. Appendices/B.1.4. Repeated meta-data items.md) - * [附录B.2. 提供人工提示](X. Appendices/B.2 Providing manual hints.md) - * [附录 B.2.1 值提示](X. Appendices/B.2.1 Value hint.md) - * [附录 B.2.2 值提供者](X. Appendices/B.2.2 Value provider.md) - * [附录B.3. 使用注解处理器产生自己的元数据](X. Appendices/B.3. Generating your own meta-data using the annotation processor.md) - * [附录 B.3.1. 内嵌属性](X. Appendices/B.3.1. Nested properties.md) - * [附录 B.3.2. 添加其他的元数据](X. Appendices/B.3.2. Adding additional meta-data.md) - * [附录C. 自动配置类](X. Appendices/C. Auto-configuration classes.md) - * [附录 C.1. 来自spring-boot-autoconfigure模块](X. Appendices/C.1. From the “spring-boot-autoconfigure” module.md) - * [附录C.2. 来自spring-boot-actuator模块](X. Appendices/C.2. From the “spring-boot-actuator” module.md) - * [附录D. 测试自动配置的标注](X. Appendices/D. Test auto-configuration annotations.md) - * [附录E. 可执行jar格式](X. Appendices/E. The executable jar format.md) - * [附录E.1. 内嵌JARs](X. Appendices/E.1. Nested JARs.md) - * [附录E.1.1. 可执行jar文件结构](X. Appendices/E.1.1. The executable jar file structure.md) - * [附录E.1.2. 可执行war文件结构](X. Appendices/E.1.2. The executable war file structure.md) - * [附录E.2. Spring Boot的"JarFile"类](X. Appendices/E.2. Spring Boot’s “JarFile” class.md) - * [附录E.2.1. 对标准Java "JarFile"的兼容性](X. Appendices/E.2.1. Compatibility with the standard Java “JarFile”.md) - * [附录E.3. 启动可执行jars](X. Appendices/E.3. Launching executable jars.md) - * [附录E.3.1 Launcher manifest](X. Appendices/E.3.1. Launcher manifest.md) - * [附录E.3.2. 暴露的存档](X. Appendices/E.3.2. Exploded archives.md) - * [附录E.4. PropertiesLauncher特性](X. Appendices/E.4. PropertiesLauncher Features.md) - * [附录E.5. 可执行jar的限制](X. Appendices/E.5. Executable jar restrictions.md) - * [附录E.5.1. Zip实体压缩](X. Appendices/E.5.1. Zip entry compression.md) - * [附录E.5.2. 系统ClassLoader](X. Appendices/E.5.2. System ClassLoader.md) - * [附录E.6. 可替代的单一jar解决方案](X. Appendices/E.6. Alternative single jar solutions.md) - * [附录F. 依赖版本](X. Appendices/F. Dependency versions.md) +# Summary + +* [I. Spring Boot文档](I. Spring Boot Documentation/README.md) + * [1. 关于本文档](I. Spring Boot Documentation/1. About the Documentation.md) + * [2. 获取帮助](I. Spring Boot Documentation/2. Getting Help.md) + * [3. 第一步](I. Spring Boot Documentation/3. First Steps.md) + * [4. 使用Spring Boot](I. Spring Boot Documentation/4. Working with Spring Boot.md) + * [5. 了解Spring Boot特性](I. Spring Boot Documentation/5. Learning about Spring Boot Features.md) + * [6. 迁移到生产环境](I. Spring Boot Documentation/6. Moving to Production.md) + * [7. 高级主题](I. Spring Boot Documentation/7. Advanced Topics.md) +* [II. 开始](II. Getting Started/README.md) + * [8. Spring Boot介绍](II. Getting Started/8. Introducing Spring Boot.md) + * [9. 系统要求](II. Getting Started/9. System Requirements.md) + * [9.1. Servlet容器](II. Getting Started/9.1. Servlet Containers.md) + * [10. Spring Boot安装](II. Getting Started/10. Installing Spring Boot.md) + * [10.1. 为Java开发者准备的安装指南](II. Getting Started/10.1. Installation Instructions for the Java Developer.md) + * [10.1.1. Maven安装](II. Getting Started/10.1.1. Maven Installation.md) + * [10.1.2. Gradle安装](II. Getting Started/10.1.2. Gradle Installation.md) + * [10.2. Spring Boot CLI安装](II. Getting Started/10.2. Installing the Spring Boot CLI.md) + * [10.2.1. 手动安装](II. Getting Started/10.2.1. Manual Installation.md) + * [10.2.2. 使用SDKMAN进行安装](II. Getting Started/10.2.2. Installation with SDKMAN.md) + * [10.2.3. 使用OSX Homebrew进行安装](II. Getting Started/10.2.3. OSX Homebrew Installation.md) + * [10.2.4. 使用MacPorts进行安装](II. Getting Started/10.2.4. MacPorts Installation.md) + * [10.2.5. 命令行实现](II. Getting Started/10.2.5. Command-line Completion.md) + * [10.2.6. Spring CLI示例快速入门](II. Getting Started/10.2.6. Quick-start Spring CLI Example.md) + * [10.3. 从Spring Boot早期版本升级](II. Getting Started/10.3. Upgrading from an Earlier Version of Spring Boot.md) + * [11. 开发你的第一个Spring Boot应用](II. Getting Started/11. Developing Your First Spring Boot Application.md) + * [11.1. 创建POM](II. Getting Started/11.1. Creating the POM.md) + * [11.2. 添加classpath依赖](II. Getting Started/11.2. Adding Classpath Dependencies.md) + * [11.3. 编写代码](II. Getting Started/11.3. Writing the Code.md) + * [11.3.1. @RestController和@RequestMapping注解](II. Getting Started/11.3.1. The @RestController and @RequestMapping Annotations.md) + * [11.3.2. @EnableAutoConfiguration注解](II. Getting Started/11.3.2. The @EnableAutoConfiguration Annotation.md) + * [11.3.3. main方法](II. Getting Started/11.3.3. The “main” Method.md) + * [11.4. 运行示例](II. Getting Started/11.4. Running the Example.md) + * [11.5. 创建一个可执行jar](II. Getting Started/11.5. Creating an Executable Jar.md) + * [12. 接下来阅读什么](II. Getting Started/12. What to Read Next.md) +* [III. 使用Spring Boot](III. Using Spring Boot/README.md) + * [13. 构建系统](III. Using Spring Boot/13. Build Systems.md) + * [13.1. 依赖管理](III. Using Spring Boot/13.1. Dependency Management.md) + * [13.2. Maven](III. Using Spring Boot/13.2. Maven.md) + * [13.2.1. 继承starter parent](III. Using Spring Boot/13.2.1. Inheriting the Starter Parent.md) + * [13.2.2. 在不使用parent POM的情况下玩转Spring Boot](III. Using Spring Boot/13.2.2. Using Spring Boot without the Parent POM.md) + * [13.2.3. 使用Spring Boot Maven插件](III. Using Spring Boot/13.2.3. Using the Spring Boot Maven Plugin.md) + * [13.3. Gradle](III. Using Spring Boot/13.3. Gradle.md) + * [13.4. Ant](III. Using Spring Boot/13.4. Ant.md) + * [13.5. Starters](III. Using Spring Boot/13.5. Starters.md) + * [14. 组织你的代码](III. Using Spring Boot/14. Structuring Your Code.md) + * [14.1. 使用"default"包](III. Using Spring Boot/14.1. Using the “default” Package.md) + * [14.2. 放置应用的main类](III. Using Spring Boot/14.2. Locating the Main Application Class.md) +   * [15. 配置类](III. Using Spring Boot/15. Configuration Classes.md) + * [15.1. 导入其他配置类](III. Using Spring Boot/15.1. Importing Additional Configuration Classes.md) + * [15.2. 导入XML配置](III. Using Spring Boot/15.2. Importing XML Configuration.md) + * [16. 自动配置](III. Using Spring Boot/16. Auto-configuration.md) + * [16.1. 逐步替换自动配置](III. Using Spring Boot/16.1. Gradually Replacing Auto-configuration.md) +      * [16.2. 禁用特定的自动配置类](III. Using Spring Boot/16.2. Disabling Specific Auto-configuration Classes.md) +   * [17. Spring Beans和依赖注入](III. Using Spring Boot/17. Spring Beans and Dependency Injection.md) + * [18. 使用@SpringBootApplication注解](III. Using Spring Boot/18. Using the @SpringBootApplication Annotation.md) + * [19. 运行应用程序](III. Using Spring Boot/19. Running Your Application.md) + * [19.1. 从IDE中运行](III. Using Spring Boot/19.1. Running from an IDE.md) + * [19.2. 作为一个打包后的应用运行](III. Using Spring Boot/19.2. Running as a Packaged Application.md) + * [19.3. 使用Maven插件运行](III. Using Spring Boot/19.3. Using the Maven Plugin.md) + * [19.4. 使用Gradle插件运行](III. Using Spring Boot/19.4. Using the Gradle Plugin.md) + * [19.5. 热交换](III. Using Spring Boot/19.5. Hot Swapping.md) + * [20. 开发者工具](III. Using Spring Boot/20. Developer Tools.md) + * [20.1. 默认属性](III. Using Spring Boot/20.1. Property Defaults.md) + * [20.2. 自动重启](III. Using Spring Boot/20.2. Automatic Restart.md) + * [20.2.1. 在状况评估里记录更改](III. Using Spring Boot/20.2.1. Logging changes in condition evaluation.md) + * [20.2.2. 排除资源](III. Using Spring Boot/20.2.2. Excluding Resources.md) + * [20.2.3. 查看其他路径](III. Using Spring Boot/20.2.3. Watching Additional Paths.md) + * [20.2.4. 禁用重启](III. Using Spring Boot/20.2.4. Disabling Restart.md) + * [20.2.5. 使用触发器文件](III. Using Spring Boot/20.2.5. Using a Trigger File.md) + * [20.2.6. 自定义restart类加载器](III. Using Spring Boot/20.2.6. Customizing the Restart Classloader.md) + * [20.2.7. 已知限制](III. Using Spring Boot/20.2.7. Known Limitations.md) + * [20.3. LiveReload](III. Using Spring Boot/20.3. LiveReload.md) +      * [20.4. 全局设置](III. Using Spring Boot/20.4. Global Settings.md) + * [20.5. 远程应用](III. Using Spring Boot/20.5. Remote Applications.md) + * [20.5.1. 运行远程客户端应用](III. Using Spring Boot/20.5.1. Running the Remote Client Application.md) +         * [20.5.2. 远程更新](III. Using Spring Boot/20.5.2. Remote Update.md) + * [21. 打包用于生产的应用](III. Using Spring Boot/21. Packaging Your Application for Production.md) + * [22. 接下来阅读什么](III. Using Spring Boot/22. What to Read Next.md) +* [IV. Spring Boot特性](IV. Spring Boot features/README.md) + * [23. SpringApplication](IV. Spring Boot features/23. SpringApplication.md) + * [23.1. 启动失败](IV. Spring Boot features/23.1. Startup Failure.md) + * [23.2. 自定义Banner](IV. Spring Boot features/23.2. Customizing the Banner.md) + * [23.3. 自定义SpringApplication](IV. Spring Boot features/23.3. Customizing SpringApplication.md) + * [23.4. 流式构建API](IV. Spring Boot features/23.4. Fluent Builder API.md) + * [23.5. 应用事件和监听器](IV. Spring Boot features/23.5. Application Events and Listeners.md) +      * [23.6. Web环境](IV. Spring Boot features/23.6. Web Environment.md) + * [23.7. 访问应用参数](IV. Spring Boot features/23.7. Accessing Application Arguments.md) + * [23.8. 使用ApplicationRunner或CommandLineRunner](IV. Spring Boot features/23.8. Using the ApplicationRunner or CommandLineRunner.md) +      * [23.9. 应用退出](IV. Spring Boot features/23.9. Application Exit.md) + * [23.10. Admin特性](IV. Spring Boot features/23.10. Admin Features.md) + * [24.外化配置](IV. Spring Boot features/24. Externalized Configuration.md) +      * [24.1. 配置随机值](IV. Spring Boot features/24.1. Configuring Random Values.md) + * [24.2. 访问命令行属性](IV. Spring Boot features/24.2. Accessing Command Line Properties.md) + * [24.3. 应用属性文件](IV. Spring Boot features/24.3. Application Property Files.md) + * [24.4. Profile-specific属性](IV. Spring Boot features/24.4. Profile-specific Properties.md) + * [24.5. 属性占位符](IV. Spring Boot features/24.5. Placeholders in Properties.md) +      * [24.6. 使用YAML代替Properties](IV. Spring Boot features/24.6. Using YAML Instead of Properties.md) + * [24.6.1. 加载YAML](IV. Spring Boot features/24.6.1. Loading YAML.md) + * [24.6.2. 在Spring环境中使用YAML暴露属性](IV. Spring Boot features/24.6.2. Exposing YAML as Properties in the Spring Environment.md) +         * [24.6.3. Multi-profile YAML文档](IV. Spring Boot features/24.6.3. Multi-profile YAML Documents.md) +         * [24.6.4. YAML缺点](IV. Spring Boot features/24.6.4. YAML Shortcomings.md) +         * [24.6.5. 合并YAML列表](IV. Spring Boot features/24.6.5. Merging YAML Lists.md) + * [24.7. 类型安全的配置属性](IV. Spring Boot features/24.7. Type-safe Configuration Properties.md) +         * [24.7.1. 第三方配置](IV. Spring Boot features/24.7.1. Third-party Configuration.md) +         * [24.7.2. Relaxed绑定](IV. Spring Boot features/24.7.2. Relaxed Binding.md) +         * [24.7.3. 属性转换](IV. Spring Boot features/24.7.3. Properties Conversion.md) + * [24.7.4. @ConfigurationProperties校验](IV. Spring Boot features/24.7.4. @ConfigurationProperties Validation.md) + * [24.7.5. @ConfigurationProperties vs @Value](IV. Spring Boot features/24.7.5. @ConfigurationProperties vs. @Value.md) + * [25. Profiles](IV. Spring Boot features/25. Profiles.md) + * [25.1. 添加激活的profiles](IV. Spring Boot features/25.1. Adding Active Profiles.md) + * [25.2.以编程方式设置profiles](IV. Spring Boot features/25.2. Programmatically Setting Profiles.md) + * [25.3. Profile-specific配置文件](IV. Spring Boot features/25.3. Profile-specific Configuration Files.md) + * [26. 日志](IV. Spring Boot features/26. Logging.md) + * [26.1. 日志格式](IV. Spring Boot features/26.1. Log Format.md) + * [26.2. 控制台输出](IV. Spring Boot features/26.2. Console Output.md) + * [26.2.1. Color-coded输出](IV. Spring Boot features/26.2.1. Color-coded Output.md) + * [26.3. 文件输出](IV. Spring Boot features/26.3. File Output.md) + * [26.4. 日志级别](IV. Spring Boot features/26.4. Log Levels.md) + * [26.5. 自定义日志配置](IV. Spring Boot features/26.5. Custom Log Configuration.md) + * [26.6. Logback扩展](IV. Spring Boot features/26.6. Logback Extensions.md) + * [26.6.1. Profile-specific配置](IV. Spring Boot features/26.6.1. Profile-specific Configuration.md) + * [26.6.2. Environment属性](IV. Spring Boot features/26.6.2. Environment Properties.md) + * [27. 开发Web应用](IV. Spring Boot features/27. Developing Web Applications.md) + * [27.1. Spring Web MVC框架](IV. Spring Boot features/27.1. The “Spring Web MVC Framework”.md) + * [27.1.1. Spring MVC自动配置](IV. Spring Boot features/27.1.1. Spring MVC Auto-configuration.md) + * [27.1.2. HttpMessageConverters](IV. Spring Boot features/27.1.2. HttpMessageConverters.md) + * [27.1.3. 自定义JSON序列化器和反序列化器](IV. Spring Boot features/27.1.3. Custom JSON Serializers and Deserializers.md) + * [27.1.4. MessageCodesResolver](IV. Spring Boot features/27.1.4. MessageCodesResolver.md) + * [27.1.5. 静态内容](IV. Spring Boot features/27.1.5. Static Content.md) + * [27.1.6. 欢迎页](IV. Spring Boot features/27.1.6. Welcome Page.md) + * [27.1.7. 定制网站图标](IV. Spring Boot features/27.1.7. Custom Favicon.md) + * [27.1.8. 路径匹配与内容协商](IV. Spring Boot features/27.1.8. Path Matching and Content Negotiation.md) + * [27.1.9. ConfigurableWebBindingInitializer](IV. Spring Boot features/27.1.9. ConfigurableWebBindingInitializer.md) + * [27.1.10. 模板引擎](IV. Spring Boot features/27.1.10. Template Engines.md) + * [27.1.11. 错误处理](IV. Spring Boot features/27.1.11. Error Handling.md) + * [27.1.12. Spring HATEOAS](IV. Spring Boot features/27.1.12. Spring HATEOAS.md) + * [27.1.13. CORS支持](IV. Spring Boot features/27.1.13. CORS support.md) + * [27.2 Spring WebFlux框架](IV. Spring Boot features/27.2 The “Spring WebFlux Framework”.md) + * [27.2.1 Spring WebFlux自动配置](IV. Spring Boot features/27.2.1 Spring WebFlux Auto-configuration.md) + * [27.2.2 HTTP编解码器——HttpMessageReaders与HttpMessageWriters](IV. Spring Boot features/27.2.2 HTTP Codecs with HttpMessageReaders and HttpMessageWriters.md) + * [27.2.3 静态内容](IV. Spring Boot features/27.2.3 Static Content.md) + * [27.2.4 模板引擎](IV. Spring Boot features/27.2.4 Template Engines.md) + * [27.2.5 错误处理](IV. Spring Boot features/27.2.5 Error Handling.md) + * [27.2.6 网络过滤器](IV. Spring Boot features/27.2.6 Web Filters.md) + * [27.3. JAX-RS和Jersey](IV. Spring Boot features/27.3. JAX-RS and Jersey.md) + * [27.4 内嵌servlet容器支持](IV. Spring Boot features/27.4 Embedded Servlet Container Support.md) + * [27.4.1 Servlets、Filters和listeners](IV. Spring Boot features/27.4.1 Servlets, Filters, and listeners.md) + * [27.4.2 Servlet上下文初始化](IV. Spring Boot features/27.4.2 Servlet Context Initialization.md) + * [27.4.3 ServletWebServerApplicationContext](IV. Spring Boot features/27.4.3 The ServletWebServerApplicationContext.md) + * [27.4.4 自定义内嵌servlet容器](IV. Spring Boot features/27.4.4 Customizing Embedded Servlet Containers.md) + * [27.4.5 JSP的限制](IV. Spring Boot features/27.4.5 JSP Limitations.md) + * [28. 安全](IV. Spring Boot features/28. Security.md) + * [28.1 MVC安全](IV. Spring Boot features/28.1 MVC Security.md) + * [28.2 WebFlux安全](IV. Spring Boot features/28.2 WebFlux Security.md) + * [28.3 OAuth2](IV. Spring Boot features/28.3 OAuth2.md) + * [28.3.1 客户端](IV. Spring Boot features/28.3.1 Client.md) + * [28.4 执行器安全](IV. Spring Boot features/28.4 Actuator Security.md) + * [28.4.1 跨站请求伪造保护](IV. Spring Boot features/28.4.1 Cross Site Request Forgery Protection.md) + * [29. 使用SQL数据库](IV. Spring Boot features/29. Working with SQL Databases.md) + * [29.1. 配置数据源](IV. Spring Boot features/29.1. Configure a DataSource.md) + * [29.1.1. 对内嵌数据库的支持](IV. Spring Boot features/29.1.1. Embedded Database Support.md) + * [29.1.2. 连接生产环境数据库](IV. Spring Boot features/29.1.2. Connection to a Production Database.md) + * [29.1.3. 连接JNDI数据库](IV. Spring Boot features/29.1.3. Connection to a JNDI DataSource.md) + * [29.2. 使用JdbcTemplate](IV. Spring Boot features/29.2. Using JdbcTemplate.md) + * [29.3. JPA和Spring Data](IV. Spring Boot features/29.3. JPA and Spring Data.md) + * [29.3.1. 实体类](IV. Spring Boot features/29.3.1. Entity Classes.md) + * [29.3.2. Spring Data JPA仓库](IV. Spring Boot features/29.3.2. Spring Data JPA Repositories.md) + * [29.3.3. 创建和删除JPA数据库](IV. Spring Boot features/29.3.3. Creating and Dropping JPA Databases.md) + * [29.3.4. 在视图中打开实体管理器](IV. Spring Boot features/29.3.4. Open EntityManager in View.md) + * [29.4 使用H2的web控制台](IV. Spring Boot features/29.4 Using H2’s Web Console.md) + * [29.4.1 改变H2控制台路径](IV. Spring Boot features/29.4.1 Changing the H2 Console’s Path.md) + * [29.5 使用jOOQ](IV. Spring Boot features/29.5 Using jOOQ.md) + * [29.5.1 代码生成](IV. Spring Boot features/29.5.1 Code Generation.md) + * [29.5.2 使用DSLContext](IV. Spring Boot features/29.5.2 Using DSLContext.md) + * [29.5.3 jOOQ SQL方言](IV. Spring Boot features/29.5.3 jOOQ SQL Dialect.md) + * [29.5.4 自定义jOOQ](IV. Spring Boot features/29.5.4 Customizing jOOQ.md) + * [30. 使用NoSQL技术](IV. Spring Boot features/30. Working with NoSQL Technologies.md) + * [30.1. Redis](IV. Spring Boot features/30.1. Redis.md) + * [30.1.1. 连接Redis](IV. Spring Boot features/30.1.1. Connecting to Redis.md) + * [30.2. MongoDB](IV. Spring Boot features/30.2. MongoDB.md) + * [30.2.1. 连接MongoDB数据库](IV. Spring Boot features/30.2.1. Connecting to a MongoDB Database.md) + * [30.2.2. MongoDBTemplate](IV. Spring Boot features/30.2.2. MongoTemplate.md) + * [30.2.3. Spring Data MongoDB仓库](IV. Spring Boot features/30.2.3. Spring Data MongoDB Repositories.md) + * [30.2.4 内嵌的Mongo](IV. Spring Boot features/30.2.4 Embedded Mongo.md) + * [30.3 Neo4j](IV. Spring Boot features/30.3 Neo4j.md) + * [30.3.1 连接Neo4j数据库](IV. Spring Boot features/30.3.1 Connecting to a Neo4j Database.md) + * [30.3.2 使用内嵌模式](IV. Spring Boot features/30.3.2 Using the Embedded Mode.md) + * [30.3.3 Neo4jSession](IV. Spring Boot features/30.3.3 Neo4jSession.md) + * [30.3.4 Spring Data Neo4j仓库](IV. Spring Boot features/30.3.4 Spring Data Neo4j Repositories.md) + * [30.3.5 仓库示例](IV. Spring Boot features/30.3.5 Repository Example.md) + * [30.4 Gemfire](IV. Spring Boot features/30.4 Gemfire.md) + * [30.5 Solr](IV. Spring Boot features/30.5 Solr.md) + * [30.5.1 连接Solr](IV. Spring Boot features/30.5.1 Connecting to Solr.md) + * [30.5.2 Spring Data Solr仓库](IV. Spring Boot features/30.5.2 Spring Data Solr Repositories.md) + * [30.6 Elasticsearch](IV. Spring Boot features/30.6 Elasticsearch.md) + * [30.6.1 使用Jest连接Elasticsearch](IV. Spring Boot features/30.6.1 Connecting to Elasticsearch by Using Jest.md) + * [30.6.2 使用Spring Data连接Elasticsearch](IV. Spring Boot features/30.6.2 Connecting to Elasticsearch by Using Spring Data.md) + * [30.6.3 Spring Data Elasticseach仓库](IV. Spring Boot features/30.6.3 Spring Data Elasticsearch Repositories.md) + * [30.7 Cassandra](IV. Spring Boot features/30.7 Cassandra.md) + * [30.7.1 连接Cassandra](IV. Spring Boot features/30.7.1 Connecting to Cassandra.md) + * [30.7.2 Spring Data Cassandra仓库](IV. Spring Boot features/30.7.2 Spring Data Cassandra Repositories.md) + * [30.8 Couchbase](IV. Spring Boot features/30.8 Couchbase.md) + * [30.8.1 连接Couchbase](IV. Spring Boot features/30.8.1 Connecting to Couchbase.md) + * [30.8.2 Spring Data Couchbase仓库](IV. Spring Boot features/30.8.2 Spring Data Couchbase Repositories.md) + * [30.9 LDAP](IV. Spring Boot features/30.9 LDAP.md) + * [30.9.1 连接LDAP服务器](IV. Spring Boot features/30.9.1 Connecting to an LDAP Server.md) + * [30.9.2 Spring Data LDAP仓库](IV. Spring Boot features/30.9.2 Spring Data LDAP Repositories.md) + * [30.9.3 嵌入式内存中LDAP服务器](IV. Spring Boot features/30.9.3 Embedded In-memory LDAP Server.md) + * [30.10 InfluxDB](IV. Spring Boot features/30.10 InfluxDB.md) + * [30.10.1 连接InfluxDB](IV. Spring Boot features/30.10.1 Connecting to InfluxDB.md) + * [31. 缓存](IV. Spring Boot features/31. Caching.md) + * [31.1 支持的缓存提供商](IV. Spring Boot features/31.1 Supported Cache Providers.md) + * [31.1.1 Generic](IV. Spring Boot features/31.1.1 Generic.md) + * [31.1.2 JCache (JSR-107)](IV. Spring Boot features/31.1.2 JCache(JSR-107).md) + * [31.1.3 EhCache 2.x](IV. Spring Boot features/31.1.3 EhCache 2.x.md) + * [31.1.4 Hazelcast](IV. Spring Boot features/31.1.4 Hazelcast.md) + * [31.1.5 Infinispan](IV. Spring Boot features/31.1.5 Infinispan.md) + * [31.1.6 Couchbase](IV. Spring Boot features/31.1.6 Couchbase.md) + * [31.1.7 Redis](IV. Spring Boot features/31.1.7 Redis.md) + * [31.1.8 Caffeine](IV. Spring Boot features/31.1.8 Caffeine.md) + * [31.1.9 Simple](IV. Spring Boot features/31.1.9 Simple.md) + * [31.1.10 None](IV. Spring Boot features/31.1.10 None.md) + * [32. 消息](IV. Spring Boot features/32. Messaging.md) + * [32.1. JMS](IV. Spring Boot features/32.1. JMS.md) + * [32.1.1 ActiveQ支持](IV. Spring Boot features/32.1.1 ActiveMQ Support.md) + * [32.1.2 Artemis支持](IV. Spring Boot features/32.1.2 Artemis Support.md) + * [32.1.3 使用JNDI ConnectionFactory](IV. Spring Boot features/32.1.3 Using a JNDI ConnectionFactory.md) + * [32.1.4 发送消息](IV. Spring Boot features/32.1.4 Sending a Message.md) + * [32.1.5 接收消息](IV. Spring Boot features/32.1.5 Receiving a Message.md) + * [32.2 AMQP](IV. Spring Boot features/32.2 AMQP.md) + * [32.2.1 RabbitMQ支持](IV. Spring Boot features/32.2.1 RabbitMQ support.md) + * [32.2.2 发送消息](IV. Spring Boot features/32.2.2 Sending a Message.md) + * [32.2.3 接收消息](IV. Spring Boot features/32.2.3 Receiving a Message.md) + * [32.3 Apache Kafka支持](IV. Spring Boot features/32.3 Apache Kafka Support.md) + * [32.3.1 发送消息](IV. Spring Boot features/32.3.1 Sending a Message.md) + * [32.3.2 接收消息](IV. Spring Boot features/32.3.2 Receiving a Message.md) + * [32.3.3 其它的Kafka属性](IV. Spring Boot features/32.3.3 Additional Kafka Properties.md) + * [33. 使用RestTemplate调用REST服务](IV. Spring Boot features/33. Calling REST Services with RestTemplate.md) + * [33.1 自定义RestTemplate](IV. Spring Boot features/33.1 RestTemplate Customization.md) + * [34. 使用WebClient调用REST服务](IV. Spring Boot features/34. Calling REST Services with WebClient.md) + * [34.1 自定义WebClient](IV. Spring Boot features/34.1 WebClient Customization.md) + * [35. 验证](IV. Spring Boot features/35. Validation.md) + * [36. 发送邮件](IV. Spring Boot features/36. Sending Email.md) + * [37. 使用JTA处理分布式事务](IV. Spring Boot features/37. Distributed Transactions with JTA.md) + * [37.1 使用Atomikos事务管理器](IV. Spring Boot features/37.1 Using an Atomikos Transaction Manager.md) + * [37.2 使用Bitronix事务管理器](IV. Spring Boot features/37.2 Using a Bitronix Transaction Manager.md) + * [37.3 使用Narayana事务管理器](IV. Spring Boot features/37.3 Using a Narayana Transaction Manager.md) + * [37.4 使用J2EE管理的事务管理器](IV. Spring Boot features/37.4 Using a Java EE Managed Transaction Manager.md) + * [37.5 混合XA和non-XA的JMS连接](IV. Spring Boot features/37.5 Mixing XA and Non-XA JMS Connections.md) + * [37.6 支持可替代的内嵌事务管理器](IV. Spring Boot features/37.6 Supporting an Alternative Embedded Transaction Manager.md) + * [38. Hazelcast](IV. Spring Boot features/38. Hazelcast.md) + * [39. Quartz调度器](IV. Spring Boot features/39. Quartz Scheduler.md) + * [40. Spring集成](IV. Spring Boot features/40. Spring Integration.md) + * [41. Spring Session](IV. Spring Boot features/41. Spring Session.md) + * [42. 基于JMX的监控和管理](IV. Spring Boot features/42. Monitoring and Management over JMX.md) + * [43. 测试](IV. Spring Boot features/43. Testing.md) + * [43.1 测试作用域依赖](IV. Spring Boot features/43.1 Test Scope Dependencies.md) + * [43.2 测试Spring应用](IV. Spring Boot features/43.2 Testing Spring Applications.md) + * [43.3 测试Spring Boot应用](IV. Spring Boot features/43.3 Testing Spring Boot Applications.md) + * [43.3.1 检测网络应用类型](IV. Spring Boot features/43.3.1 Detecting Web Application Type.md) + * [43.3.2 检测测试配置](IV. Spring Boot features/43.3.2 Detecting Test Configuration.md) + * [43.3.3 排除测试配置](IV. Spring Boot features/43.3.3 Excluding Test Configuration.md) + * [43.3.4 使用运行的服务器测试](IV. Spring Boot features/43.3.4 Testing with a running server.md) + * [43.3.5 模拟和监视bean](IV. Spring Boot features/43.3.5 Mocking and Spying Beans.md) + * [43.3.6 自动配置测试](IV. Spring Boot features/43.3.6 Auto-configured Tests.md) + * [43.3.7 自动配置的JSON测试](IV. Spring Boot features/43.3.7 Auto-configured JSON Tests.md) + * [43.3.8 自动配置的Spring MVC测试](IV. Spring Boot features/43.3.8 Auto-configured Spring MVC Tests.md) + * [43.3.9 自动配置的Spring WebFlux测试](IV. Spring Boot features/43.3.9 Auto-configured Spring WebFlux Tests.md) + * [43.3.10 自动配置的Data JPA测试](IV. Spring Boot features/43.3.10 Auto-configured Data JPA Tests.md) + * [43.3.11 自动配置的JDBC测试](IV. Spring Boot features/43.3.11 Auto-configured JDBC Tests.md) + * [43.3.12 自动配置的jOOQ测试](IV. Spring Boot features/43.3.12 Auto-configured jOOQ Tests.md) + * [43.3.13 自动配置的Data MongoDB测试](IV. Spring Boot features/43.3.13 Auto-configured Data MongoDB Tests.md) + * [43.3.14 自动配置的Data Neo4j测试](IV. Spring Boot features/43.3.14 Auto-configured Data Neo4j Tests.md) + * [43.3.15 自动配置的Data Redis测试](IV. Spring Boot features/43.3.15 Auto-configured Data Redis Tests.md) + * [43.3.16 自动配置的Data LDAP测试](IV. Spring Boot features/43.3.16 Auto-configured Data LDAP Tests.md) + * [43.3.17 自动配置的REST客户端](IV. Spring Boot features/43.3.17 Auto-configured REST Clients.md) + * [43.3.18 自动配置的Spring REST Docs测试](IV. Spring Boot features/43.3.18 Auto-configured Spring REST Docs Tests.md) + * [43.3.19 用户配置与切片](IV. Spring Boot features/43.3.19 User Configuration and Slicing.md) + * [43.3.20 使用Spock测试Spring Boot应用](IV. Spring Boot features/43.3.20 Using Spock to Test Spring Boot Applications.md) + * [43.4 测试工具类](IV. Spring Boot features/43.4 Test Utilities.md) + * [43.4.1 ConfigFileApplicationContextInitializer](IV. Spring Boot features/43.4.1 ConfigFileApplicationContextInitializer.md) + * [43.4.2 EnvironmentTestUtils](IV. Spring Boot features/43.4.2 EnvironmentTestUtils.md) + * [43.4.3 OutputCapture](IV. Spring Boot features/43.4.3 OutputCapture.md) + * [43.4.4 TestRestTemplate](IV. Spring Boot features/43.4.4 TestRestTemplate.md) + * [44. WebSockets](IV. Spring Boot features/44. WebSockets.md) + * [45. Web Services](IV. Spring Boot features/45. Web Services.md) + * [46. 创建自己的自动配置](IV. Spring Boot features/46. Creating Your Own Auto-configuration.md) + * [46.1 理解自动配置的bean](IV. Spring Boot features/46.1 Understanding Auto-configured Beans.md) + * [46.2 定位自动配置候选者](IV. Spring Boot features/46.2 Locating Auto-configuration Candidates.md) + * [46.3 条件注解](IV. Spring Boot features/46.3 Condition Annotations.md) + * [46.3.1 Class条件](IV. Spring Boot features/46.3.1 Class Conditions.md) + * [46.3.2 Bean条件](IV. Spring Boot features/46.3.2 Bean Conditions.md) + * [46.3.3 Property条件](IV. Spring Boot features/46.3.3 Property Conditions.md) + * [46.3.4 Resource条件](IV. Spring Boot features/46.3.4 Resource Conditions.md) + * [46.3.5 Web Application条件](IV. Spring Boot features/46.3.5 Web Application Conditions.md) + * [46.3.6 SpEL表达式条件](IV. Spring Boot features/46.3.6 SpEL Expression Conditions.md) + * [46.4 测试你的自动配置](IV. Spring Boot features/46.4 Testing your Auto-configuration.md) + * [46.4.1 模拟网络上下文](IV. Spring Boot features/46.4.1 Simulating a Web Context.md) + * [46.4.2 覆盖类路径](IV. Spring Boot features/46.4.2 Overriding the Classpath.md) + * [46.5 创建自己的starter](IV. Spring Boot features/46.5 Creating Your Own Starter.md) + * [46.5.1 命名](IV. Spring Boot features/46.5.1 Naming.md) + * [46.5.2 自动配置模块](IV. Spring Boot features/46.5.2 Autoconfigure Module.md) + * [46.5.3 Starter模块](IV. Spring Boot features/46.5.3 Starter Module.md) + * [47. Kotlin支持](IV. Spring Boot features/47. Kotlin support.md) + * [47.1 要求](IV. Spring Boot features/47.1 Requirements.md) + * [47.2 空安全](IV. Spring Boot features/47.2 Null-safety.md) + * 47.3 Kotlin API + * [47.3.1 runApplication](IV. Spring Boot features/47.3.1 runApplication.md) + * [47.3.2 扩展](IV. Spring Boot features/47.3.2 Extensions.md) + * [47.4 依赖管理](IV. Spring Boot features/47.4 Dependency management.md) + * [47.5 @ConfigurationProperties](IV. Spring Boot features/47.5 @ConfigurationProperties.md) + * [47.6 测试](IV. Spring Boot features/47.6 Testing.md) + * 47.7 资源 + * [47.7.1 延伸阅读](IV. Spring Boot features/47.7.1 Further reading.md) + * [47.7.2 示例](IV. Spring Boot features/47.7.2 Examples.md) + * [48. 接下来阅读什么](IV. Spring Boot features/48. What to Read Next.md) +* [V. Spring Boot执行器:用于生产环境的特性](V. Spring Boot Actuator/README.md) + * [49. 开启用于生产环境的特性](V. Spring Boot Actuator/49. Enabling Production-ready Features.md) + * [50. 端点](V. Spring Boot Actuator/50. Endpoints.md) + * [50.1 启用端点](V. Spring Boot Actuator/50.1 Enabling Endpoints.md) + * [50.2 暴露端点](V. Spring Boot Actuator/50.2 Exposing Endpoints.md) + * [50.3 加密HTTP端点](V. Spring Boot Actuator/50.3 Securing HTTP Endpoints.md) + * [50.4 配置端点](V. Spring Boot Actuator/50.4 Configuring Endpoints.md) + * [50.5 执行器网络端点的超媒体支持](V. Spring Boot Actuator/50.5 Hypermedia for Actuator Web Endpoints.md) + * [50.6 执行器网络端点路径](V. Spring Boot Actuator/50.6 Actuator Web Endpoint Paths.md) + * [50.7 CORS支持](V. Spring Boot Actuator/50.7 CORS Support.md) + * [50.8 实现自定义端点](V. Spring Boot Actuator/50.8 Implementing Custom Endpoints.md) + * [50.8.1 接收输入](V. Spring Boot Actuator/50.8.1 Receiving Input.md) + * [50.8.2 自定义网络端点](V. Spring Boot Actuator/50.8.2 Custom Web Endpoints.md) + * [50.8.3 Servlet端点](V. Spring Boot Actuator/50.8.3 Servlet endpoints.md) + * [50.8.4 Controller端点](V. Spring Boot Actuator/50.8.4 Controller endpoints.md) + * [50.9 健康信息](V. Spring Boot Actuator/50.9 Health Information.md) + * [50.9.1 自动配置的HealthIndicator](V. Spring Boot Actuator/50.9.1 Auto-configured HealthIndicators.md) + * [50.9.2 编写自定义HealthIndicator](V. Spring Boot Actuator/50.9.2 Writing Custom HealthIndicators.md) + * [50.9.3 响应式的健康指示器](V. Spring Boot Actuator/50.9.3 Reactive Health Indicators.md) + * [50.9.4 自动配置的ReactiveHealthIndicators](V. Spring Boot Actuator/50.9.4 Auto-configured ReactiveHealthIndicators.md) + * [50.10 应用信息](V. Spring Boot Actuator/50.10 Application Information.md) + * [50.10.1 自动配置的InfoContributors](V. Spring Boot Actuator/50.10.1 Auto-configured InfoContributors.md) + * [50.10.2 自定义应用信息](V. Spring Boot Actuator/50.10.2 Custom Application Information.md) + * [50.10.3 Git提交信息](V. Spring Boot Actuator/50.10.3 Git Commit Information.md) + * [50.10.4 构建信息](V. Spring Boot Actuator/50.10.4 Build Information.md) + * [50.10.5 编写自定义的InfoContributor](V. Spring Boot Actuator/50.10.5 Writing Custom InfoContributors.md) + * [51. 基于HTTP的监控和管理](V. Spring Boot Actuator/51. Monitoring and Management over HTTP.md) + * [51.1 自定义管理端点路径](V. Spring Boot Actuator/51.1 Customizing the Management Endpoint Paths.md) + * [51.2 自定义管理服务器端口](V. Spring Boot Actuator/51.2 Customizing the Management Server Port.md) + * [51.3 配置管理相关的SSL](V. Spring Boot Actuator/51.3 Configuring Management-specific SSL.md) + * [51.4 自定义管理服务器地址](V. Spring Boot Actuator/51.4 Customizing the Management Server Address.md) + * [51.5 禁用HTTP端点](V. Spring Boot Actuator/51.5 Disabling HTTP Endpoints.md) + * [52. 基于JMX的监控和管理](V. Spring Boot Actuator/52. Monitoring and Management over JMX.md) + * [52.1 自定义MBean名称](V. Spring Boot Actuator/52.1 Customizing MBean Names.md) + * [52.2 禁用JMX端点](V. Spring Boot Actuator/52.2 Disabling JMX Endpoints.md) + * [52.3 使用Jolokia通过HTTP实现JMX远程管理](V. Spring Boot Actuator/52.3 Using Jolokia for JMX over HTTP.md) + * [52.3.1 自定义Jolokia](V. Spring Boot Actuator/52.3.1 Customizing Jolokia.md) + * [52.3.2 禁用Jolokia](V. Spring Boot Actuator/52.3.2 Disabling Jolokia.md) + * [53. 记录器](V. Spring Boot Actuator/53. Loggers.md) + * [53.1 配置记录器](V. Spring Boot Actuator/53.1 Configure a Logger.md) + * [54. 度量指标](V. Spring Boot Actuator/54. Metrics.md) + * [54.1 入门指南](V. Spring Boot Actuator/54.1 Getting started.md) + * 54.2 支持的监控系统 + * [54.2.1 Atlas](V. Spring Boot Actuator/54.2.1 Atlas.md) + * [54.2.2 Datadog](V. Spring Boot Actuator/54.2.2 Datadog.md) + * [54.2.3 Ganglia](V. Spring Boot Actuator/54.2.3 Ganglia.md) + * [54.2.4 Graphite](V. Spring Boot Actuator/54.2.4 Graphite.md) + * [54.2.5 Influx](V. Spring Boot Actuator/54.2.5 Influx.md) + * [54.2.6 JMX](V. Spring Boot Actuator/54.2.6 JMX.md) + * [54.2.7 New Relic](V. Spring Boot Actuator/54.2.7 New Relic.md) + * [54.2.8 Prometheus](V. Spring Boot Actuator/54.2.8 Prometheus.md) + * [54.2.9 SignalFx](V. Spring Boot Actuator/54.2.9 SignalFx.md) + * [54.2.10 Simple](V. Spring Boot Actuator/54.2.10 Simple.md) + * [54.2.11 StatsD](V. Spring Boot Actuator/54.2.11 StatsD.md) + * [54.2.12 Wavefront](V. Spring Boot Actuator/54.2.12 Wavefront.md) + * [54.3 支持的指标](V. Spring Boot Actuator/54.3 Supported Metrics.md) + * [54.3.1 Spring MVC指标](V. Spring Boot Actuator/54.3.1 Spring MVC Metrics.md) + * [54.3.2 Spring WebFlux指标](V. Spring Boot Actuator/54.3.2 Spring WebFlux Metrics.md) + * [54.3.3 RestTemplate指标](V. Spring Boot Actuator/54.3.3 RestTemplate Metrics.md) + * [54.3.4 Spring集成指标](V. Spring Boot Actuator/54.3.4 Spring Integration metrics.md) + * [54.3.5 缓存指标](V. Spring Boot Actuator/54.3.5 Cache Metrics.md) + * [54.3.6 数据源指标](V. Spring Boot Actuator/54.3.6 DataSource Metrics.md) + * [54.3.7 RabbitMQ指标](V. Spring Boot Actuator/54.3.7 RabbitMQ Metrics.md) + * [54.4 注册自定义指标](V. Spring Boot Actuator/54.4 Registering custom metrics.md) + * [54.5 自定义单个指标](V. Spring Boot Actuator/54.5 Customizing individual metrics.md) + * [54.5.1 Per-meter属性](V. Spring Boot Actuator/54.5.1 Per-meter properties.md) + * [54.6 度量端点](V. Spring Boot Actuator/54.6 Metrics endpoint.md) + * [55. 审计](V. Spring Boot Actuator/55. Auditing.md) + * [56. HTTP追踪](V. Spring Boot Actuator/56. HTTP Tracing.md) + * [56.1 自定义HTTP追踪](V. Spring Boot Actuator/56.1 Custom HTTP tracing.md) + * [57. 进程监控](V. Spring Boot Actuator/57. Process Monitoring.md) + * [57.1 扩展配置](V. Spring Boot Actuator/57.1 Extend Configuration.md) + * [57.2 以编程方式](V. Spring Boot Actuator/57.2 Programmatically.md) + * [58. Cloud Foundry支持](V. Spring Boot Actuator/58. Cloud Foundry Support.md) + * [58.1 禁用扩展的Cloud Foundry执行器支持](V. Spring Boot Actuator/58.1 Disabling Extended Cloud Foundry Actuator Support.md) + * [58.2 Cloud Foundry自签名证书](V. Spring Boot Actuator/58.2 Cloud Foundry Self-signed Certificates.md) + * [58.3 自定义上下文路径](V. Spring Boot Actuator/58.3 Custom context path.md) + * [59. 接下来阅读什么](V. Spring Boot Actuator/59. What to Read Next.md) +* [VI. 部署到云端](VI. Deploying Spring Boot Applications/README.md) + * [60. 部署到云端](VI. Deploying Spring Boot Applications/60. Deploying to the Cloud.md) + * [60.1 Cloud Foundry](VI. Deploying Spring Boot Applications/60.1 Cloud Foundry.md) + * [60.1.1 绑定服务](VI. Deploying Spring Boot Applications/60.1.1 Binding to Services.md) + * [60.2 Heroku](VI. Deploying Spring Boot Applications/60.2 Heroku.md) + * [60.3 Openshift](VI. Deploying Spring Boot Applications/60.3 Openshift.md) + * [60.4 亚马逊网络服务(AWS)](VI. Deploying Spring Boot Applications/60.4 Amazon Web Services(AWS).md) + * [60.4.1 AWS Elastic Beanstalk](VI. Deploying Spring Boot Applications/60.4.1 AWS Elastic Beanstalk.md) + * [60.4.2 总结](VI. Deploying Spring Boot Applications/60.4.2 Summary.md) + * [60.5 Boxfuse和亚马逊网络服务](VI. Deploying Spring Boot Applications/60.5 Boxfuse and Amazon Web Services.md) + * [60.6 Google Cloud](VI. Deploying Spring Boot Applications/60.6 Google Cloud.md) + * [61. 安装Spring Boot应用](VI. Deploying Spring Boot Applications/61. Installing Spring Boot Applications.md) + * [61.1 支持的操作系统](VI. Deploying Spring Boot Applications/61.1 Supported Operating Systems.md) + * [61.2 Unix/Linux服务](VI. Deploying Spring Boot Applications/61.2 Unix&Linux Services.md) + * [61.2.1 安装为init.d服务(System V)](VI. Deploying Spring Boot Applications/61.2.1 Installation as an init.d Service(System V).md) + * [61.2.2 安装为Systemd服务](VI. Deploying Spring Boot Applications/61.2.2 Installation as a systemd Service.md) + * [61.2.3 自定义启动脚本](VI. Deploying Spring Boot Applications/61.2.3 Customizing the Startup Script.md) + * [61.3 Microsoft Windows服务](VI. Deploying Spring Boot Applications/61.3 Microsoft Windows Services.md) + * [62. 接下来阅读什么](VI. Deploying Spring Boot Applications/62. What to Read Next.md) +* [VII. Spring Boot CLI](VII. Spring Boot CLI/README.md) + * [63. 安装CLI](VII. Spring Boot CLI/63. Installing the CLI.md) + * [64. 使用CLI](VII. Spring Boot CLI/64. Using the CLI.md) + * [64.1 使用CLI运行应用](VII. Spring Boot CLI/64.1. Running Applications with the CLI.md) + * [64.1.1 推断"grab"依赖](VII. Spring Boot CLI/64.1.1 Deduced “grab” Dependencies.md) + * [64.1.2 推断"grab"坐标](VII. Spring Boot CLI/64.1.2 Deduced “grab” Coordinates.md) + * [64.1.3 默认import语句](VII. Spring Boot CLI/64.1.3 Default Import Statements.md) + * [64.1.4 自动创建main方法](VII. Spring Boot CLI/64.1.4 Automatic Main Method.md) + * [64.1.5 自定义依赖管理](VII. Spring Boot CLI/64.1.5 Custom Dependency Management.md) + * [64.2 多源文件应用](VII. Spring Boot CLI/64.2 Applications with Multiple Source Files.md) + * [64.3 应用打包](VII. Spring Boot CLI/64.3 Packaging Your Application.md) + * [64.4 初始化新工程](VII. Spring Boot CLI/64.4 Initialize a New Project.md) + * [64.5 使用内嵌shell](VII. Spring Boot CLI/64.5 Using the Embedded Shell.md) + * [64.6 为CLI添加扩展](VII. Spring Boot CLI/64.6 Adding Extensions to the CLI.md) + * [65. 使用Groovy beans DSL开发应用](VII. Spring Boot CLI/65. Developing Application with the Groovy Beans DSL.md) + * [66. 使用settings.xml配置CLI](VII. Spring Boot CLI/66. Configuring the CLI with settings.xml.md) + * [67. 接下来阅读什么](VII. Spring Boot CLI/67. What to Read Next.md) +* [VIII. 构建工具插件](VIII. Build tool plugins/README.md) + * [68. Spring Boot Maven插件](VIII. Build tool plugins/68. Spring Boot Maven Plugin.md) + * [68.1 包含该插件](VIII. Build tool plugins/68.1 Including the Plugin.md) + * [68.2 打包可执行jar和war文件](VIII. Build tool plugins/68.2 Packaging Executable Jar and War Files.md) + * [69. Spring Boot Gradle插件](VIII. Build tool plugins/69. Spring Boot Gradle Plugin.md) + * [70. Spring Boot AntLib模块](VIII. Build tool plugins/70. Spring Boot AntLib Module.md) + * [70.1. Spring Boot Ant任务](VIII. Build tool plugins/70.1. Spring Boot Ant Tasks.md) + * [70.1.1. spring-boot:exejar](VIII. Build tool plugins/70.1.1. spring-boot:exejar.md) + * [70.1.2. 示例](VIII. Build tool plugins/70.1.2. Examples.md) + * [70.2. spring-boot:findmainclass](VIII. Build tool plugins/70.2. spring-boot:findmainclass.md) + * [70.2.1. 示例](VIII. Build tool plugins/70.2.1. Examples.md) +   * [71. 对其他构建系统的支持](VIII. Build tool plugins/71. Supporting Other Build Systems.md) + * [71.1. 重新打包存档](VIII. Build tool plugins/71.1. Repackaging Archives.md) + * [71.2. 内嵌库](VIII. Build tool plugins/71.2. Nested Libraries.md) + * [71.3. 查找main类](VIII. Build tool plugins/71.3. Finding a Main Class.md) + * [71.4. repackage实现示例](VIII. Build tool plugins/71.4. Example Repackage Implementation.md) + * [72. 接下来阅读什么](VIII. Build tool plugins/72. What to Read Next.md) +* [IX. How-to指南](IX. ‘How-to’ guides/README.md) + * [73. Spring Boot应用](IX. ‘How-to’ guides/73. Spring Boot Application.md) + * [73.1 创建自己的FailureAnalyzer](IX. ‘How-to’ guides/73.1 Create Your Own FailureAnalyzer.md) + * [73.2 解决自动配置问题](IX. ‘How-to’ guides/73.2 Troubleshoot Auto-configuration.md) + * [73.3 启动前自定义Environment或ApplicationContext](IX. ‘How-to’ guides/73.3 Customize the Environment or ApplicationContext Before It Starts.md) + * [73.4 构建ApplicationContext层次结构](IX. ‘How-to’ guides/73.4 Build an ApplicationContext Hierarchy(Adding a Parent or Root Context).md) + * [73.5 创建no-web应用](IX. ‘How-to’ guides/73.5 Create a Non-web Application.md) + * [74. 属性与配置](IX. ‘How-to’ guides/74. Properties and Configuration.md) + * [74.1. 运行时暴露属性](IX. ‘How-to’ guides/74.1. Automatically Expand Properties at Build Time.md) + * [74.1.1. 使用Maven自动暴露属性](IX. ‘How-to’ guides/74.1.1. Automatic Property Expansion Using Maven.md) + * [74.1.2. 使用Gradle自动暴露属性](IX. ‘How-to’ guides/74.1.2. Automatic Property Expansion Using Gradle.md) + * [74.2. 外部化SpringApplication配置](IX. ‘How-to’ guides/74.2. Externalize the Configuration of SpringApplication.md) + * [74.3 改变应用程序外部配置文件的位置](IX. ‘How-to’ guides/74.3 Change the Location of External Properties of an Application.md) + * [74.4 使用“短”命令行参数](IX. ‘How-to’ guides/74.4 Use ‘Short’ Command Line Arguments.md) + * [74.5 使用YAML配置外部属性](IX. ‘How-to’ guides/74.5 Use YAML for External Properties.md) + * [74.6 设置生效的Spring profiles](IX. ‘How-to’ guides/74.6 Set the Active Spring Profiles.md) + * [74.7 根据环境改变配置](IX. ‘How-to’ guides/74.7 Change Configuration Depending on the Environment.md) + * [74.8 发现外部属性的内置选项](IX. ‘How-to’ guides/74.8 Discover Built-in Options for External Properties.md) + * [75. 内嵌网络服务器](IX. ‘How-to’ guides/75. Embedded Web Servers.md) + * [75.1 使用另外的网络服务器](IX. ‘How-to’ guides/75.1 Use Another Web Server.md) + * [75.2 配置Jetty](IX. ‘How-to’ guides/75.2 Configure Jetty.md) + * [75.3 为应用添加Servlet、Filter或Listener](IX. ‘How-to’ guides/75.3 Add a Servlet, Filter, or Listener to an Application.md) + * [75.3.1 使用Spring bean添加Servlet、Filter或Listener](IX. ‘How-to’ guides/75.3.1 Add a Servlet, Filter, or Listener by Using a Spring Bean.md) + * [75.3.2 使用类路径扫描添加Servlet、Filter和Listener](IX. ‘How-to’ guides/75.3.2 Add Servlets, Filters, and Listeners by Using Classpath Scanning.md) + * [75.4 改变HTTP端口](IX. ‘How-to’ guides/75.4 Change the HTTP Port.md) + * [75.5 使用随机未分配的HTTP端口](IX. ‘How-to’ guides/75.5 Use a Random Unassigned HTTP Port.md) + * [75.6 在运行时发现HTTP端口](IX. ‘How-to’ guides/75.6 Discover the HTTP Port at Runtime.md) + * [75.7 配置SSL](IX. ‘How-to’ guides/75.7 Configure SSL.md) + * [75.8 配置HTTP/2](IX. ‘How-to’ guides/75.8 Configure HTTP2.md) + * [75.8.1 HTTP/2与Undertow](IX. ‘How-to’ guides/75.8.1 HTTP2 with Undertow.md) + * [75.8.2 HTTP/2与Jetty](IX. ‘How-to’ guides/75.8.2 HTTP2 with Jetty.md) + * [75.8.3 HTTP/2与Tomcat](IX. ‘How-to’ guides/75.8.3 HTTP2 with Tomcat.md) + * [75.9 配置访问日志](IX. ‘How-to’ guides/75.9 Configure Access Logging.md) + * [75.10 在前端代理服务器后运行](IX. ‘How-to’ guides/75.10 Running Behind a Front-end Proxy Server.md) + * [75.10.1 自定义Tomcat代理配置](IX. ‘How-to’ guides/75.10.1 Customize Tomcat’s Proxy Configuration.md) + * [75.11 配置Tomcat](IX. ‘How-to’ guides/75.11 Configure Tomcat.md) + * [75.12 启用Tomcat的多连接器](IX. ‘How-to’ guides/75.12 Enable Multiple Connectors with Tomcat.md) + * [75.13 使用Tomcat的LegacyCookieProcessor](IX. ‘How-to’ guides/75.13 Use Tomcat’s LegacyCookieProcessor.md) + * [75.14 配置Undertow](IX. ‘How-to’ guides/75.14 Configure Undertow.md) + * [75.15 启用Undertow的多监听器](IX. ‘How-to’ guides/75.15 Enable Multiple Listeners with Undertow.md) + * [75.16 使用@ServerEndpoint创建WebSocket端点](IX. ‘How-to’ guides/75.16 Create WebSocket Endpoints Using @ServerEndpoint.md) + * [75.17 启用HTTP响应压缩](IX. ‘How-to’ guides/75.17 Enable HTTP Response Compression.md) + * [76. Spring MVC](IX. ‘How-to’ guides/76. Spring MVC.md) + * [76.1 编写JSON REST服务](IX. ‘How-to’ guides/76.1 Write a JSON REST Service.md) + * [76.2 编写XML REST服务](IX. ‘How-to’ guides/76.2 Write an XML REST Service.md) + * [76.3 自定义Jackson ObjectMapper](IX. ‘How-to’ guides/76.3 Customize the Jackson ObjectMapper.md) + * [76.4 自定义@ResponseBody渲染](IX. ‘How-to’ guides/76.4 Customize the @ResponseBody Rendering.md) + * [76.5 处理Multipart文件上传](IX. ‘How-to’ guides/76.5 Handling Multipart File Uploads.md) + * [76.6 关闭Spring MVC DispatcherServlet](IX. ‘How-to’ guides/76.6 Switch Off the Spring MVC DispatcherServlet.md) + * [76.7 关闭默认的MVC配置](IX. ‘How-to’ guides/76.7 Switch off the Default MVC Configuration.md) + * [76.8 自定义ViewResolvers](IX. ‘How-to’ guides/76.8 Customize ViewResolvers.md) + * [77. HTTP客户端](IX. ‘How-to’ guides/77. HTTP Clients.md) + * [77.1 配置RestTemplate使用代理](IX. ‘How-to’ guides/77.1 Configure RestTemplate to Use a Proxy.md) + * [78. 日志](IX. ‘How-to’ guides/78. Logging.md) + * [78.1 配置Logback](IX. ‘How-to’ guides/78.1 Configure Logback for Logging.md) + * [78.1.1 配置logback只输出到文件](IX. ‘How-to’ guides/78.1.1 Configure Logback for File-only Output.md) + * [78.2 配置Log4j](IX. ‘How-to’ guides/78.2 Configure Log4j for Logging.md) + * [78.2.1 使用YAML或JSON配置Log4j2](IX. ‘How-to’ guides/78.2.1 Use YAML or JSON to Configure Log4j 2.md) + * [79. 数据访问](IX. ‘How-to’ guides/79. Data Access.md) + * [79.1 配置自定义的数据源](IX. ‘How-to’ guides/79.1 Configure a Custom DataSource.md) + * [79.2 配置两个数据源](IX. ‘How-to’ guides/79.2 Configure Two DataSources.md) + * [79.3 使用Spring Data仓库](IX. ‘How-to’ guides/79.3 Use Spring Data Repositories.md) + * [79.4 从Spring配置分离@Entity定义](IX. ‘How-to’ guides/79.4 Separate @Entity Definitions from Spring Configuration.md) + * [79.5 配置JPA属性](IX. ‘How-to’ guides/79.5 Configure JPA Properties.md) + * [79.6 配置Hibernate命名策略](IX. ‘How-to’ guides/79.6 Configure Hibernate Naming Strategy.md) + * [79.7 使用自定义EntityManagerFactory](IX. ‘How-to’ guides/79.7 Use a Custom EntityManagerFactory.md) + * [79.8 使用两个EntityManagers](IX. ‘How-to’ guides/79.8 Use Two EntityManagers.md) + * [79.9 使用传统的persistence.xml文件](IX. ‘How-to’ guides/79.9 Use a Traditional persistence.xml File.md) + * [79.10 使用Spring Data JPA和Mongo仓库](IX. ‘How-to’ guides/79.10 Use Spring Data JPA and Mongo Repositories.md) + * [79.11 将Spring Data仓库暴露为REST端点](IX. ‘How-to’ guides/79.11 Expose Spring Data Repositories as REST Endpoint.md) + * [79.12 配置JPA使用的组件](IX. ‘How-to’ guides/79.12 Configure a Component that is Used by JPA.md) + * [79.13 使用两个数据源配置jOOQ](IX. ‘How-to’ guides/79.13 Configure jOOQ with Two DataSources.md) + * [80. 数据库初始化](IX. ‘How-to’ guides/80. Database Initialization.md) + * [80.1 使用JPA初始化数据库](IX. ‘How-to’ guides/80.1 Initialize a Database Using JPA.md) + * [80.2 使用Hibernate初始化数据库](IX. ‘How-to’ guides/80.2 Initialize a Database Using Hibernate.md) + * [80.3 初始化数据库](IX. ‘How-to’ guides/80.3 Initialize a Database.md) + * [80.4 初始化Spring Batch数据库](IX. ‘How-to’ guides/80.4 Initialize a Spring Batch Database.md) + * [80.5 使用高级数据迁移工具](IX. ‘How-to’ guides/80.5 Use a Higher-level Database Migration Tool.md) + * [80.5.1 启动时执行Flyway数据库迁移](IX. ‘How-to’ guides/80.5.1 Execute Flyway Database Migrations on Startup.md) + * [80.5.2 启动时执行Liquibase数据库迁移](IX. ‘How-to’ guides/80.5.2 Execute Liquibase Database Migrations on Startup.md) + * [81. 消息传送](IX. ‘How-to’ guides/81. Messaging.md) + * [81.1 禁用事务JMS会话](IX. ‘How-to’ guides/81.1 Disable Transacted JMS Session.md) + * [82. 批处理应用](IX. ‘How-to’ guides/82. Batch Applications.md) + * [82.1 在启动时执行Spring Batch作业](IX. ‘How-to’ guides/82.1 Execute Spring Batch Jobs on Startup.md) + * [83. 执行器](IX. ‘How-to’ guides/83. Actuator.md) + * [83.1 改变HTTP端口或执行器端点的地址](IX. ‘How-to’ guides/83.1 Change the HTTP Port or Address of the Actuator Endpoints.md) + * [83.2 自定义WhiteLabel错误页面](IX. ‘How-to’ guides/83.2 Customize the ‘whitelabel’ Error Page.md) + * [84. 安全](IX. ‘How-to’ guides/84. Security.md) + * [84.1 关闭Spring Boot安全配置](IX. ‘How-to’ guides/84.1 Switch off the Spring Boot Security Configuration.md) + * [84.2 改变AuthenticationManager并添加用户账号](IX. ‘How-to’ guides/84.2 Change the AuthenticationManager and Add User Accounts.md) + * [84.3 当前端使用代理服务器时启用HTTPS](IX. ‘How-to’ guides/84.3 Enable HTTPS When Running behind a Proxy Server.md) + * [85. 热交换](IX. ‘How-to’ guides/85. Hot Swapping.md) + * [85.1 重新加载静态内容](IX. ‘How-to’ guides/85.1 Reload Static Content.md) + * [85.2. 在不重启容器的情况下重新加载模板](IX. ‘How-to’ guides/85.2. Reload Templates without Restarting the Container.md) + * [85.2.1 Thymeleaf模板](IX. ‘How-to’ guides/85.2.1 Thymeleaf Templates.md) + * [85.2.2 FreeMarker模板](IX. ‘How-to’ guides/85.2.2 FreeMarker Templates.md) + * [85.2.3 Groovy模板](IX. ‘How-to’ guides/85.2.3 Groovy Templates.md) + * [85.3 应用快速重启](IX. ‘How-to’ guides/85.3 Fast Application Restarts.md) + * [85.4 在不重启容器的情况下重新加载Java类](IX. ‘How-to’ guides/85.4 Reload Java Classes without Restarting the Container.md) + * [86. 构建](IX. ‘How-to’ guides/86. Build.md) + * [86.1 生成构建信息](IX. ‘How-to’ guides/86.1 Generate Build Information.md) + * [86.2 生成Git信息](IX. ‘How-to’ guides/86.2 Generate Git Information.md) + * [86.3 自定义依赖版本](IX. ‘How-to’ guides/86.3 Customize Dependency Versions.md) + * [86.4 使用Maven创建可执行JAR](IX. ‘How-to’ guides/86.4 Create an Executable JAR with Maven.md) + * [86.5 将Spring Boot应用作为依赖](IX. ‘How-to’ guides/86.5 Use a Spring Boot Application as a Dependency.md) + * [86.6 在可执行jar运行时提取特定的版本](IX. ‘How-to’ guides/86.6 Extract Specific Libraries When an Executable Jar Runs.md) + * [86.7 使用排除创建不可执行的JAR](IX. ‘How-to’ guides/86.7 Create a Non-executable JAR with Exclusions.md) + * [86.8 远程调试使用Maven启动的Spring Boot项目](IX. ‘How-to’ guides/86.8 Remote Debug a Spring Boot Application Started with Maven.md) + * [86.9 使用Ant构建可执行存档(不使用spring-boot-antlib)](IX. ‘How-to’ guides/86.9 Build an Executable Archive from Ant without Using spring-boot-antlib.md) + * [87. 传统部署](IX. ‘How-to’ guides/87. Traditional Deployment.md) + * [87.1 创建可部署的war文件](IX. ‘How-to’ guides/87.1 Create a Deployable War File.md) + * [87.2 为老的servlet容器创建可部署的war文件](IX. ‘How-to’ guides/87.2 Create a Deployable War File for Older Servlet Containers.md) + * [87.3 将现有的应用转换为Spring Boot](IX. ‘How-to’ guides/87.3 Convert an Existing Application to Spring Boot.md) + * [87.4 部署WAR到Weblogic](IX. ‘How-to’ guides/87.4 Deploying a WAR to Weblogic.md) + * [87.5 部署WAR到老的(Servlet2.5)容器](IX. ‘How-to’ guides/87.5 Deploying a WAR in an Old(Servlet 2.5)Container.md) + * [87.6 使用Lettuce来代替Jedis](IX. ‘How-to’ guides/87.6 Use Jedis Instead of Lettuce.md) +* [X.附录](X. Appendices/README.md) + * [附录A. 常见应用属性](X. Appendices/A. Common application properties.md) + * [附录B. 配置元数据](X. Appendices/B. Configuration Metadata.md) + * [附录B.1. 元数据格式](X. Appendices/B.1. Metadata Format.md) + * [附录B.1.1. Group属性](X. Appendices/B.1.1. Group Attributes.md) + * [附录B.1.2. Property属性](X. Appendices/B.1.2. Property Attributes.md) + * [附录B.1.3. Hint属性](X. Appendices/B.1.3 Hint Attributes.md) + * [附录B.1.4. 可重复的元数据节点](X. Appendices/B.1.4. Repeated Metadata Items.md) + * [附录B.2. 提供人工提示](X. Appendices/B.2 Providing Manual Hints.md) + * [附录 B.2.1 值提示](X. Appendices/B.2.1 Value Hint.md) + * [附录 B.2.2 值提供者](X. Appendices/B.2.2 Value Provider.md) + * [附录B.3. 使用注解处理器产生自己的元数据](X. Appendices/B.3. Generating Your Own Metadata by Using the Annotation Processor.md) + * [附录 B.3.1. 内嵌属性](X. Appendices/B.3.1. Nested Properties.md) + * [附录 B.3.2. 添加其他的元数据](X. Appendices/B.3.2. Adding Additional Metadata.md) + * [附录C. 自动配置类](X. Appendices/C. Auto-configuration classes.md) + * [附录C.1. 来自spring-boot-autoconfigure模块](X. Appendices/C.1. From the “spring-boot-autoconfigure” module.md) + * [附录C.2. 来自spring-boot-actuator-autoconfigure模块](X. Appendices/C.2. From the “spring-boot-actuator-autoconfigure” module.md) + * [附录D. 测试的自动配置的标注](X. Appendices/D. Test auto-configuration annotations.md) + * [附录E. 可执行Jar格式](X. Appendices/E. The Executable Jar Format.md) + * [附录E.1. 内嵌JARs](X. Appendices/E.1. Nested JARs.md) + * [附录E.1.1. 可执行Jar文件结构](X. Appendices/E.1.1. The Executable Jar File Structure.md) + * [附录E.1.2. 可执行War文件结构](X. Appendices/E.1.2. The Executable War File Structure.md) + * [附录E.2. Spring Boot的"JarFile"类](X. Appendices/E.2. Spring Boot’s “JarFile” Class.md) + * [附录E.2.1. 对标准Java "JarFile"的兼容性](X. Appendices/E.2.1. Compatibility with the Standard Java “JarFile”.md) + * [附录E.3. 启动可执行Jars](X. Appendices/E.3. Launching Executable Jars.md) + * [附录E.3.1 Launcher manifest](X. Appendices/E.3.1. Launcher Manifest.md) + * [附录E.3.2. 暴露的存档](X. Appendices/E.3.2. Exploded Archives.md) + * [附录E.4. PropertiesLauncher特性](X. Appendices/E.4. PropertiesLauncher Features.md) + * [附录E.5. 可执行jar的限制](X. Appendices/E.5. Executable Jar Restrictions.md) + * [附录E.6. 可替代的单一jar解决方案](X. Appendices/E.6. Alternative Single Jar Solutions.md) + * [附录F. 依赖版本](X. Appendices/F. Dependency versions.md) diff --git a/V. Spring Boot Actuator/47. Enabling production-ready features.md b/V. Spring Boot Actuator/47. Enabling production-ready features.md deleted file mode 100644 index b6242ce2..00000000 --- a/V. Spring Boot Actuator/47. Enabling production-ready features.md +++ /dev/null @@ -1,20 +0,0 @@ -### 47. 开启production-ready特性 -[spring-boot-actuator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator)模块提供Spring Boot所有的production-ready特性,启用该特性的最简单方式是添加`spring-boot-starter-actuator` ‘Starter’依赖。 - -**执行器(Actuator)的定义**:执行器是一个制造业术语,指的是用于移动或控制东西的一个机械装置,一个很小的改变就能让执行器产生大量的运动。 - -按以下配置为Maven项目添加执行器: -```xml - - - org.springframework.boot - spring-boot-starter-actuator - - -``` -对于Gradle,使用下面的声明: -```java -dependencies { - compile("org.springframework.boot:spring-boot-starter-actuator") -} -``` diff --git a/V. Spring Boot Actuator/48. Endpoints.md b/V. Spring Boot Actuator/48. Endpoints.md deleted file mode 100644 index 865d793e..00000000 --- a/V. Spring Boot Actuator/48. Endpoints.md +++ /dev/null @@ -1,35 +0,0 @@ -### 48. 端点 -执行器端点(endpoints)可用于监控应用及与应用进行交互,Spring Boot包含很多内置的端点,你也可以添加自己的。例如,`health`端点提供了应用的基本健康信息。 -端点暴露的方式取决于你采用的技术类型,大部分应用选择HTTP监控,端点的ID连同前缀`/application`映射到一个URL。例如,`health`端点默认映射到`/application/health`。 - -下面的端点都是可用的: - -| ID | 描述 |是否敏感| -| ---- | :----- | :----- | -|`actuator`|为其他端点提供基于超文本的导航页面,需要添加Spring HATEOAS依赖|true| -|`auditevents`|为当前应用暴露审计事件的信息|true| -|`autoconfig`|显示一个自动配置类的报告,该报告展示所有自动配置候选者及它们被应用或未被应用的原因|true| -|`beans`|显示一个应用中所有Spring Beans的完整列表|true| -|`configprops`|显示一个所有`@ConfigurationProperties`的集合列表|true| -|`dump`|执行一个线程转储|true| -|`env`|暴露来自Spring `ConfigurableEnvironment`的属性|true| -|`flyway`|显示数据库迁移路径,如果有的话|true| -|`health`|展示应用的健康信息(当使用一个未认证连接访问时显示一个简单的'status',使用认证连接访问则显示全部信息详情)|false| -|`info`|显示任意的应用信息|false| -|`loggers`|显示和修改应用中的记录器的配置|true| -|`liquibase`|展示任何Liquibase数据库迁移路径,如果有的话|true| -|`metrics`|展示当前应用的'metrics'信息|true| -|`mappings`|显示一个所有`@RequestMapping`路径的集合列表|true| -|`shutdown`|允许应用以优雅的方式关闭(默认情况下不启用)|true| -|`trace`|显示trace信息(默认为最新的100条HTTP请求)|true| - -如果使用Spring MVC,你还可以使用以下端点: - -| ID | 描述 |是否敏感| -| ---- | :----- | :----- | -|`docs`|展示Actuator的文档,包括示例请求和响应,需添加`spring-boot-actuator-docs`依赖|false| -|`heapdump`|返回一个GZip压缩的`hprof`堆转储文件|true| -|`jolokia`|通过HTTP暴露JMX beans(依赖Jolokia)|true| -|`logfile`|返回日志文件内容(如果设置`logging.file`或`logging.path`属性),支持使用HTTP `Range`头接收日志文件内容的部分信息|| - -**注**:根据端点暴露的方式,`sensitive`属性可用做安全提示,例如,在使用HTTP访问敏感(sensitive)端点时需要提供用户名/密码(如果没有启用web安全,可能会简化为禁止访问该端点)。 diff --git a/V. Spring Boot Actuator/48.1 Customizing endpoints.md b/V. Spring Boot Actuator/48.1 Customizing endpoints.md deleted file mode 100644 index fafa72f2..00000000 --- a/V. Spring Boot Actuator/48.1 Customizing endpoints.md +++ /dev/null @@ -1,19 +0,0 @@ -### 48.1 自定义端点 -使用Spring属性可以自定义端点,你可以设置端点是否开启(`enabled`),是否敏感(`sensitive`),甚至改变它的`id`。例如,下面的`application.properties`改变`beans`端点的敏感性及id,并启用`shutdown`: -```java -endpoints.beans.id=springbeans -endpoints.beans.sensitive=false -endpoints.shutdown.enabled=true -``` -**注**:前缀`endpoints + . + name`用于被配置端点的唯一标识。 - -默认情况,所有端点除了`shutdown`以外都是开启的,你可以使用`endpoints.enabled`属性指定可选端点是否启用。例如,所有端点除`info`外都被禁用: -```java -endpoints.enabled=false -endpoints.info.enabled=true -``` -同样地,你可以全局范围内设置所有端点的`sensitive`标记,敏感标记默认取决于端点类型(查看上面表格)。例如,所有端点除`info`外都标记为敏感: -```java -endpoints.sensitive=true -endpoints.info.sensitive=false -``` diff --git a/V. Spring Boot Actuator/48.2 Hypermedia for actuator MVC endpoints.md b/V. Spring Boot Actuator/48.2 Hypermedia for actuator MVC endpoints.md deleted file mode 100644 index bad667a1..00000000 --- a/V. Spring Boot Actuator/48.2 Hypermedia for actuator MVC endpoints.md +++ /dev/null @@ -1,6 +0,0 @@ -###48.2 执行器MVC端点的超媒体支持 -如果`endpoints.hypermedia.enabled`设置为true,同时classpath下存在[Spring HATEOAS](http://projects.spring.io/spring-hateoas)库(比如,通过`spring-boot-starter-hateoas`或使用[Spring Data REST](http://projects.spring.io/spring-data-rest)),来自执行器(Actuator)的HTTP端点将使用超媒体链接进行增强(hypermedia links),也就是使用一个“导航页”汇总所有端点链接,该页面默认路径为`/application`。该实现也是一个端点,可以通过属性配置它的路径(`endpoints.actuator.path`)及是否开启(`endpoints.actuator.enabled`)。 - -当指定了一个自定义管理上下文路径时,“导航页”路径自动从`/application`迁移到管理上下文根目录。例如,如果管理上下文路径为`/management`,那就可以通过`/management`访问“导航页”。 - -如果classpath下存在[HAL Browser](https://github.com/mikekelly/hal-browser)(通过webjar:`org.webjars:hal-browser`,或`spring-data-rest-hal-browser`),Spring Boot将提供一个以HAL Browser格式的HTML“导航页”。 diff --git a/V. Spring Boot Actuator/48.3 CORS support.md b/V. Spring Boot Actuator/48.3 CORS support.md deleted file mode 100644 index 9104a59e..00000000 --- a/V. Spring Boot Actuator/48.3 CORS support.md +++ /dev/null @@ -1,10 +0,0 @@ -###48.3 CORS支持 -[跨域资源共享](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)(CORS)是一个[W3C规范](http://www.w3.org/TR/cors/),用于以灵活的方式指定跨域请求的认证类型,执行器的MVC端点也可以配置成支持该场景。 - -CORS支持默认是禁用的,只有在`endpoints.cors.allowed-origins`属性设置时才启用。以下配置允许来自`example.com`域的`GET`和`POST`调用: -```properties -endpoints.cors.allowed-origins=http://example.com -endpoints.cors.allowed-methods=GET,POST -``` - -**注** 查看[EndpointCorsProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointCorsProperties.java)获取完整的配置选项列表。 diff --git a/V. Spring Boot Actuator/48.4 Adding custom endpoints.md b/V. Spring Boot Actuator/48.4 Adding custom endpoints.md deleted file mode 100644 index fa69d852..00000000 --- a/V. Spring Boot Actuator/48.4 Adding custom endpoints.md +++ /dev/null @@ -1,4 +0,0 @@ -###48.4 添加自定义端点 -如果添加一个`Endpoint`类型的`@Bean`,Spring Boot会自动通过JMX和HTTP(如果有可用服务器)将该端点暴露出去。通过创建`MvcEndpoint`类型的bean可进一步定义HTTP端点,虽然该bean不是`@Controller`,但仍能使用`@RequestMapping`(和`@Managed*`)暴露资源。 - -**注** 如果你的用户需要一个单独的管理端口或地址,你可以将注解`@ManagementContextConfiguration`的配置类添加到`/META-INF/spring.factories`中,且key为`org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration`,这样该端点将跟其他MVC端点一样移动到一个子上下文中,通过`WebConfigurerAdapter`可以为管理端点添加静态资源。 diff --git a/V. Spring Boot Actuator/48.5 Health information.md b/V. Spring Boot Actuator/48.5 Health information.md deleted file mode 100644 index a31bcdb1..00000000 --- a/V. Spring Boot Actuator/48.5 Health information.md +++ /dev/null @@ -1,4 +0,0 @@ -### 48.5 健康信息 -健康信息可以检查应用的运行状态,它经常被监控软件用来提醒人们生产环境是否存在问题。`health`端点暴露的默认信息取决于端点是如何被访问的。对于一个非安全,未认证的连接只返回一个简单的'status'信息。对于一个安全或认证过的连接其他详细信息也会展示(具体参考[章节49.7, “HTTP健康端点形式和访问限制” ](49.7. HTTP health endpoint format and access restrictions.md))。 - -健康信息是从你的`ApplicationContext`中定义的所有[HealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java) beans收集过来的。Spring Boot包含很多自动配置的`HealthIndicators`,你也可以写自己的。 diff --git a/V. Spring Boot Actuator/48.6 Security with HealthIndicators.md b/V. Spring Boot Actuator/48.6 Security with HealthIndicators.md deleted file mode 100644 index 38187328..00000000 --- a/V. Spring Boot Actuator/48.6 Security with HealthIndicators.md +++ /dev/null @@ -1,4 +0,0 @@ -### 48.6 安全与HealthIndicators -`HealthIndicators`返回的信息通常有点敏感,例如,你可能不想将数据库服务器的详情发布到外面。因此,在使用一个未认证的HTTP连接时,默认只会暴露健康状态(health status)。如果想将所有的健康信息暴露出去,你可以把`endpoints.health.sensitive`设置为`false`。 - -为防止'拒绝服务'攻击,Health响应会被缓存,你可以使用`endpoints.health.time-to-live`属性改变默认的缓存时间(1000毫秒)。 diff --git a/V. Spring Boot Actuator/48.6.1 Auto-configured-HealthIndicators.md b/V. Spring Boot Actuator/48.6.1 Auto-configured-HealthIndicators.md deleted file mode 100644 index 7e07c112..00000000 --- a/V. Spring Boot Actuator/48.6.1 Auto-configured-HealthIndicators.md +++ /dev/null @@ -1,18 +0,0 @@ -### 48.6.1 自动配置的HealthIndicators - -Spring Boot在合适的时候会自动配置以下`HealthIndicators`: - -|名称|描述| -|----|:-----| -|[`CassandraHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CassandraHealthIndicator.java)|检查Cassandra数据库状况| -|[`DiskSpaceHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java)|低磁盘空间检查| -|[`DataSourceHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java)|检查是否能从`DataSource`获取连接| -|[`ElasticsearchHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicator.java)|检查Elasticsearch集群状况| -|[`JmsHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java)|检查JMS消息代理状况| -|[`MailHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MailHealthIndicator.java)|检查邮件服务器状况| -|[`MongoHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MongoHealthIndicator.java)|检查Mongo数据库状况| -|[`RabbitHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MongoHealthIndicator.java)|检查Rabbit服务器状况| -|[`RedisHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java)|检查Redis服务器状况| -|[`SolrHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/SolrHealthIndicator.java)|检查Solr服务器状况| - -**注** 使用`management.health.defaults.enabled`属性可以禁用以上全部`HealthIndicators`。 diff --git a/V. Spring Boot Actuator/48.6.2 Writing custom HealthIndicators.md b/V. Spring Boot Actuator/48.6.2 Writing custom HealthIndicators.md deleted file mode 100644 index fe5b6bcc..00000000 --- a/V. Spring Boot Actuator/48.6.2 Writing custom HealthIndicators.md +++ /dev/null @@ -1,33 +0,0 @@ -### 48.6.2 编写自定义HealthIndicators -你可以注册实现[HealthIndicator](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java)接口的Spring beans来提供自定义健康信息。你需要实现`health()`方法,并返回一个`Health`响应,该响应需要包含一个`status`和其他用于展示的详情。 -```java -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.stereotype.Component; - -@Component -public class MyHealth 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`的标识是bean name去掉`HealthIndicator`后缀剩下的部分。在以上示例中,可以在`my`的实体中获取健康信息。 - -除Spring Boot预定义的[`Status`](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java)类型,`Health`也可以返回一个代表新的系统状态的自定义`Status`。在这种情况下,你需要提供一个[`HealthAggregator`](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthAggregator.java)接口的自定义实现,或使用`management.health.status.order`属性配置默认实现。 - -例如,假设一个新的,代码为`FATAL`的`Status`被用于你的一个`HealthIndicator`实现中。为了配置严重性级别,你需要将以下配置添加到application属性文件中: -```properties -management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP -``` -在回应中的HTTP状态码反映了全体的健康状况(例如,`UP`映射到200,`OUT_OF_SERVICE`或者`DOWN`映射到503)。如果使用HTTP访问health端点,你可能想要注册自定义的status,并使用`HealthMvcEndpoint`进行映射。例如,你可以将`FATAL`映射为`HttpStatus.SERVICE_UNAVAILABLE`。 -例如,如下将`FATAL`映射到`HttpStatus.SERVICE_UNAVAILABLE`: -```properties -endpoints.health.mapping.FATAL=503 -``` diff --git a/V. Spring Boot Actuator/48.7 Application information.md b/V. Spring Boot Actuator/48.7 Application information.md deleted file mode 100644 index ed8873f7..00000000 --- a/V. Spring Boot Actuator/48.7 Application information.md +++ /dev/null @@ -1,2 +0,0 @@ -###48.7 应用信息 -应用信息会暴露所有[`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoContributor.java) beans收集的各种信息,Spring Boot包含很多自动配置的`InfoContributors`,你也可以编写自己的实现。 diff --git a/V. Spring Boot Actuator/48.7.1 Auto-configured InfoContributors.md b/V. Spring Boot Actuator/48.7.1 Auto-configured InfoContributors.md deleted file mode 100644 index c8f5af9e..00000000 --- a/V. Spring Boot Actuator/48.7.1 Auto-configured InfoContributors.md +++ /dev/null @@ -1,10 +0,0 @@ -###48.7.1 自动配置的InfoContributors -Spring Boot会在合适的时候自动配置以下`InfoContributors`: - -|名称|描述| -|:----|:----| -|[`EnvironmentInfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/EnvironmentInfoContributor.java)|暴露`Environment`中key为`info`的所有key| -|[`GitInfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java)|暴露git信息,如果存在`git.properties`文件| -|[`BuildInfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/BuildInfoContributor.java)|暴露构建信息,如果存在`META-INF/build-info.properties`文件| - -**注** 使用`management.info.defaults.enabled`属性可禁用以上所有`InfoContributors`。 diff --git a/V. Spring Boot Actuator/48.7.2 Custom application info information.md b/V. Spring Boot Actuator/48.7.2 Custom application info information.md deleted file mode 100644 index c86fefc0..00000000 --- a/V. Spring Boot Actuator/48.7.2 Custom application info information.md +++ /dev/null @@ -1,14 +0,0 @@ -### 48.7.2 自定义应用info信息 - -通过设置Spring属性`info.*`,你可以定义`info`端点暴露的数据。所有在`info`关键字下的`Environment`属性都将被自动暴露,例如,你可以将以下配置添加到`application.properties`: -```properties -info.app.encoding=UTF-8 -info.app.java.source=1.8 -info.app.java.target=1.8 -``` -**注** 你可以[在构建时扩展info属性](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-automatic-expansion),而不是硬编码这些值。假设使用Maven,你可以按以下配置重写示例: -```properties -info.app.encoding=@project.build.sourceEncoding@ -info.app.java.source=@java.version@ -info.app.java.target=@java.version@ -``` diff --git a/V. Spring Boot Actuator/48.7.3 Git commit information.md b/V. Spring Boot Actuator/48.7.3 Git commit information.md deleted file mode 100644 index 1e3a8ec6..00000000 --- a/V. Spring Boot Actuator/48.7.3 Git commit information.md +++ /dev/null @@ -1,9 +0,0 @@ -### 48.7.3 Git提交信息 -`info`端点的另一个有用特性是,在项目构建完成后发布`git`源码仓库的状态信息。如果`GitProperties` bean可用,Spring Boot将暴露`git.branch`,`git.commit.id`和`git.commit.time`属性。 - -**注** 如果classpath根目录存在`git.properties`文件,Spring Boot将自动配置`GitProperties` bean。查看[Generate git information](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-git-info)获取更多详细信息。 - -使用`management.info.git.mode`属性可展示全部git信息(比如`git.properties`全部内容): -```properties -management.info.git.mode=full -``` diff --git a/V. Spring Boot Actuator/48.7.4 Build information.md b/V. Spring Boot Actuator/48.7.4 Build information.md deleted file mode 100644 index 412814f6..00000000 --- a/V. Spring Boot Actuator/48.7.4 Build information.md +++ /dev/null @@ -1,4 +0,0 @@ -###48.7.4 构建信息 -如果`BuildProperties` bean存在,`info`端点也会发布你的构建信息。 - -**注** 如果classpath下存在`META-INF/build-info.properties`文件,Spring Boot将自动构建`BuildProperties` bean。Maven和Gradle都能产生该文件,具体查看[Generate build information](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-build-info)。 diff --git a/V. Spring Boot Actuator/48.7.5 Writing custom InfoContributors.md b/V. Spring Boot Actuator/48.7.5 Writing custom InfoContributors.md deleted file mode 100644 index 914db6ba..00000000 --- a/V. Spring Boot Actuator/48.7.5 Writing custom InfoContributors.md +++ /dev/null @@ -1,28 +0,0 @@ -###48.7.5 编写自定义的InfoContributors -你可以注册实现了[`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoContributor.java)接口的Spring beans来提供自定义应用信息。以下示例暴露一个只有单个值的`example`实体: -```java -import java.util.Collections; - -import org.springframework.boot.actuate.info.Info; -import org.springframework.boot.actuate.info.InfoContributor; -import org.springframework.stereotype.Component; - -@Component -public class ExampleInfoContributor implements InfoContributor { - - @Override - public void contribute(Info.Builder builder) { - builder.withDetail("example", - Collections.singletonMap("key", "value")); - } - -} -``` -如果点击`info`端点,你应该可以看到包含以下实体的响应: -```json -{ - "example": { - "key" : "value" - } -} -``` diff --git a/V. Spring Boot Actuator/49. Enabling Production-ready Features.md b/V. Spring Boot Actuator/49. Enabling Production-ready Features.md new file mode 100644 index 00000000..1df28896 --- /dev/null +++ b/V. Spring Boot Actuator/49. Enabling Production-ready Features.md @@ -0,0 +1,21 @@ +### 49. 开启用于生产环境的特性 + +[spring-boot-actuator](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator)模块提供Spring Boot所有的用于生产环境的特性,启用该特性的最简单方式是添加`spring-boot-starter-actuator`“Starter依赖。 + +**执行器(Actuator)的定义**:执行器是一个制造业术语,指的是用于移动或控制东西的一个机械装置,一个很小的改变就能让执行器产生大量的运动。 + +按以下配置为Maven项目添加执行器: +```xml + + + org.springframework.boot + spring-boot-starter-actuator + + +``` +对于Gradle,使用下面的声明: +```java +dependencies { + compile("org.springframework.boot:spring-boot-starter-actuator") +} +``` diff --git a/V. Spring Boot Actuator/49. Monitoring and management over HTTP.md b/V. Spring Boot Actuator/49. Monitoring and management over HTTP.md deleted file mode 100644 index 568b1e01..00000000 --- a/V. Spring Boot Actuator/49. Monitoring and management over HTTP.md +++ /dev/null @@ -1,3 +0,0 @@ -### 49. 基于HTTP的监控和管理 - -如果你正在开发一个Spring MVC应用,Spring Boot执行器自动将所有启用的端点通过HTTP暴露出去。默认约定使用端点的`id`加上前缀`/application`作为URL路径,例如,`health`暴露为`/application/health`。 diff --git a/V. Spring Boot Actuator/49.1 Accessing sensitive endpoints.md b/V. Spring Boot Actuator/49.1 Accessing sensitive endpoints.md deleted file mode 100644 index 554b5099..00000000 --- a/V. Spring Boot Actuator/49.1 Accessing sensitive endpoints.md +++ /dev/null @@ -1,29 +0,0 @@ -### 49.1 访问敏感端点 - -默认地,所有敏感的HTTP端点受到保护,只有角色为`ACTUATOR`的用户可以访问它们。通过使用标准的`HttpServletRequest.isUserInRole`方法确保了安全。 - -**提示** 如果想要与`ACTUATOR`不同,使用`management.security.roles`属性 - -如果你正在防火墙后面部署应用,你可能更喜欢所有的执行器端点不需要验证就可以访问。你可以通过改变`management.security.enabled`属性来实现: - -**application.properties.** -```properties -management.security.enabled=false -``` -**注** 默认地,执行器端点暴露在同一个服务常规HTTP传输的端口之下。如果你改变了`management.security.enabled`属性,小心不要意外暴露了敏感信息。 - -如果你正在公开地部署应用,你可能会想加上‘Spring Security’来处理用户认证。当你加上了‘Spring Security’, 默认情况下会使用用户名为`user`的基本认证(basic authentication),产生的密码会在应用启动时打印到控制台上。 - -**注** 在应用启动时会记录生成的密码,具体搜索`Using default security password`。 - -你可以使用Spring属性改变用户名,密码和访问端点需要的安全角色。例如,你可以将以下配置添加到`application.properties`中: -```java -security.user.name=admin -security.user.password=secret -management.security.role=SUPERUSER -``` -如果你的应用有自定义的安全配置,而且你想要所有的执行器端点不需要验证就可以访问,你需要明确地在你的安全配置中配置。除此之外,你需要将`management.security.enabled`属性改为`false`。 - -如果你自定义的安全配置保护了你的执行器端点,你也需要确认验证过的用户拥有`management.security.roles`下指定的角色。 - -**注** 如果你没有一种使用情况要将基本的健康信息暴露给未经身份验证的用户,而且你已经通过自定义安全保护了执行器端点,你可以将`management.security.enabled`设置为`false`。这将会通知Spring Boot跳过另外的角色检查。 diff --git a/V. Spring Boot Actuator/49.2 Customizing the management endpoint paths.md b/V. Spring Boot Actuator/49.2 Customizing the management endpoint paths.md deleted file mode 100644 index 7a62e74a..00000000 --- a/V. Spring Boot Actuator/49.2 Customizing the management endpoint paths.md +++ /dev/null @@ -1,12 +0,0 @@ -### 49.2 自定义管理端点路径 -有时给管理端点自定义前缀是有用的。例如,`/application`可能已被应用占用,你可以用`management.context-path`属性来改变管理端点的前缀: -```java -management.context-path=/manage -``` -以上的`application.properties`示例将把端点从`/application/{id}`改为`/manage/{id}`(比如`/manage/info`)。 - -你也可以改变端点的`path`(使用`endpoints.{name}.path`)来改变MVC端点的默认资源路径。Spring Boot不会校验这些值(所以你可以使用URL中任何合法的字符)。例如,想要改变`/health`端点路径为`/ping/me`,你可以设置`endpoints.health.path=/ping/me`。 - -**注** 即使端点路径是分开配置的,仍旧与`management.context-path`相关。 - -**提醒** 如果你提供一个自定义`MvcEndpoint`,记得包含一个可设置的`path`属性,并像标准MVC端点那样将该属性默认设置为`/{id}`(具体可参考`HealthMvcEndpoint`)。如果你的自定义端点是一个`Endpoint`(不是`MvcEndpoint`),Spring Boot将会为你分配路径。 diff --git a/V. Spring Boot Actuator/49.3 Customizing the management server port.md b/V. Spring Boot Actuator/49.3 Customizing the management server port.md deleted file mode 100644 index d3a018a3..00000000 --- a/V. Spring Boot Actuator/49.3 Customizing the management server port.md +++ /dev/null @@ -1,10 +0,0 @@ -### 49.3 自定义管理服务器端口 -对于基于云的部署,使用默认的HTTP端口暴露管理端点(endpoints)是明智的选择。然而,如果你的应用是在自己的数据中心运行,那你可能倾向于使用一个不同的HTTP端口来暴露端点。`management.port`属性可以用来改变HTTP端口: -```java -management.port=8081 -``` -由于你的管理端口经常被防火墙保护,不对外暴露也就不需要保护管理端点,即使你的主应用是受保护的。在这种情况下,classpath下会存在Spring Security库,你可以设置以下属性来禁用安全管理策略(management security): -```java -management.security.enabled=false -``` -(如果classpath下不存在Spring Security,那也就不需要显式的以这种方式来禁用安全管理策略,它甚至可能会破坏应用程序。) diff --git a/V. Spring Boot Actuator/49.4 Configuring management-specific SSL.md b/V. Spring Boot Actuator/49.4 Configuring management-specific SSL.md deleted file mode 100644 index 9998cb35..00000000 --- a/V. Spring Boot Actuator/49.4 Configuring management-specific SSL.md +++ /dev/null @@ -1,21 +0,0 @@ -###49.4 配置管理相关的SSL -当配置使用一个自定义端口时,管理服务器可以通过各种`management.ssl.*`属性配置自己的SSL。例如,以下配置允许通过HTTP访问管理服务器,通过HTTPS访问主应用: -```properties -server.port=8443 -server.ssl.enabled=true -server.ssl.key-store=classpath:store.jks -server.ssl.key-password=secret -management.port=8080 -management.ssl.enabled=false -``` -或者,主应用服务器和管理服务器都使用SSL,但key stores不一样: -```properties -server.port=8443 -server.ssl.enabled=true -server.ssl.key-store=classpath:main.jks -server.ssl.key-password=secret -management.port=8080 -management.ssl.enabled=true -management.ssl.key-store=classpath:management.jks -management.ssl.key-password=secret -``` diff --git a/V. Spring Boot Actuator/49.5 Customizing the management server address.md b/V. Spring Boot Actuator/49.5 Customizing the management server address.md deleted file mode 100644 index b39ab192..00000000 --- a/V. Spring Boot Actuator/49.5 Customizing the management server address.md +++ /dev/null @@ -1,10 +0,0 @@ -### 49.5 自定义管理服务器地址 -你可以通过设置`management.address`属性来定义管理端点使用的地址,这在你只想监听内部或面向生产环境的网络,或只监听来自`localhost`的连接时非常有用。 - -**注** 如果端口跟主应用服务器不一样,你只能监听一个不同的地址。 - -下面的application.properties示例不允许远程访问管理服务器: -```java -management.port=8081 -management.address=127.0.0.1 -``` diff --git a/V. Spring Boot Actuator/49.6 Disabling HTTP endpoints.md b/V. Spring Boot Actuator/49.6 Disabling HTTP endpoints.md deleted file mode 100644 index 2eec811f..00000000 --- a/V. Spring Boot Actuator/49.6 Disabling HTTP endpoints.md +++ /dev/null @@ -1,4 +0,0 @@ -### 49.6 禁用HTTP端点 - -如果不想通过HTTP暴露端点,你可以将管理端口设置为-1: -`management.port=-1` diff --git a/V. Spring Boot Actuator/49.7 HTTP Health endpoint access restrictions.md b/V. Spring Boot Actuator/49.7 HTTP Health endpoint access restrictions.md deleted file mode 100644 index 9fa4b2e7..00000000 --- a/V. Spring Boot Actuator/49.7 HTTP Health endpoint access restrictions.md +++ /dev/null @@ -1,54 +0,0 @@ -### 49.7 HTTP health端点访问限制 -`health`端点暴露的信息依赖于是否为匿名访问,应用是否受保护。默认情况下,当匿名访问一个受保护的应用时,任何有关服务器的健康详情都被隐藏了,该端点只简单的展示服务器运行状况(up或down)。此外,响应会被缓存一个可配置的时间段以防止端点被用于'拒绝服务'攻击,你可以通过`endpoints.health.time-to-live`属性设置缓存时间(单位为毫秒),默认为1000毫秒,也就是1秒。 - -概括了HTTP请求的样本(默认对于匿名请求): -```shell -$ curl -i localhost:8080/health -HTTP/1.1 200 -X-Application-Context: application -Content-Type: application/vnd.spring-boot.actuator.v2+json;charset=UTF-8 -Content-Length: 15 - -{"status":"UP"} -``` -概括了对于状态“DOWN”的HTTP请求的样本(注意状态码503): -```shell -$ curl -i localhost:8080/health -HTTP/1.1 503 -X-Application-Context: application -Content-Type: application/vnd.spring-boot.actuator.v2+json;charset=UTF-8 -Content-Length: 17 - -{"status":"DOWN"} -``` -详细的HTTP请求样本: -```shell -$ curl -i localhost:8080/health -HTTP/1.1 200 OK -X-Application-Context: application -Content-Type: application/vnd.spring-boot.actuator.v2+json;charset=UTF-8 -Content-Length: 221 - -{ - "status" : "UP", - "diskSpace" : { - "status" : "UP", - "total" : 63251804160, - "free" : 31316164608, - "threshold" : 10485760 - }, - "db" : { - "status" : "UP", - "database" : "H2", - "hello" : 1 - } -} -``` -你可以增强上述限制,从而只允许认证用户完全访问一个受保护应用的`health`端点,将`endpoints.health.sensitive`设为`true`可以实现该效果,具体可查看以下总结(`sensitive`标识值为"false"的默认加粗): - -|`management.security.enabled`|`endpoints.health.sensitive`|未认证|认证(有正确的角色)| -|:----|:----|:----|:-----| -|false|*|全部内容|全部内容| -|true|**false**|只能查看Status|全部内容| -|true|true|不能查看任何内容|全部内容| - diff --git a/V. Spring Boot Actuator/50. Endpoints.md b/V. Spring Boot Actuator/50. Endpoints.md new file mode 100644 index 00000000..94620600 --- /dev/null +++ b/V. Spring Boot Actuator/50. Endpoints.md @@ -0,0 +1,37 @@ +### 50. 端点 + +执行器端点(endpoints)可用于监控应用及与应用进行交互,Spring Boot包含很多内置的端点,你也可以添加自己的。例如,`health`端点提供了应用的基本健康信息。 +可以单独[启用或禁用](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-endpoints-enabling-endpoints)每个端点。这决定了端点是否已经创建并且在应用上下文里存在它的bean。[通过JMX或者HTTP暴露的](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-endpoints-enabling-endpoints)端点可以被远程访问。大部分应用选择HTTP监控,端点的ID连同前缀`/actuator`映射到一个URL。例如,`health`端点默认映射到`/actuator/health`。 + +下面的端点都是可用的: + +| ID | 描述 |是否默认启用| +| ---- | :----- | :----- | +|`auditevents`|为当前应用暴露审计事件的信息|Yes| +|`beans`|显示一个应用中所有Spring Bean的完整列表|Yes| +|`conditions`|展示依据配置和自动配置类评估的条件,以及它们匹配或者不匹配的原因|Yes| +|`configprops`|显示一个所有`@ConfigurationProperties`的集合列表|Yes| +|`env`|暴露来自Spring `ConfigurableEnvironment`的属性|Yes| +|`flyway`|显示数据库迁移路径,如果有的话|Yes| +|`health`|展示应用健康信息|Yes| +|`httptrace`|显示HTTP跟踪信息(默认的,最后的100个HTTP请求-响应交换)|Yes| +|`info`|显示任意的应用信息|Yes| +|`loggers`|显示和修改应用中的记录器的配置|Yes| +|`liquibase`|展示任何Liquibase数据库迁移路径,如果有的话|Yes| +|`metrics`|展示当前应用的'metrics'信息|Yes| +|`mappings`|显示一个所有`@RequestMapping`路径的集合列表|Yes| +|`scheduledtasks`|显示应用里的计划任务|Yes| +|`sessions`|允许从Spring Session的会话存储,检索和删除用户会话。当为响应式网络应用使用Spring Session支持时,不可用|Yes| +|`shutdown`|允许应用以优雅的方式关闭|No| +|`threaddump`|执行线程转储|Yes| + +如果你的应用是一个网络应用(Spring MVC、Spring WebFlux或者Jersey),你可以使用以下额外的端点: + +| ID | 描述 |是否默认启用| +| ---- | :----- | :----- | +|`heapdump`|返回一个GZip压缩的`hprof`堆转储文件|Yes| +|`jolokia`|通过HTTP暴露JMX bean(当Jolokia在类路径上,对WebFlux不可用)|Yes| +|`logfile`|返回日志文件内容(如果设置了`logging.file`或`logging.path`属性),支持使用HTTP `Range`头接收日志文件内容的部分信息|Yes| +|`prometheus`|用一种可以被Prometheus服务器下载的格式暴露度量指标|Yes| + +请参考单独的API文档([HTML](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/actuator-api//html)或者[PDF](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/actuator-api//pdf/spring-boot-actuator-web-api.pdf)),学习更多有关执行器端点和它们的请求与响应的格式。 diff --git a/V. Spring Boot Actuator/50. Monitoring and management over JMX.md b/V. Spring Boot Actuator/50. Monitoring and management over JMX.md deleted file mode 100644 index 1dd2c5bb..00000000 --- a/V. Spring Boot Actuator/50. Monitoring and management over JMX.md +++ /dev/null @@ -1,3 +0,0 @@ -### 50. 基于JMX的监控和管理 - -Java管理扩展(JMX)提供了一种标准的监控和管理应用的机制。默认情况下,Spring Boot在`org.springframework.boot`域下将管理端点暴露为JMX MBeans。 diff --git a/V. Spring Boot Actuator/50.1 Customizing MBean names.md b/V. Spring Boot Actuator/50.1 Customizing MBean names.md deleted file mode 100644 index 23658f72..00000000 --- a/V. Spring Boot Actuator/50.1 Customizing MBean names.md +++ /dev/null @@ -1,9 +0,0 @@ -### 50.1 自定义MBean名称 -MBean的名称通常产生于端点的id,例如,`health`端点被暴露为`org.springframework.boot/Endpoint/healthEndpoint`。 - -如果应用包含多个Spring `ApplicationContext`,你会发现存在名称冲突。为了解决这个问题,你可以将`endpoints.jmx.uniqueNames`设置为`true`,这样MBean的名称总是唯一的。 - -你也可以自定义端点暴露的JMX域,具体可参考以下`application.properties`示例: -```properties -endpoints.jmx.domain=myapp -endpoints.jmx.uniqueNames=true diff --git a/V. Spring Boot Actuator/50.1 Enabling Endpoints.md b/V. Spring Boot Actuator/50.1 Enabling Endpoints.md new file mode 100644 index 00000000..298528ef --- /dev/null +++ b/V. Spring Boot Actuator/50.1 Enabling Endpoints.md @@ -0,0 +1,12 @@ +### 50.1 启用端点 + +默认的,除了`shutdown`,所有端点都是启用的。使用`management.endpoint..enabled`属性,启用端点。下面的示例启用了`shutdown`端点: +```java +management.endpoint.shutdown.enabled=true +``` +如果相比选择性退出,你更喜欢选择性加入端点启用,将`management.endpoints.enabled-by-default`属性设置为`false`,并使用独立的端点`enabled`属性。下面的示例启用了`info`端点,禁用了所有其它端点: +```java +management.endpoints.enabled-by-default=false +management.endpoint.info.enabled=true +``` +**注** 禁用的端点会完全从应用上下文中移除。如果你想改变端点暴露的技术,使用[`include`与`exclude`属性](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-endpoints-exposing-endpoints)代替。 diff --git a/V. Spring Boot Actuator/50.10 Application Information.md b/V. Spring Boot Actuator/50.10 Application Information.md new file mode 100644 index 00000000..a64c0524 --- /dev/null +++ b/V. Spring Boot Actuator/50.10 Application Information.md @@ -0,0 +1,3 @@ +### 50.10 应用信息 + +应用信息会暴露所有[`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoContributor.java) bean收集的各种信息。Spring Boot包含很多自动配置的`InfoContributor` bean,你也可以编写自己的实现。 diff --git a/V. Spring Boot Actuator/50.10.1 Auto-configured InfoContributors.md b/V. Spring Boot Actuator/50.10.1 Auto-configured InfoContributors.md new file mode 100644 index 00000000..5da1205b --- /dev/null +++ b/V. Spring Boot Actuator/50.10.1 Auto-configured InfoContributors.md @@ -0,0 +1,11 @@ +### 50.10.1 自动配置的InfoContributor + +Spring Boot会在合适的时候自动配置以下`InfoContributor` bean: + +|名称|描述| +|:----|:----| +|[`EnvironmentInfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/EnvironmentInfoContributor.java)|暴露`Environment`中key为`info`的所有key| +|[`GitInfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java)|暴露git信息,如果存在`git.properties`文件| +|[`BuildInfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/BuildInfoContributor.java)|暴露构建信息,如果存在`META-INF/build-info.properties`文件| + +**注** 使用`management.info.defaults.enabled`属性可禁用以上所有`InfoContributor` bean。 diff --git a/V. Spring Boot Actuator/50.10.2 Custom Application Information.md b/V. Spring Boot Actuator/50.10.2 Custom Application Information.md new file mode 100644 index 00000000..b11eefd3 --- /dev/null +++ b/V. Spring Boot Actuator/50.10.2 Custom Application Information.md @@ -0,0 +1,14 @@ +### 50.10.2 自定义应用信息 + +通过设置Spring属性`info.*`,你可以定义`info`端点暴露的数据。所有在`info`关键字下的`Environment`属性都将被自动暴露。例如,你可以将以下配置添加到`application.properties`文件: +```properties +info.app.encoding=UTF-8 +info.app.java.source=1.8 +info.app.java.target=1.8 +``` +**注** 你可以[在构建时扩展info属性](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-automatic-expansion),而不是硬编码这些值。假设使用Maven,你可以按以下配置重写示例: +```properties +info.app.encoding=@project.build.sourceEncoding@ +info.app.java.source=@java.version@ +info.app.java.target=@java.version@ +``` diff --git a/V. Spring Boot Actuator/50.10.3 Git Commit Information.md b/V. Spring Boot Actuator/50.10.3 Git Commit Information.md new file mode 100644 index 00000000..b344f38d --- /dev/null +++ b/V. Spring Boot Actuator/50.10.3 Git Commit Information.md @@ -0,0 +1,10 @@ +### 50.10.3 Git提交信息 + +`info`端点的另一个有用特性是,在项目构建完成后发布`git`源码仓库的状态信息。如果`GitProperties` bean可用,Spring Boot将暴露`git.branch`,`git.commit.id`和`git.commit.time`属性。 + +**注** 如果classpath根目录存在`git.properties`文件,Spring Boot将自动配置`GitProperties` bean。查看[Generate git information](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-git-info)获取更多详细信息。 + +使用`management.info.git.mode`属性可展示全部git信息(比如`git.properties`全部内容): +```properties +management.info.git.mode=full +``` diff --git a/V. Spring Boot Actuator/50.10.4 Build Information.md b/V. Spring Boot Actuator/50.10.4 Build Information.md new file mode 100644 index 00000000..46bbe3a2 --- /dev/null +++ b/V. Spring Boot Actuator/50.10.4 Build Information.md @@ -0,0 +1,5 @@ +### 50.10.4 构建信息 + +如果`BuildProperties` bean存在,`info`端点也会发布你的构建信息。 + +**注** 如果classpath下存在`META-INF/build-info.properties`文件,Spring Boot将自动构建`BuildProperties` bean。Maven和Gradle都能产生该文件,具体查看[Generate build information](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-build-info)。 diff --git a/V. Spring Boot Actuator/50.10.5 Writing Custom InfoContributors.md b/V. Spring Boot Actuator/50.10.5 Writing Custom InfoContributors.md new file mode 100644 index 00000000..1b4e7f26 --- /dev/null +++ b/V. Spring Boot Actuator/50.10.5 Writing Custom InfoContributors.md @@ -0,0 +1,29 @@ +### 50.10.5 编写自定义的InfoContributor + +你可以注册实现了[`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoContributor.java)接口的Spring bean,来提供自定义应用信息。以下示例暴露一个只有单个值的`example`实体: +```java +import java.util.Collections; + +import org.springframework.boot.actuate.info.Info; +import org.springframework.boot.actuate.info.InfoContributor; +import org.springframework.stereotype.Component; + +@Component +public class ExampleInfoContributor implements InfoContributor { + + @Override + public void contribute(Info.Builder builder) { + builder.withDetail("example", + Collections.singletonMap("key", "value")); + } + +} +``` +如果到达`info`端点,你应该可以看到包含以下实体的响应: +```json +{ + "example": { + "key" : "value" + } +} +``` diff --git a/V. Spring Boot Actuator/50.2 Disabling JMX endpoints.md b/V. Spring Boot Actuator/50.2 Disabling JMX endpoints.md deleted file mode 100644 index 640fa722..00000000 --- a/V. Spring Boot Actuator/50.2 Disabling JMX endpoints.md +++ /dev/null @@ -1,5 +0,0 @@ -### 50.2 禁用JMX端点 -如果不想通过JMX暴露端点,你可以将`endpoints.jmx.enabled`属性设置为`false`: -```java -endpoints.jmx.enabled=false -``` diff --git a/V. Spring Boot Actuator/50.2 Exposing Endpoints.md b/V. Spring Boot Actuator/50.2 Exposing Endpoints.md new file mode 100644 index 00000000..fbe29033 --- /dev/null +++ b/V. Spring Boot Actuator/50.2 Exposing Endpoints.md @@ -0,0 +1,52 @@ +### 50.2 暴露端点 + +由于端点可能包含敏感信息,暴露它们要慎重。下面的表格展示了内建端点默认是否展示的情况: + +| ID | JMX |Web| +| ---- | :----- | :----- | +|`auditevents`|Yes|No| +|`beans`|Yes|No| +|`conditions`|Yes|No| +|`configprops`|Yes|No| +|`env`|Yes|No| +|`flyway`|Yes|No| +|`health`|Yes|Yes| +|`heapdump`|N/A|No| +|`httptrace`|Yes|No| +|`info`|Yes|Yes| +|`jolokia`|N/A|No| +|`logfile`|N/A|No| +|`loggers`|Yes|No| +|`liquibase`|Yes|No| +|`metrics`|Yes|No| +|`mappings`|Yes|No| +|`prometheus`|N/A|No| +|`scheduledtasks`|Yes|No| +|`sessions`|Yes|No| +|`shutdown`|Yes|No| +|`threaddump`|Yes|No| + +使用下面技术特定的`include`和`exclude`属性,改变端点的暴露状况: + +| 属性 | 默认 | +| ---- | :----- | +|`management.endpoints.jmx.exposure.exclude`|| +|`management.endpoints.jmx.exposure.include`|`*`| +|`management.endpoints.web.exposure.exclude`|| +|`management.endpoints.web.exposure.include`|`info, health`| + +`include`属性列出了暴露的端点ID。`exclude`属性列出了不应当暴露的端点ID。`exclude`属性优先于`include`属性。`include`和`exclude`属性都可以使用端点ID列表配置。 + +例如,为了停止暴露所有JMX端点,只暴露`health`和`info`端点,使用下面的属性: +```properties +management.endpoints.jmx.exposure.include=health,info +``` +`*`可以用于选择所有端点。例如,为了暴露所有HTTP端点,但是不暴露`env`和`beans`端点,使用下面的属性: +```properties +management.endpoints.web.exposure.include=* +management.endpoints.web.exposure.exclude=env,beans +``` + +**注** 如果你的应用公开暴露,我们强烈推荐你[加密端点](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-endpoints-security). + +**注** 如果你想实现自己的何时暴露端点的策略,你可以注册一个`EndpointFilter` bean。 diff --git a/V. Spring Boot Actuator/50.3 Securing HTTP Endpoints.md b/V. Spring Boot Actuator/50.3 Securing HTTP Endpoints.md new file mode 100644 index 00000000..572102b5 --- /dev/null +++ b/V. Spring Boot Actuator/50.3 Securing HTTP Endpoints.md @@ -0,0 +1,40 @@ +### 50.3 加密HTTP端点 + +你应当采取与处理其它敏感的URL相同的方式,加密HTTP端点。如果存在Spring Security,端点会默认用Spring Security的内容协商策略加密。如果你要为HTTP端点配置自定义的安全,例如,只允许某一角色的用户访问它们,Spring Boot提供了一些方便的`RequestMatcher`对象。它们可以与Spring Security结合使用。 + +典型的Spring Security配置可能类似于下面的例子: +```java +@Configuration +public class ActuatorSecurity extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() + .anyRequest().hasRole("ENDPOINT_ADMIN") + .and() + .httpBasic(); + } + +} +``` +之前的例子使用`EndpointRequest.toAnyEndpoint()`将请求匹配端点,然后确保所有请求都有`ENDPOINT_ADMIN`角色。另外几个匹配器方法也可以用于`EndpointRequest`。详情请查看API文档([HTML](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/actuator-api//html)或者[PDF](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/actuator-api//pdf/spring-boot-actuator-web-api.pdf))。 + +如果你在防火墙后面部署应用,你可能更喜欢不需要验证,你所有的执行器端点就能被访问。你可以改变`management.endpoints.web.exposure.include`属性,达到这种效果。如下所示: + +**application.properties.** +```properties +management.endpoints.web.exposure.include=* +``` +另外,如果Spring Security存在,你需要添加自定义的安全配置,来允许未验证的访问。如下所示: +```java +@Configuration +public class ActuatorSecurity extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() + .anyRequest().permitAll() + } + +} +``` diff --git a/V. Spring Boot Actuator/50.3 Using Jolokia for JMX over HTTP.md b/V. Spring Boot Actuator/50.3 Using Jolokia for JMX over HTTP.md deleted file mode 100644 index 1c63c730..00000000 --- a/V. Spring Boot Actuator/50.3 Using Jolokia for JMX over HTTP.md +++ /dev/null @@ -1,9 +0,0 @@ -### 50.3 使用Jolokia通过HTTP实现JMX远程管理 -Jolokia是一个JMX-HTTP桥,它提供了一种访问JMX beans的替代方法。想要使用Jolokia,只需添加`org.jolokia:jolokia-core`的依赖。例如,使用Maven需要添加以下配置: -```xml - - org.jolokia - jolokia-core - -``` -然后在你的管理HTTP服务器上可以通过`/jolokia`访问Jolokia。 diff --git a/V. Spring Boot Actuator/50.3.1 Customizing Jolokia.md b/V. Spring Boot Actuator/50.3.1 Customizing Jolokia.md deleted file mode 100644 index 8a94a6b7..00000000 --- a/V. Spring Boot Actuator/50.3.1 Customizing Jolokia.md +++ /dev/null @@ -1,5 +0,0 @@ -### 50.3.1 自定义Jolokia -Jolokia有很多配置,通常使用servlet参数进行设置,跟Spring Boot一块使用时可以在`application.properties`中添加`jolokia.config.`前缀的属性进行配置: -```java -jolokia.config.debug=true -``` diff --git a/V. Spring Boot Actuator/50.3.2 Disabling Jolokia.md b/V. Spring Boot Actuator/50.3.2 Disabling Jolokia.md deleted file mode 100644 index f69a190e..00000000 --- a/V. Spring Boot Actuator/50.3.2 Disabling Jolokia.md +++ /dev/null @@ -1,5 +0,0 @@ -### 50.3.2 禁用Jolokia -如果正在使用Jolokia,又不想让Spring Boot配置它,你只需要简单的将`endpoints.jolokia.enabled`属性设置为`false`: -```java -endpoints.jolokia.enabled=false -``` diff --git a/V. Spring Boot Actuator/50.4 Configuring Endpoints.md b/V. Spring Boot Actuator/50.4 Configuring Endpoints.md new file mode 100644 index 00000000..d045ffec --- /dev/null +++ b/V. Spring Boot Actuator/50.4 Configuring Endpoints.md @@ -0,0 +1,12 @@ +### 50.4 配置端点 + +端点自动缓存不带任何参数的读取操作的响应。使用`cache.time-to-live`属性,配置端点缓存响应的时间。下面的例子将`beans`端点的缓存的存活时间设置为10秒: + +**application.properties.** +```properties +management.endpoint.beans.cache.time-to-live=10s +``` + +**注** 前缀`management.endpoint.`用于唯一确定一个端点。 + +**注** 当发送一个经过验证的HTTP请求时,`Principal`会被当做端点的输入,因此,响应不会被缓存。 diff --git a/V. Spring Boot Actuator/50.5 Hypermedia for Actuator Web Endpoints.md b/V. Spring Boot Actuator/50.5 Hypermedia for Actuator Web Endpoints.md new file mode 100644 index 00000000..d98f3857 --- /dev/null +++ b/V. Spring Boot Actuator/50.5 Hypermedia for Actuator Web Endpoints.md @@ -0,0 +1,5 @@ +### 50.5 执行器网络端点的超媒体支持 + +一个“发现页”会带着链接加到所有端点。该页面默认可用,路径为`/actuator`。 + +当指定了一个自定义管理上下文路径时,“发现页”路径自动从`/actuator`迁移到管理上下文根目录。例如,如果管理上下文路径为`/management`,那就可以通过`/management`访问“发现页”。当管理上下文路径设置为`/`时,为了防止和其它映射发生冲突,发现页会被禁用。 diff --git a/V. Spring Boot Actuator/50.6 Actuator Web Endpoint Paths.md b/V. Spring Boot Actuator/50.6 Actuator Web Endpoint Paths.md new file mode 100644 index 00000000..881bb41d --- /dev/null +++ b/V. Spring Boot Actuator/50.6 Actuator Web Endpoint Paths.md @@ -0,0 +1,11 @@ +### 50.6 执行器网络端点路径 + +默认的,端点使用其ID,通过HTTP暴露在`/actuator`下。例如,`beans`端点暴露在`/actuator/beans`下面。如果你想要将端点映射到不同的路径,你可以使用`management.endpoints.web.path-mapping`属性。同样的,如果你需要修改基础路径,你可以使用`management.endpoints.web.base-path`。 + +下面的例子将`/actuator/health`重映射为`/healthcheck`: + +**application.properties.** +```properties +management.endpoints.web.base-path=/ +management.endpoints.web.path-mapping.health=healthcheck +``` diff --git a/V. Spring Boot Actuator/50.7 CORS Support.md b/V. Spring Boot Actuator/50.7 CORS Support.md new file mode 100644 index 00000000..7c0b1c02 --- /dev/null +++ b/V. Spring Boot Actuator/50.7 CORS Support.md @@ -0,0 +1,11 @@ +### 50.7 CORS支持 + +[跨域资源共享](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)(CORS)是一个[W3C规范](https://www.w3.org/TR/cors/),用于以灵活的方式指定跨域请求的认证类型。如果你使用Spring MVC或者Spring WebFlux,执行器的网络端点也可以配置成支持该场景。 + +CORS支持默认是禁用的,只有在`management.endpoints.web.cors.allowed-origins`属性设置时才启用。以下配置允许来自`example.com`域的`GET`和`POST`调用: +```properties +management.endpoints.web.cors.allowed-origins=http://example.com +management.endpoints.web.cors.allowed-methods=GET,POST +``` + +**注** 查看[CorsEndpointProperties](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/CorsEndpointProperties.java)获取完整的配置选项列表。 diff --git a/V. Spring Boot Actuator/50.8 Implementing Custom Endpoints.md b/V. Spring Boot Actuator/50.8 Implementing Custom Endpoints.md new file mode 100644 index 00000000..a2934865 --- /dev/null +++ b/V. Spring Boot Actuator/50.8 Implementing Custom Endpoints.md @@ -0,0 +1,11 @@ +### 50.8 实现自定义端点 + +如果你添加一个用`@Endpoint`标注的`@Bean`,任何用`@ReadOperation`、`@WriteOperation`或者`@DeleteOperation`标注的方法都会自动通过JMX暴露,在网络应用里则会通过HTTP暴露。使用Jersey、Spring MVC或者Spring WebFlux时,端点会通过HTTP暴露。 + +你也可以使用`@JmxEndpoint`或者`@WebEndpoint`,编写技术特定的端点。这些端点受到对应技术的限制。比如,`@WebEndpoint`只能通过HTTP暴露,不能通过JMX暴露。 + +你可以使用`@EndpointWebExtension`或者`@EndpointJmxExtension`编写技术特定的扩展。这些注解让你提供技术特定的操作,来声明一个既存的端点。 + +最后,如果你需要访问网络框架特定的功能,你可以实现Servlet或者Spring `@Controller`和`@RestController`端点。但是,它们将不能通过JMX暴露,也不能用于另外的网络框架。 + +**注** 如果你添加端点作为一个库特性,考虑将一个用`@ManagementContextConfiguration`标注的配置类添加到`/META-INF/spring.factories`中,且key为`org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration`。这样,如果你的用户要求一个独立的管理端口或地址,端点将跟其它网络端点一样移动到一个子上下文中。 diff --git a/V. Spring Boot Actuator/50.8.1 Receiving Input.md b/V. Spring Boot Actuator/50.8.1 Receiving Input.md new file mode 100644 index 00000000..08b81e68 --- /dev/null +++ b/V. Spring Boot Actuator/50.8.1 Receiving Input.md @@ -0,0 +1,9 @@ +### 50.8.1 接收输入 + +在一个端点上的操作会通过它们的参数接收数据。当该端点通过网络暴露的时候,这些参数的值取自URL查询参数和JSON请求体。当该端点通过JMX暴露的时候,这些参数会映射到MBean操作的参数上。参数默认必需。但是,它们可以通过标注`@org.springframework.lang.Nullable`成为可选项。 + +**注** 为了允许输入映射到操作方法的参数上,实现端点的代码应该带上`-parameters`编译。如果你正在使用Spring Boot的Gradle插件,或是Maven和`spring-boot-starter-parent`,这会自动发生。 + +**输入类型转换** + +如果需要,传递到端点操作方法的参数会自动转换到需要的类型。在调用操作方法之前,通过JMX或者HTTP请求接收的输入会使用`ApplicationConversionService`的实例转换到需要的类型。 diff --git a/V. Spring Boot Actuator/50.8.2 Custom Web Endpoints.md b/V. Spring Boot Actuator/50.8.2 Custom Web Endpoints.md new file mode 100644 index 00000000..c906a888 --- /dev/null +++ b/V. Spring Boot Actuator/50.8.2 Custom Web Endpoints.md @@ -0,0 +1,53 @@ +### 50.8.2 自定义网络端点 + +在`@Endpoint`、`@WebEndpoint`或者`@WebEndpointExtension`上的操作会自动使用Jersey、Spring MVC或者Spring WebFlux通过HTTP暴露。 + +**网络端点请求谓语** + +请求谓语会在网络暴露的端点上,为每一个操作自动产生。 + +**路径** + +谓语的路径由端点的ID以及网络暴露的基础路径所决定。默认的基础路径是`/actuator`。比如,ID为`sessions`的端点会使用`/actuator/sessions`,作为它在谓语里的路径。 + +路径可以通过使用`@Selector`标注一个或者更多的操作方法参数,进一步自定义。这样的一个参数会添加进路径谓语,作为一个路径变量。当端点操作被调用时,变量值会传入操作方法。 + +**HTTP方法** + +谓语的HTTP方法由操作类型所决定。如下所示: + +| 操作 | HTTP方法 | +| ---- | :----- | +|`@ReadOperation`|`GET`| +|`@WriteOperation`|`POST`| +|`@DeleteOperation`|`DELETE`| + +**Consumes** + +对于使用请求体的`@WriteOperation`(HTTP `POST`),谓语的consumes子句是`application/vnd.spring-boot.actuator.v2+json, application/json`。对于其它所有的操作,consumes子句是空的。 + +**Produces** + +谓语的produces子句由`@DeleteOperation`、`@ReadOperation`和`@WriteOperation`注解的`produces`属性所决定。这个属性是可选的。如果它没被使用,produces子句会被自动决定。 + +如果操作方法返回`void`或者`Void`,produces子句是空的。如果操作方法返回`org.springframework.core.io.Resource`,produces子句`application/octet-stream`。对于其它所有的操作,produces子句是`application/vnd.spring-boot.actuator.v2+json, application/json`。 + +**网络端点响应状态** + +端点操作的默认响应状态取决于操作类型(读取、写入或者删除)。 + +`@ReadOperation`返回一个值,响应状态将会是200(OK)。如果没有返回一个值,响应状态将会是404(没有找到)。 + +如果`@WriteOperation`或者`@DeleteOperation`返回一个值,响应状态将会是200(OK)。如果没有返回一个值,响应状态将会是204(没有内容)。 + +如果一个操作被调用了,但是没有需要的参数,或者参数无法转换成需要的类型,操作方法将不会被调用,响应状态将会是400(错误请求)。 + +**网络端点范围请求** + +HTTP范围请求可以用于请求HTTP资源的一部分。当使用Spring MVC或者Spring Web Flux时,返回`org.springframework.core.io.Resource`的操作自动支持范围请求。 + +**注** 使用Jersey时,范围请求不被支持。 + +**网络端点安全** + +在网络端点或是网络特定端点扩展上的操作会收到`urrent java.security.Principal`或者`org.springframework.boot.actuate.endpoint.SecurityContext`,作为一个方法参数。前者典型地和`@Nullable`结合使用,来为认证用户和未认证用户提供不同的行为。后者使用它的`isUserInRole(String)`方法,典型地用于执行权限检查。 diff --git a/V. Spring Boot Actuator/50.8.3 Servlet endpoints.md b/V. Spring Boot Actuator/50.8.3 Servlet endpoints.md new file mode 100644 index 00000000..e6f05c32 --- /dev/null +++ b/V. Spring Boot Actuator/50.8.3 Servlet endpoints.md @@ -0,0 +1,3 @@ +### 50.8.3 Servlet端点 + +通过实现一个用`@ServletEndpoint`注解的类,`Servlet`可以暴露为一个端点。该类还实现了`Supplier`。Servlet端点提供了与Servlet容器更深层次的集成,但是暴露了可移植性。它们用于将现有`Servlet`暴露为端点。对于新的端点,只要可能,就应该首选`@Endpoint`和`@WebEndpoint`注解。 diff --git a/V. Spring Boot Actuator/50.8.4 Controller endpoints.md b/V. Spring Boot Actuator/50.8.4 Controller endpoints.md new file mode 100644 index 00000000..7b36cce2 --- /dev/null +++ b/V. Spring Boot Actuator/50.8.4 Controller endpoints.md @@ -0,0 +1,3 @@ +### 50.8.4 Controller端点 + +`@ControllerEndpoint`和`@RestControllerEndpoint`可用于实现仅由Spring MVC或Spring WebFlux暴露的端点。方法使用标准注解Spring MVC和Spring WevFlux注解(如`@RequestMapping`和`@GetMapping`)进行映射,端点的ID用作路径的前缀。Controller端点提供了与Spring的web框架更深入的集成,但这是以可移植性为代价的。只要可能,应该首选`@Endpoint`和`@WebEndpoint`注解。 diff --git a/V. Spring Boot Actuator/50.9 Health Information.md b/V. Spring Boot Actuator/50.9 Health Information.md new file mode 100644 index 00000000..00cbe295 --- /dev/null +++ b/V. Spring Boot Actuator/50.9 Health Information.md @@ -0,0 +1,15 @@ +### 50.9 健康信息 + +你可以使用健康信息来检查应用的运行状态。它经常被监控软件用来提醒人们生产环境是否存在问题。`health`端点暴露的信息取决于`management.endpoint.health.show-details`属性。该属性可以使用下列值配置: + +| 名称 | 描述 | +| ---- | :----- | +|`never`|不展示细节| +|`when-authorized`|只对授权用户展示细节。可以使用`management.endpoint.health.roles`配置授权用户| +|`always`|对所有用户展示细节| + +默认值是`never`。当用户有一到多个端点角色时,就认为用户已经授权。如果端点没有配置角色(默认),就认为所有验证用户已经授权。可以使用`management.endpoint.health.roles`属性配置角色。 + +**注** 如果你已经加密了你的应用,并且想要使用`always`,你的加密配置必须允许所有用户访问健康端点。 + +健康信息是从你的`ApplicationContext`中定义的所有[HealthIndicator](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java) beans收集过来的。Spring Boot包含很多自动配置的`HealthIndicators`,你也可以写自己的。默认的,最终的系统状态来自于`HealthAggregator`。它会基于一个状态的有序列表,排序来自每一个`HealthIndicator`的状态。有序列表里的头一个状态会用作全体的健康状态。如果`HealthIndicator`返回的状态都无法被`HealthAggregator`识别, 则会使用`UNKNOWN`状态。 diff --git a/V. Spring Boot Actuator/50.9.1 Auto-configured HealthIndicators.md b/V. Spring Boot Actuator/50.9.1 Auto-configured HealthIndicators.md new file mode 100644 index 00000000..b6bd2a6d --- /dev/null +++ b/V. Spring Boot Actuator/50.9.1 Auto-configured HealthIndicators.md @@ -0,0 +1,20 @@ +### 50.9.1 自动配置的HealthIndicator + +Spring Boot在合适的时候会自动配置以下`HealthIndicators`: + +|名称|描述| +|----|:-----| +|[`CassandraHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra/CassandraHealthIndicator.java)|检查Cassandra数据库状况| +|[`DiskSpaceHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java)|低磁盘空间检查| +|[`DataSourceHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jdbc/DataSourceHealthIndicator.java)|检查是否能从`DataSource`获取连接| +|[`ElasticsearchHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicator.java)|检查Elasticsearch集群状况| +|[`InfluxDbHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicator.java)|检查InfluxDB服务器状况| +|[`JmsHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java)|检查JMS消息代理状况| +|[`MailHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mail/MailHealthIndicator.java)|检查邮件服务器状况| +|[`MongoHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mongo/MongoHealthIndicator.java)|检查Mongo数据库状况| +|[`Neo4jHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java)|检查Neo4j服务器状况| +|[`RabbitHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java)|检查Rabbit服务器状况| +|[`RedisHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisHealthIndicator.java)|检查Redis服务器状况| +|[`SolrHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/solr/SolrHealthIndicator.java)|检查Solr服务器状况| + +**注** 使用`management.health.defaults.enabled`属性可以禁用以上全部`HealthIndicators`。 diff --git a/V. Spring Boot Actuator/50.9.2 Writing Custom HealthIndicators.md b/V. Spring Boot Actuator/50.9.2 Writing Custom HealthIndicators.md new file mode 100644 index 00000000..332cdb5c --- /dev/null +++ b/V. Spring Boot Actuator/50.9.2 Writing Custom HealthIndicators.md @@ -0,0 +1,44 @@ +### 50.9.2 编写自定义HealthIndicator + +你可以注册实现[HealthIndicator](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java)接口的Spring beans来提供自定义健康信息。你需要实现`health()`方法,并返回一个`Health`响应,该响应需要包含一个`status`和其他用于展示的详情。下面的代码展示了一个`HealthIndicator`实现类的例子: +```java +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +@Component +public class MyHealth 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`的标识是bean name去掉`HealthIndicator`后缀剩下的部分。在以上示例中,可以在`my`的实体中获取健康信息。 + +除Spring Boot预定义的[`Status`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java)类型,`Health`也可以返回一个代表新的系统状态的自定义`Status`。在这种情况下,你需要提供一个[`HealthAggregator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthAggregator.java)接口的自定义实现,或使用`management.health.status.order`属性配置默认实现。 + +例如,假设一个新的,代码为`FATAL`的`Status`被用于你的一个`HealthIndicator`实现中。为了配置严重性级别,你需要将以下配置添加到application属性文件中: +```properties +management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP +``` +在回应中的HTTP状态码反映了全体的健康状况(例如,`UP`映射到200,`OUT_OF_SERVICE`和`DOWN`映射到503)。如果使用HTTP访问health端点,你可能想要注册自定义的status。例如,你可以将`FATAL`映射为503(服务不可用)。 +```properties +management.health.status.http-mapping.FATAL=503 +``` + +**注** 如果你需要更多的控制,你可以定义你自己的`HealthStatusHttpMapper`bean。 + +下面的表格展示了内建状态的默认状态映射: + +|状态|映射| +|----|:-----| +|DOWN|SERVICE_UNAVAILABLE (503)| +|OUT_OF_SERVICE|SERVICE_UNAVAILABLE (503)| +|UP|默认无映射,所以http状态是200| +|UNKNOWN|默认无映射,所以http状态是200| diff --git a/V. Spring Boot Actuator/50.9.3 Reactive Health Indicators.md b/V. Spring Boot Actuator/50.9.3 Reactive Health Indicators.md new file mode 100644 index 00000000..5c988fc7 --- /dev/null +++ b/V. Spring Boot Actuator/50.9.3 Reactive Health Indicators.md @@ -0,0 +1,19 @@ +### 50.9.3 响应式的健康指示器 + +对于响应式应用程序,例如那些使用Spring WebFlux的应用程序,`ReactiveHealthIndicator`提供了一个非阻塞契约来获得应用程序的健康状态。与传统的`HealthIndicator`类似,健康信息收集自`ApplicationContext`中定义的所有[`ReactiveHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthIndicator.java) bean。不检查响应式API的常规`HealthIndicator`bean包含在弹性调度器中并在其上执行。 + +要从响应式API提供自定义健康信息,你可以注册实现[`ReactiveHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthIndicator.java)接口的Spring bean。下面的代码显示了一个示例`ReactiveHealthIndicator`实现: +``` +@Component +public class MyReactiveHealthIndicator implements ReactiveHealthIndicator { + + @Override + public Mono health() { + return doHealthCheck() //perform some specific health check that returns a Mono + .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build()))); + } + +} +``` + +**注** 要自动处理错误,可以考虑从`AbstractReactiveHealthIndicator`扩展。 diff --git a/V. Spring Boot Actuator/50.9.4 Auto-configured ReactiveHealthIndicators.md b/V. Spring Boot Actuator/50.9.4 Auto-configured ReactiveHealthIndicators.md new file mode 100644 index 00000000..f9582f14 --- /dev/null +++ b/V. Spring Boot Actuator/50.9.4 Auto-configured ReactiveHealthIndicators.md @@ -0,0 +1,10 @@ +### 50.9.4 自动配置的ReactiveHealthIndicator + +以下`ReactiveHealthIndicator`是由Spring Boot在适当的时候自动配置的: + +|名称|描述| +|----|:-----| +|[`MongoReactiveHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicator.java)|检查Mongo数据库是否已启动| +|[`RedisReactiveHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicator.java)|检查Redis服务器是否已启动| + +**注** 如有必要,响应式指标会取代常规指标。此外,任何未显式处理的`HealthIndicator`都会自动包装。 diff --git a/V. Spring Boot Actuator/51. Loggers.md b/V. Spring Boot Actuator/51. Loggers.md deleted file mode 100644 index 38c3651f..00000000 --- a/V. Spring Boot Actuator/51. Loggers.md +++ /dev/null @@ -1,14 +0,0 @@ -### 51. 记录器 - -Spring Boot执行器可以在运行时查看和配置你的应用的记录器级别。你可以查看整个的列表或者单个的记录器配置。单个的记录器配置由明确配置的日志级别和日志框架提供的有效日志级别组成。这些级别是: - -* `TRACE` -* `DEBUG` -* `INFO` -* `WARN` -* `ERROR` -* `FATAL` -* `OFF` -* `null` - -`null`表明没有明确的配置。 \ No newline at end of file diff --git a/V. Spring Boot Actuator/51. Monitoring and Management over HTTP.md b/V. Spring Boot Actuator/51. Monitoring and Management over HTTP.md new file mode 100644 index 00000000..48a10a89 --- /dev/null +++ b/V. Spring Boot Actuator/51. Monitoring and Management over HTTP.md @@ -0,0 +1,5 @@ +### 51. 基于HTTP的监控和管理 + +如果你正在开发一个网络应用,Spring Boot执行器自动将所有启用的端点通过HTTP暴露出去。默认约定使用端点的`id`加上前缀`/actuator`作为URL路径。例如,`health`暴露为`/actuator/health`。 + +**注** Spring MVC、Spring WebFlux和Jersey对执行器提供了原生支持。 diff --git a/V. Spring Boot Actuator/51.1 Configure a Logger.md b/V. Spring Boot Actuator/51.1 Configure a Logger.md deleted file mode 100644 index 47028efd..00000000 --- a/V. Spring Boot Actuator/51.1 Configure a Logger.md +++ /dev/null @@ -1,9 +0,0 @@ -### 51.1 配置记录器 - -为了配置一个特定的记录器,你向资源的URI`POST`一个部分的实体: -```properties -{ - "configuredLevel": "DEBUG" -} -``` -**提示** 你也可以传递一个`null`的`配置级别`来“重置”记录器的特定的级别(使用默认的配置)。 diff --git a/V. Spring Boot Actuator/51.1 Customizing the Management Endpoint Paths.md b/V. Spring Boot Actuator/51.1 Customizing the Management Endpoint Paths.md new file mode 100644 index 00000000..987315e9 --- /dev/null +++ b/V. Spring Boot Actuator/51.1 Customizing the Management Endpoint Paths.md @@ -0,0 +1,9 @@ +### 51.1 自定义管理端点路径 + +有时给管理端点自定义前缀是有用的。例如,`/actuator`可能已被应用占用,你可以用`management.endpoints.web.base-path`属性来改变管理端点的前缀。如下所示: +```java +management.endpoints.web.base-path=/manage +``` +以上的`application.properties`示例将把端点从`/actuator/{id}`改为`/manage/{id}`(比如,`/manage/info`)。 + +**注** `management.endpoints.web.base-path`相对于`server.servlet.context-path`,除非管理端口已经配置为[使用不同的HTTP端口暴露端点](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-customizing-management-server-port)。如果已经配置了`management.server.port`,`management.endpoints.web.base-path`相对于`management.server.servlet.context-path`。 diff --git a/V. Spring Boot Actuator/51.2 Customizing the Management Server Port.md b/V. Spring Boot Actuator/51.2 Customizing the Management Server Port.md new file mode 100644 index 00000000..68e9d8df --- /dev/null +++ b/V. Spring Boot Actuator/51.2 Customizing the Management Server Port.md @@ -0,0 +1,8 @@ +### 51.2 自定义管理服务器端口 + +对于基于云的部署,使用默认的HTTP端口暴露管理端点(endpoints)是明智的选择。然而,如果你的应用是在自己的数据中心运行,那你可能倾向于使用一个不同的HTTP端口来暴露端点。 + +你可以设置`management.server.port`属性,来改变HTTP端口。如下所示: +```java +management.server.port=8081 +``` diff --git a/V. Spring Boot Actuator/51.3 Configuring Management-specific SSL.md b/V. Spring Boot Actuator/51.3 Configuring Management-specific SSL.md new file mode 100644 index 00000000..96adaeba --- /dev/null +++ b/V. Spring Boot Actuator/51.3 Configuring Management-specific SSL.md @@ -0,0 +1,23 @@ +### 51.3 配置管理相关的SSL + +当配置使用一个自定义端口时,管理服务器可以通过各种`management.server.ssl.*`属性配置自己的SSL。例如,以下配置允许通过HTTP访问管理服务器,通过HTTPS访问主应用: +```properties +server.port=8443 +server.ssl.enabled=true +server.ssl.key-store=classpath:store.jks +server.ssl.key-password=secret +management.server.port=8080 +management.server.ssl.enabled=false +``` + +或者,主应用服务器和管理服务器都使用SSL,但key stores不一样: +```properties +server.port=8443 +server.ssl.enabled=true +server.ssl.key-store=classpath:main.jks +server.ssl.key-password=secret +management.server.port=8080 +management.server.ssl.enabled=true +management.server.ssl.key-store=classpath:management.jks +management.server.ssl.key-password=secret +``` diff --git a/V. Spring Boot Actuator/51.4 Customizing the Management Server Address.md b/V. Spring Boot Actuator/51.4 Customizing the Management Server Address.md new file mode 100644 index 00000000..852d7a83 --- /dev/null +++ b/V. Spring Boot Actuator/51.4 Customizing the Management Server Address.md @@ -0,0 +1,11 @@ +### 51.4 自定义管理服务器地址 + +你可以通过设置`management.server.address`属性来定义管理端点使用的地址,这在你只想监听内部或面向生产环境的网络,或只监听来自`localhost`的连接时非常有用。 + +**注** 当端口跟主应用服务器不一样时,你只能监听一个不同的地址。 + +下面的application.properties示例不允许远程访问管理服务器: +```java +management.server.port=8081 +management.server.address=127.0.0.1 +``` diff --git a/V. Spring Boot Actuator/51.5 Disabling HTTP Endpoints.md b/V. Spring Boot Actuator/51.5 Disabling HTTP Endpoints.md new file mode 100644 index 00000000..8e42f2ab --- /dev/null +++ b/V. Spring Boot Actuator/51.5 Disabling HTTP Endpoints.md @@ -0,0 +1,6 @@ +### 51.5 禁用HTTP端点 + +如果不想通过HTTP暴露端点,你可以将管理端口设置为`-1`。如下所示: +``` +management.server.port=-1 +``` diff --git a/V. Spring Boot Actuator/52. Metrics.md b/V. Spring Boot Actuator/52. Metrics.md deleted file mode 100644 index 3f76c402..00000000 --- a/V. Spring Boot Actuator/52. Metrics.md +++ /dev/null @@ -1,38 +0,0 @@ - -### 52. 度量指标(Metrics) -Spring Boot执行器包含一个支持'gauge'和'counter'级别的度量指标服务,'gauge'记录一个单一值,'counter'记录一个增量(增加或减少)。同时,Spring Boot提供一个[PublicMetrics](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/PublicMetrics.java)接口,你可以实现它,从而暴露以上两种机制不能记录的指标,具体参考[SystemPublicMetrics](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/SystemPublicMetrics.java)。 - -所有HTTP请求的指标都被自动记录,所以如果点击`metrics`端点,你可能会看到类似以下的响应: -```javascript -{ - "counter.status.200.root": 20, - "counter.status.200.metrics": 3, - "counter.status.200.star-star": 5, - "counter.status.401.root": 4, - "gauge.response.star-star": 6, - "gauge.response.root": 2, - "gauge.response.metrics": 3, - "classes": 5808, - "classes.loaded": 5808, - "classes.unloaded": 0, - "heap": 3728384, - "heap.committed": 986624, - "heap.init": 262144, - "heap.used": 52765, - "mem": 986624, - "mem.free": 933858, - "processors": 8, - "threads": 15, - "threads.daemon": 11, - "threads.peak": 15, - "uptime": 494836, - "instance.uptime": 489782, - "datasource.primary.active": 5, - "datasource.primary.usage": 0.25 -} -``` -此处,我们可以看到基本的`memory`,`heap`,`class loading`,`processor`和`thread pool`信息,连同一些HTTP指标。在该实例中,`root`('/'),`/metrics` URLs分别返回`20`次,`3`次`HTTP 200`响应,同时可以看到`root` URL返回了`4`次`HTTP 401`(unauthorized)响应。双星号(`star-star`)来自于被Spring MVC `/**`匹配到的请求(通常为静态资源)。 - -`gauge`展示了一个请求的最后响应时间,所以`root`的最后请求响应耗时`2毫秒`,`/metrics`耗时`3毫秒`。 - -**注** 在该示例中,我们实际是通过HTTP的`/metrics`路径访问该端点的,这也就是响应中出现`metrics`的原因。 diff --git a/V. Spring Boot Actuator/52. Monitoring and Management over JMX.md b/V. Spring Boot Actuator/52. Monitoring and Management over JMX.md new file mode 100644 index 00000000..9eb293da --- /dev/null +++ b/V. Spring Boot Actuator/52. Monitoring and Management over JMX.md @@ -0,0 +1,3 @@ +### 52. 基于JMX的监控和管理 + +Java管理扩展(JMX)提供了一种标准的监控和管理应用的机制。默认情况下,Spring Boot在`org.springframework.boot`域下将管理端点暴露为JMX MBean。 diff --git a/V. Spring Boot Actuator/52.1 Customizing MBean Names.md b/V. Spring Boot Actuator/52.1 Customizing MBean Names.md new file mode 100644 index 00000000..f7c61a4e --- /dev/null +++ b/V. Spring Boot Actuator/52.1 Customizing MBean Names.md @@ -0,0 +1,11 @@ +### 52.1 自定义MBean名称 + +MBean的名称通常产生于端点的`id`。例如,`health`端点被暴露为`org.springframework.boot:type=Endpoint,name=Health`。 + +如果应用包含多个Spring `ApplicationContext`,你会发现存在名称冲突。为了解决这个问题,你可以将`management.endpoints.jmx.unique-names`设置为`true`,这样MBean的名称总是唯一的。 + +你也可以自定义端点暴露的JMX域,具体可参考以下`application.properties`示例: +```properties +management.endpoints.jmx.domain=com.example.myapp +management.endpoints.jmx.unique-names=true +``` diff --git a/V. Spring Boot Actuator/52.1 System metrics.md b/V. Spring Boot Actuator/52.1 System metrics.md deleted file mode 100644 index 4192f45b..00000000 --- a/V. Spring Boot Actuator/52.1 System metrics.md +++ /dev/null @@ -1,12 +0,0 @@ -### 52.1 系统指标 -Spring Boot会暴露以下系统指标: -- 系统内存总量(`mem`),单位:KB -- 空闲内存数量(`mem.free`),单位:KB -- 处理器数量(`processors`) -- 系统正常运行时间(`uptime`),单位:毫秒 -- 应用上下文(应用实例)正常运行时间(`instance.uptime`),单位:毫秒 -- 系统平均负载(`systemload.average`) -- 堆信息(`heap`,`heap.committed`,`heap.init`,`heap.used`),单位:KB -- 线程信息(`threads`,`thread.peak`,`thead.daemon`) -- 类加载信息(`classes`,`classes.loaded`,`classes.unloaded`) -- 垃圾收集信息(`gc.xxx.count`, `gc.xxx.time`) diff --git a/V. Spring Boot Actuator/52.10 Message channel integration.md b/V. Spring Boot Actuator/52.10 Message channel integration.md deleted file mode 100644 index 1751deef..00000000 --- a/V. Spring Boot Actuator/52.10 Message channel integration.md +++ /dev/null @@ -1,2 +0,0 @@ -### 52.10 消息渠道集成 -如果存在名为`metricsChannel`的`MessageChannel` bean,Spring Boot将创建一个`MetricWriter`将指标写入该渠道(channel)。每一条传送到这个渠道的信息将会包含一个[Delta](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/actuate/metrics/writer/Delta.html)或者[Metric](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/actuate/metrics/Metric.html),同时有一个`metricName`标头。writer自动挂钩一个exporter,所以全部指标值都会出现在渠道上, 订阅者就可以进行其他分析或动作(提供渠道和订阅者取决于你)。 diff --git a/V. Spring Boot Actuator/52.2 DataSource metrics.md b/V. Spring Boot Actuator/52.2 DataSource metrics.md deleted file mode 100644 index 5fe3c941..00000000 --- a/V. Spring Boot Actuator/52.2 DataSource metrics.md +++ /dev/null @@ -1,11 +0,0 @@ -### 52.2 数据源指标 -Spring Boot会为应用中定义的每个支持的`DataSource`暴露以下指标: -- 活动连接数(`datasource.xxx.active`) -- 连接池当前使用情况(`datasource.xxx.usage`) - -所有数据源指标共用`datasoure.`前缀,该前缀适用于每个数据源: -- 如果是主数据源(唯一可用的数据源或注解`@Primary`的数据源)前缀为`datasource.primary`。 -- 如果数据源bean名称以`DataSource`结尾,前缀就是bean的名称去掉`DataSource`的部分(比如,`batchDataSource`的前缀是`datasource.batch`)。 -- 其他情况使用bean的名称作为前缀。 - -通过注册自定义版本的`DataSourcePublicMetrics` bean,你可以覆盖部分或全部的默认行为。Spring Boot默认提供支持所有数据源的元数据,如果喜欢的数据源恰好不被支持,你可以添加其他的`DataSourcePoolMetadataProvider` beans,具体参考`DataSourcePoolMetadataProvidersConfiguration`。 diff --git a/V. Spring Boot Actuator/52.2 Disabling JMX Endpoints.md b/V. Spring Boot Actuator/52.2 Disabling JMX Endpoints.md new file mode 100644 index 00000000..c23b344b --- /dev/null +++ b/V. Spring Boot Actuator/52.2 Disabling JMX Endpoints.md @@ -0,0 +1,6 @@ +### 52.2 禁用JMX端点 + +如果不想通过JMX暴露端点,你可以将`management.endpoints.jmx.exposure.exclude`属性设置为`*`: +```properties +management.endpoints.jmx.exposure.exclude=* +``` diff --git a/V. Spring Boot Actuator/52.3 Cache metrics.md b/V. Spring Boot Actuator/52.3 Cache metrics.md deleted file mode 100644 index dca3ed5b..00000000 --- a/V. Spring Boot Actuator/52.3 Cache metrics.md +++ /dev/null @@ -1,12 +0,0 @@ -###52.3 缓存指标 -Spring Boot会为应用中定义的每个支持的缓存暴露以下指标: -- cache当前大小(`cache.xxx.size`) -- 命中率(`cache.xxx.hit.ratio`) -- 丢失率(`cache.xxx.miss.ratio`) - -**注** 缓存提供商没有以一致的方式暴露命中/丢失率,有些暴露的是聚合(aggregated)值(比如,自从统计清理后的命中率),而其他暴露的是时序(temporal)值 -(比如,最后一秒的命中率),具体查看缓存提供商的文档。 - -如果两个不同的缓存管理器恰巧定义了相同的缓存,缓存name将以`CacheManager` bean的name作为前缀。 - -注册自定义版本的`CachePublicMetrics`可以部分或全部覆盖这些默认值,Spring Boot默认为EhCache,Hazelcast,Infinispan,JCache和Caffeine提供统计。如果喜欢的缓存库没被支持,你可以添加其他`CacheStatisticsProvider` beans,具体可参考`CacheStatisticsAutoConfiguration`。 diff --git a/V. Spring Boot Actuator/52.3 Using Jolokia for JMX over HTTP.md b/V. Spring Boot Actuator/52.3 Using Jolokia for JMX over HTTP.md new file mode 100644 index 00000000..4d14c99b --- /dev/null +++ b/V. Spring Boot Actuator/52.3 Using Jolokia for JMX over HTTP.md @@ -0,0 +1,11 @@ +### 52.3 使用Jolokia通过HTTP实现JMX远程管理 + +Jolokia是一个JMX-HTTP桥。它提供了一种访问JMX bean的替代方法。想要使用Jolokia,只需添加`org.jolokia:jolokia-core`的依赖。例如,使用Maven需要添加以下配置: +```xml + + org.jolokia + jolokia-core + +``` + +之后,通过将`jolokia`或者`*`添加到`management.endpoints.web.exposure.include`属性,暴露Jolokia端点。然后,在你的管理HTTP服务器上可以使用`/actuator/jolokia`访问Jolokia。 diff --git a/V. Spring Boot Actuator/52.3.1 Customizing Jolokia.md b/V. Spring Boot Actuator/52.3.1 Customizing Jolokia.md new file mode 100644 index 00000000..113b73d8 --- /dev/null +++ b/V. Spring Boot Actuator/52.3.1 Customizing Jolokia.md @@ -0,0 +1,6 @@ +### 52.3.1 自定义Jolokia + +Jolokia有很多配置,通常使用servlet参数进行设置。跟Spring Boot一块使用时可以在`application.properties`文件中添加`management.endpoint.jolokia.config.`前缀的属性进行配置: +```properties +management.endpoint.jolokia.config.debug=true +``` diff --git a/V. Spring Boot Actuator/52.3.2 Disabling Jolokia.md b/V. Spring Boot Actuator/52.3.2 Disabling Jolokia.md new file mode 100644 index 00000000..c2abe34b --- /dev/null +++ b/V. Spring Boot Actuator/52.3.2 Disabling Jolokia.md @@ -0,0 +1,6 @@ +### 52.3.2 禁用Jolokia + +如果正在使用Jolokia,又不想让Spring Boot配置它,你只需要简单的将`management.endpoint.jolokia.enabled`属性设置为`false`: +```properties +management.endpoint.jolokia.enabled=false +``` diff --git a/V. Spring Boot Actuator/52.4 Tomcat session metrics.md b/V. Spring Boot Actuator/52.4 Tomcat session metrics.md deleted file mode 100644 index 9fc36770..00000000 --- a/V. Spring Boot Actuator/52.4 Tomcat session metrics.md +++ /dev/null @@ -1,3 +0,0 @@ -### 52.4 Tomcat session指标 -如果你使用Tomcat作为内嵌的servlet容器,Spring Boot将自动暴露session指标, -`httpsessions.active`和`httpsessions.max`分别提供活动的和最大的session数量。 diff --git a/V. Spring Boot Actuator/52.5 Recording your own metrics.md b/V. Spring Boot Actuator/52.5 Recording your own metrics.md deleted file mode 100644 index 50939d07..00000000 --- a/V. Spring Boot Actuator/52.5 Recording your own metrics.md +++ /dev/null @@ -1,27 +0,0 @@ - -### 52.5 记录自己的指标 -将[CounterService](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/CounterService.java)或[GaugeService](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/GaugeService.java)注入到你的bean中可以记录自己的度量指标:`CounterService`暴露`increment`,`decrement`和`reset`方法;`GaugeService`提供一个`submit`方法。 - -下面是一个简单的示例,它记录了方法调用的次数: -```java -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.metrics.CounterService; -import org.springframework.stereotype.Service; - -@Service -public class MyService { - - private final CounterService counterService; - - @Autowired - public MyService(CounterService counterService) { - this.counterService = counterService; - } - - public void exampleMethod() { - this.counterService.increment("services.system.myservice.invoked"); - } - -} -``` -**注** 你可以将任何字符串用作度量指标的名称,但最好遵循所选存储/图形技术的指南,[Matt Aimonetti’s Blog](http://matt.aimonetti.net/posts/2013/06/26/practical-guide-to-graphite-monitoring/)中有一些好的关于Graphite的指南。 diff --git a/V. Spring Boot Actuator/52.6 Adding your own public metrics.md b/V. Spring Boot Actuator/52.6 Adding your own public metrics.md deleted file mode 100644 index 9c8b0c7e..00000000 --- a/V. Spring Boot Actuator/52.6 Adding your own public metrics.md +++ /dev/null @@ -1,2 +0,0 @@ -### 52.6 添加自己的公共指标 -只要注册其他的`PublicMetrics`实现beans,你就可以添加其他的度量指标,比如计算metrics端点每次调用的次数。默认情况下,端点会聚合所有这样的beans,通过定义自己的`MetricsEndpoint`可以轻易改变这种情况。 diff --git a/V. Spring Boot Actuator/52.7 Metric writers, exporters and aggregation.md b/V. Spring Boot Actuator/52.7 Metric writers, exporters and aggregation.md deleted file mode 100644 index d34c2aa9..00000000 --- a/V. Spring Boot Actuator/52.7 Metric writers, exporters and aggregation.md +++ /dev/null @@ -1,10 +0,0 @@ -###52.7 指标写入,导出和聚合 -Spring Boot提供几个标记接口`Exporter`的实现,可用于将从内存buffers读取的指标复制到一个分析和展示它们的地方。实际上,如果提供一个实现`MetricWriter`接口(或`GaugeWriter`用于简单场景)且注解`@ExportMetricWriter`的`@Bean`,它将自动挂钩一个`Exporter`并每5秒反馈下指标更新(通过`spring.metrics.export.delay-millis`配置)。此外,你定义的所有注解`@ExportMetricReader`的`MetricReader`,它们的值将被默认exporter导出。 - -**注** 这个特性会在你的应用中启用调度(`@EnableScheduling`)。如果你正在运行综合测试,这就会成为一个问题。因为你自己安排好的任务将会开始进行。你可以通过设置`spring.metrics.export.enabled`为`false`来禁用这个行为。 - -默认exporter是一个`MetricCopyExporter`,它会优化自己不去复制那些从上次调用以来没有变化的值(设置`spring.metrics.export.send-latest`标识可以关闭该优化)。注意Dropwizard `MetricRegistry`不支持时间戳,所以如果你使用Dropwizard指标服务,该优化是不起作用的(每次都会复制全部指标)。 - -通过`spring.metrics.export.*`属性可以设置导出的触发器(`delay-millis`,`includes`,`excludes`和`send-latest`),特殊`MetricWriters`的值可以通过`spring.metrics.export.triggers..*`设置,此处``是bean的名称(或匹配bean名称的表达式)。 - -**警告⚠️** 如果关闭默认的`MetricRepository`(比如使用Dropwizard指标服务),指标的自动导出将禁用。你可以通过声明自定义类型的`MetricReader`并注解`@ExportMetricReader`来获取相同功能。 diff --git a/V. Spring Boot Actuator/52.7.1 Export to Redis.md b/V. Spring Boot Actuator/52.7.1 Export to Redis.md deleted file mode 100644 index 18f94d0c..00000000 --- a/V. Spring Boot Actuator/52.7.1 Export to Redis.md +++ /dev/null @@ -1,23 +0,0 @@ -### 52.7.1 示例: 导出到Redis - -如果提供一个`RedisMetricRepository`类型的`@Bean`并注解`@ExportMetricWriter`,指标将导出到Redis缓存完成聚合。`RedisMetricRepository`有两个重要参数用于配置实现这样的目的:`prefix`和`key`(传递给构造器)。最好使用应用实例唯一的前缀(比如,使用一个随机值及应用的逻辑name,这样可以关联相同应用的其他实例)。“key”用来保持所有指标name的全局索引,所以它应该全局唯一,不管这对于你的应用意味着什么(比如,相同系统的两个实例可以共享一个Redis缓存,如果它们有不同的keys)。 - -示例: -```java -@Bean -@ExportMetricWriter -MetricWriter metricWriter(MetricExportProperties export) { - return new RedisMetricRepository(connectionFactory, - export.getRedis().getPrefix(), export.getRedis().getKey()); -} -``` -**application.properties.** -```properties -spring.metrics.export.redis.prefix: metrics.mysystem.${spring.application.name:application}.${random.value:0000} -spring.metrics.export.redis.key: keys.metrics.mysystem -``` -前缀最后由应用名和id组成,所以它可以用来标识具有相同逻辑名的processes分组。 - -**注** 设置`key`和`prefix`都是非常重要的。key用于所有的仓库操作,并可以被多个仓库共享。如果多个仓库共享一个key(比如你需要聚合它们的时候),你通常有一个只读“master”仓库,它有一个简短的但可辨识的前缀(比如`metrics.mysystem`),还有很多只写的仓库,这些仓库以master前缀开头(比如以上示例中为`metrics.mysystem.*`)。这样从一个"master"仓库读取所有keys是相当高效的,但使用较长的前缀读取一个子集就比较低效了(比如使用一个写仓库)。 - -**注** 以上示例使用`MetricExportProperties`去注入和提取key和前缀,这是Spring Boot提供的便利设施,用于配置合适的默认值,你也可以自己设值。 diff --git a/V. Spring Boot Actuator/52.7.2 Export to Open TSDB.md b/V. Spring Boot Actuator/52.7.2 Export to Open TSDB.md deleted file mode 100644 index 88af2cc3..00000000 --- a/V. Spring Boot Actuator/52.7.2 Export to Open TSDB.md +++ /dev/null @@ -1,21 +0,0 @@ -###52.7.2 示例: 导出到Open TSDB -如果提供一个`OpenTsdbGaugeWriter`类型的`@Bean`并注解`@ExportMetricWriter`,指标将导出到[Open TSDB ](http://opentsdb.net/)完成聚合。`OpenTsdbGaugeWriter`有一个`url`属性,你需要将它设置为Open TSDB的“/put”端点,比如`localhost:4242/api/put`。它还有个`namingStrategy`,你可以自定义或配置以使指标匹配服务器上你需要的数据结构。默认它只传递指标名作为Open TSDB指标名,添加`domain`标签(值为`org.springframework.metrics`)和`process`(值为命名策略的对象hash值)。因此,在运行应用并产生一些指标后,你可以在TSD UI查看这些指标(默认路径为`localhost:4242`)。 - -示例: -```shell -curl localhost:4242/api/query?start=1h-ago&m=max:counter.status.200.root -[ - { - "metric": "counter.status.200.root", - "tags": { - "domain": "org.springframework.metrics", - "process": "b968a76" - }, - "aggregateTags": [], - "dps": { - "1430492872": 2, - "1430492875": 6 - } - } -] -``` diff --git a/V. Spring Boot Actuator/52.7.3 Export to Statsd.md b/V. Spring Boot Actuator/52.7.3 Export to Statsd.md deleted file mode 100644 index ee093fb6..00000000 --- a/V. Spring Boot Actuator/52.7.3 Export to Statsd.md +++ /dev/null @@ -1,13 +0,0 @@ -###52.7.3 示例: 导出到Statsd - -想要将指标导出到Statsd,首先你需要确定添加了`com.timgroup:java-statsd-client`依赖(Spring Boot为它提供了依赖管理),然后将`spring.metrics.export.statsd.host`属性添加到`application.properties`文件中,连接将在`8125`端口建立,除非设置`spring.metrics.export.statsd.port`对默认值进行覆盖。使用`spring.metrics.export.statsd.prefix`可以设置自定义前缀,此外,你可以提供一个`StatsdMetricWriter`类型的`@Bean`并注解`@ExportMetricWriter`: -```java -@Value("${spring.application.name:application}.${random.value:0000}") -private String prefix = "metrics"; - -@Bean -@ExportMetricWriter -MetricWriter metricWriter() { - return new StatsdMetricWriter(prefix, "localhost", 8125); -} -``` diff --git a/V. Spring Boot Actuator/52.7.4 Export to JMX.md b/V. Spring Boot Actuator/52.7.4 Export to JMX.md deleted file mode 100644 index a9c82e52..00000000 --- a/V. Spring Boot Actuator/52.7.4 Export to JMX.md +++ /dev/null @@ -1,12 +0,0 @@ -###52.7.4 示例: 导出到JMX -如果提供一个`JmxMetricWriter`类型并注解`@ExportMetricWriter`的`@Bean`,指标将作为MBeans暴露到本地服务器(只要开启,Spring Boot JMX自动配置会提供`MBeanExporter`)。 - -示例: -```java -@Bean -@ExportMetricWriter -MetricWriter metricWriter(MBeanExporter exporter) { - return new JmxMetricWriter(exporter); -} -``` -每个指标都暴露为单独的MBean,你可以将`ObjectNamingStrategy`注入`JmxMetricWriter`来指定`ObjectNames`的格式。 diff --git a/V. Spring Boot Actuator/52.8 Aggregating metrics from multiple sources.md b/V. Spring Boot Actuator/52.8 Aggregating metrics from multiple sources.md deleted file mode 100644 index 13fa22a6..00000000 --- a/V. Spring Boot Actuator/52.8 Aggregating metrics from multiple sources.md +++ /dev/null @@ -1,29 +0,0 @@ -###52.8 聚合多个来源的指标 -Spring Boot提供一个`AggregateMetricReader`,用于合并来自不同物理来源的指标。具有相同逻辑指标的来源只需将指标加上以句号分隔的前缀发布出去,reader会聚合它们(通过截取指标名并丢掉前缀),计数器被求和,所有东西(比如gauges)都采用最近的值。 - -这非常有用,特别是当有多个应用实例反馈数据到中央仓库(比如Redis),并且你想展示结果。推荐将`MetricReaderPublicMetrics`结果连接到`/metrics`端点。 - -示例: -```java -@Autowired -private MetricExportProperties export; - -@Bean -public PublicMetrics metricsAggregate() { - return new MetricReaderPublicMetrics(aggregatesMetricReader()); -} - -private MetricReader globalMetricsForAggregation() { - return new RedisMetricRepository(this.connectionFactory, - this.export.getRedis().getAggregatePrefix(), this.export.getRedis().getKey()); -} - -private MetricReader aggregatesMetricReader() { - AggregateMetricReader repository = new AggregateMetricReader( - globalMetricsForAggregation()); - return repository; -} -``` -**注** 上面的示例使用`MetricExportProperties`注入和提取key和前缀,这是Spring Boot提供的便利设施,并且默认值是合适的,它们是在`MetricExportAutoConfiguration`中设置的。 - -**注** 上面的`MetricReaders`不是`@Beans`,也没注解`@ExportMetricReader`,因为它们只收集和分析来自其他仓库的数据,不需要暴露自己的值。 diff --git a/V. Spring Boot Actuator/52.9 Dropwizard Metrics.md b/V. Spring Boot Actuator/52.9 Dropwizard Metrics.md deleted file mode 100644 index a7fb93a1..00000000 --- a/V. Spring Boot Actuator/52.9 Dropwizard Metrics.md +++ /dev/null @@ -1,4 +0,0 @@ -### 52.9 Dropwizard指标 -当你声明对`io.dropwizard.metrics:metrics-core`的依赖时,Spring Boot会创建一个默认的`MetricRegistry` bean。如果需要自定义,你可以注册自己的`@Bean`实例。使用[Dropwizard ‘Metrics’ library](https://dropwizard.github.io/metrics/)的用户会发现Spring Boot指标自动发布到`com.codahale.metrics.MetricRegistry`,来自`MetricRegistry`的指标也自动暴露到`/metrics`端点。 - -使用Dropwizard指标时,默认的`CounterService`和`GaugeService`被`DropwizardMetricServices`替换,它是一个`MetricRegistry`的包装器(所以你可以`@Autowired`其中任意services,并像平常那么使用它)。通过使用恰当的前缀类型标记你的指标名可以创建特殊的Dropwizard指标服务(比如,gauges使用`timer.*`,`histogram.*`,counters使用`meter.*`)。 diff --git a/V. Spring Boot Actuator/53. Auditing.md b/V. Spring Boot Actuator/53. Auditing.md deleted file mode 100644 index 16023dca..00000000 --- a/V. Spring Boot Actuator/53. Auditing.md +++ /dev/null @@ -1,2 +0,0 @@ -### 53. 审计 -Spring Boot执行器有一个灵活的审计框架,一旦Spring Security处于活动状态(默认抛出'authentication success','failure'和'access denied'异常),它就会发布事件。这对于报告非常有用,同时可以基于认证失败实现一个锁定策略。为了自定义发布的安全事件,你可以提供自己的`AbstractAuthenticationAuditListener`,`AbstractAuthorizationAuditListener`实现。你也可以使用审计服务处理自己的业务事件。为此,你可以将存在的`AuditEventRepository`注入到自己的组件,并直接使用它,或者只是简单地通过Spring `ApplicationEventPublisher`发布`AuditApplicationEvent`(使用`ApplicationEventPublisherAware`)。 diff --git a/V. Spring Boot Actuator/53. Loggers.md b/V. Spring Boot Actuator/53. Loggers.md new file mode 100644 index 00000000..04f362d3 --- /dev/null +++ b/V. Spring Boot Actuator/53. Loggers.md @@ -0,0 +1,14 @@ +### 53. 记录器 + +Spring Boot执行器可以在运行时查看和配置你的应用的记录器级别。你可以查看整个的列表或者单个的记录器配置。单个的记录器配置由明确配置的日志级别和日志框架提供的有效日志级别组成。这些级别是: + +* `TRACE` +* `DEBUG` +* `INFO` +* `WARN` +* `ERROR` +* `FATAL` +* `OFF` +* `null` + +`null`表明没有明确的配置。 diff --git a/V. Spring Boot Actuator/53.1 Configure a Logger.md b/V. Spring Boot Actuator/53.1 Configure a Logger.md new file mode 100644 index 00000000..33a581ce --- /dev/null +++ b/V. Spring Boot Actuator/53.1 Configure a Logger.md @@ -0,0 +1,9 @@ +### 53.1 配置记录器 + +为了配置一个特定的记录器,你向资源的URI`POST`一个部分的实体: +```properties +{ + "configuredLevel": "DEBUG" +} +``` +**提示** 你也可以传递一个`null`的`配置级别`来“重置”记录器的特定的级别(使用默认的配置)。 diff --git a/V. Spring Boot Actuator/54. Metrics.md b/V. Spring Boot Actuator/54. Metrics.md new file mode 100644 index 00000000..a458a2cb --- /dev/null +++ b/V. Spring Boot Actuator/54. Metrics.md @@ -0,0 +1,18 @@ +### 54. 度量指标(Metrics) + +Spring Boot执行器为[Micrometer](https://micrometer.io/)提供了依赖管理和自动配置。Micrometer是一种应用度量外观。它支持许多的监控系统,包括: + +- [Atlas](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-atlas) +- [Datadog](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-datadog) +- [Ganglia](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-ganglia) +- [Graphite](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-graphite) +- [Influx](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-influx) +- [JMX](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-jmx) +- [New Relic](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-newrelic) +- [Prometheus](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-prometheus) +- [SignalFx](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-signalfx) +- [Simple (in-memory)](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-simple) +- [StatsD](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-statsd) +- [Wavefront](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-export-wavefront) + +**注** 请参考[文档](https://micrometer.io/docs),学习更多的Micrometer功能,特别是[概念章节](https://micrometer.io/docs/concepts)。 diff --git a/V. Spring Boot Actuator/54. Tracing.md b/V. Spring Boot Actuator/54. Tracing.md deleted file mode 100644 index e7c89292..00000000 --- a/V. Spring Boot Actuator/54. Tracing.md +++ /dev/null @@ -1,42 +0,0 @@ -### 54. 追踪(Tracing) - -对于所有的HTTP请求Spring Boot自动启用追踪,你可以查看`trace`端点获取最近100条请求的基本信息: -```javascript -[{ - "timestamp": 1394343677415, - "info": { - "method": "GET", - "path": "/trace", - "headers": { - "request": { - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", - "Connection": "keep-alive", - "Accept-Encoding": "gzip, deflate", - "User-Agent": "Mozilla/5.0 Gecko/Firefox", - "Accept-Language": "en-US,en;q=0.5", - "Cookie": "_ga=GA1.1.827067509.1390890128; ..." - "Authorization": "Basic ...", - "Host": "localhost:8080" - }, - "response": { - "Strict-Transport-Security": "max-age=31536000 ; includeSubDomains", - "X-Application-Context": "application:8080", - "Content-Type": "application/json;charset=UTF-8", - "status": "200" - } - } - } -},{ - "timestamp": 1394343684465, - ... -}] -``` -以下会默认包含在追踪里: - -|名称|描述| -|:----|:----| -|Request Headers|来自请求的Headers| -|Response Headers|来自响应的Headers| -|Cookies|来自request headers的`Cookie`和来自response headers的`Set-Cookie`| -|Errors|error属性(如果有的话)| -|Time Taken|服务请求花费的毫秒数| diff --git a/V. Spring Boot Actuator/54.1 Custom tracing.md b/V. Spring Boot Actuator/54.1 Custom tracing.md deleted file mode 100644 index 92336534..00000000 --- a/V. Spring Boot Actuator/54.1 Custom tracing.md +++ /dev/null @@ -1,4 +0,0 @@ -### 54.1 自定义追踪 -如果需要追踪其他事件,你可以注入[TraceRepository](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/TraceRepository.java)到你的Spring Beans中,`add`方法接收一个`Map`结构的参数,该数据将转换为JSON并被记录下来。 - -默认使用`InMemoryTraceRepository`存储最新的100个事件,如果需要扩充容量,你可以定义自己的`InMemoryTraceRepository`实例,甚至创建自己的`TraceRepository`实现。 diff --git a/V. Spring Boot Actuator/54.1 Getting started.md b/V. Spring Boot Actuator/54.1 Getting started.md new file mode 100644 index 00000000..8d285296 --- /dev/null +++ b/V. Spring Boot Actuator/54.1 Getting started.md @@ -0,0 +1,50 @@ +### 54.1 入门指南 + +Spring Boot会自动配置一个复合`MeterRegistry`,并为它在类路径上找到的每个受支持的实现向复合添加注册。在运行时类路径中依赖于`micrometer-registry-{system}`就足以让Spring Boot配置注册表。 + +大多数注册表都具有相同的特性。例如,即使Micrometer注册表实现位于类路径上,也可以禁用特定的注册表。例如,要禁用Datadog: +```properties +management.metrics.export.datadog.enabled=false +``` + +Spring Boot还会在`Metrics`类的全局静态复合注册表中添加任何自动配置的注册表,除非您明确告诉它不要: +```properties +management.metrics.use-global-registry=false +``` + +你可以注册任何数量的`MeterRegistryCustomizer` bean来进一步配置注册表。例如在注册表注册任何meter之前应用通用标签: +```java +@Bean +MeterRegistryCustomizer metricsCommonTags() { + return registry -> registry.config().commonTags("region", "us-east-1"); +} +``` + +您可以通过更具体的泛型类型将定制应用到特定的注册表实现: +```java +@Bean +MeterRegistryCustomizer graphiteMetricsNamingConvention() { + return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION); +} +``` + +有了这样的设置,你可以注入`MeterRegistry`在你的组件和注册指标: +```java +@Component +public class SampleBean { + + private final Counter counter; + + public SampleBean(MeterRegistry registry) { + this.counter = registry.counter("received.messages"); + } + + public void handleMessage(String message) { + this.counter.increment(); + // handle message implementation + } + +} +``` + +Spring Boot还[配置了内置的工具](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-meter)(即`MeterBinder`实现),你可以通过配置或专用的注释标记来控制这些工具。 diff --git a/V. Spring Boot Actuator/54.2.1 Atlas.md b/V. Spring Boot Actuator/54.2.1 Atlas.md new file mode 100644 index 00000000..5b4b0fa1 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.1 Atlas.md @@ -0,0 +1,6 @@ +### 54.2.1 Atlas + +默认情况下,指标被导出到运行在本地机器上的[Atlas](http://micrometer.io/docs/registry/atlas)。可用以下方法提供要使用的[Atlas服务器](https://github.com/Netflix/atlas)的位置: +```properties +management.metrics.export.atlas.uri=http://atlas.example.com:7101/api/v1/publish +``` diff --git a/V. Spring Boot Actuator/54.2.10 Simple.md b/V. Spring Boot Actuator/54.2.10 Simple.md new file mode 100644 index 00000000..b80b0b30 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.10 Simple.md @@ -0,0 +1,8 @@ +### 54.2.10 Simple + +Micrometer附带一个简单的内存后端。如果没有配置其它注册表,该后端将自动用作回退。这允许你查看[度量端点](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics-endpoint)中收集了哪些度量数据。 + +只要使用任何其它可用后端,内存中的后端就会禁用自己。你也可以显式禁用它: +```properties +management.metrics.export.simple.enabled=false +``` diff --git a/V. Spring Boot Actuator/54.2.11 StatsD.md b/V. Spring Boot Actuator/54.2.11 StatsD.md new file mode 100644 index 00000000..74899526 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.11 StatsD.md @@ -0,0 +1,11 @@ +### 54.2.11 StatsD + +StatsD注册表急切地将度量数据从UDP推送到StatsD代理。默认情况下,度量数据被导出到运行在本地机器上的[StatsD](http://micrometer.io/docs/registry/statsd)代理。可以使用以下方法提供StatsD代理主机和端口: +```properties +management.metrics.export.statsd.host=statsd.example.com +management.metrics.export.statsd.port=9125 +``` +你也可以改变StatsD行协议来使用(默认为Datadog): +```properties +management.metrics.export.statsd.flavor=etsy +``` diff --git a/V. Spring Boot Actuator/54.2.12 Wavefront.md b/V. Spring Boot Actuator/54.2.12 Wavefront.md new file mode 100644 index 00000000..4019c647 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.12 Wavefront.md @@ -0,0 +1,17 @@ +### 54.2.12 Wavefront + +Wavefront注册表周期性地将度量数据推送到[Wavefront](http://micrometer.io/docs/registry/wavefront)。如果你直接将度量数据导出到[Wavefront](https://www.wavefront.com/),你的API令牌必须提供: +```properties +management.metrics.export.wavefront.api-token=YOUR_API_TOKEN +``` +或者,你可以使用一个Wavefront sidecar或在你的环境中设置的内部代理,将度量数据转发到WavefrontAPI主机: +```properties +management.metrics.export.uri=proxy://localhost:7828 +``` + +**注** 如果将度量数据发布到一个Wavefront代理(如[文档](https://docs.wavefront.com/proxies_installing.html)中所述),主机必须采用`proxy://HOST:PORT`格式。 + +你也可以改变数据发送到Wavefront的时间间隔: +```properties +management.metrics.export.wavefront.steps=30s +``` diff --git a/V. Spring Boot Actuator/54.2.2 Datadog.md b/V. Spring Boot Actuator/54.2.2 Datadog.md new file mode 100644 index 00000000..9a597451 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.2 Datadog.md @@ -0,0 +1,12 @@ + +### 54.2.2 Datadog + +Datadog注册表定期将度量数据推送到[datadoghq](https://www.datadoghq.com/)。要将指标导出到[Datadog](http://micrometer.io/docs/registry/datadog),必须提供API密钥: +```properties +management.metrics.export.datadog.api-key=YOUR_KEY +``` + +你还可以更改将度量发送到Datadog的时间间隔: +```properties +management.metrics.export.datadog.steps=30s +``` diff --git a/V. Spring Boot Actuator/54.2.3 Ganglia.md b/V. Spring Boot Actuator/54.2.3 Ganglia.md new file mode 100644 index 00000000..0bbb6574 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.3 Ganglia.md @@ -0,0 +1,7 @@ +### 54.2.3 Ganglia + +默认情况下,指标被导出到运行在本地机器上的[Ganglia](http://micrometer.io/docs/registry/ganglia)。[Ganglia服务器](http://ganglia.sourceforge.net/)主机和端口可以通过以下方式提供: +```properties +management.metrics.export.ganglia.host=ganglia.example.com +management.metrics.export.ganglia.post=9649 +``` diff --git a/V. Spring Boot Actuator/54.2.4 Graphite.md b/V. Spring Boot Actuator/54.2.4 Graphite.md new file mode 100644 index 00000000..f5f913ab --- /dev/null +++ b/V. Spring Boot Actuator/54.2.4 Graphite.md @@ -0,0 +1,7 @@ +### 54.2.4 Graphite + +默认情况下,指标被导出到运行在本地机器上的[Graphite](http://micrometer.io/docs/registry/graphite)。[Graphite服务器](https://graphiteapp.org/)主机和端口可以通过以下方式提供: +```properties +management.metrics.export.graphite.host=graphite.example.com +management.metrics.export.graphite.post=9004 +``` diff --git a/V. Spring Boot Actuator/54.2.5 Influx.md b/V. Spring Boot Actuator/54.2.5 Influx.md new file mode 100644 index 00000000..edfa8478 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.5 Influx.md @@ -0,0 +1,6 @@ +### 54.2.5 Influx + +默认情况下,指标被导出到运行在本地机器上的[Influx](http://micrometer.io/docs/registry/influx)。可以使用以下方法提供要使用的[Influx服务器](https://www.influxdata.com/)的位置: +```properties +management.metrics.export.influx.uri=http://influx.example.com:8086 +``` diff --git a/V. Spring Boot Actuator/54.2.6 JMX.md b/V. Spring Boot Actuator/54.2.6 JMX.md new file mode 100644 index 00000000..c800bd4f --- /dev/null +++ b/V. Spring Boot Actuator/54.2.6 JMX.md @@ -0,0 +1,5 @@ +### 54.2.6 JMX + +Micrometer提供了到[JMX](http://micrometer.io/docs/registry/jmx)的层次映射,主要是作为一种廉价且可移植的方法来查看本地指标。Spring Boot提供了一个默认的`HierarchicalNameMapper`。它用于管理维度表id如何映射到平面分级名称。 + +**注** 要控制这种行为,请定义你自己的`HierarchicalNameMapper` bean。 diff --git a/V. Spring Boot Actuator/54.2.7 New Relic.md b/V. Spring Boot Actuator/54.2.7 New Relic.md new file mode 100644 index 00000000..eb054857 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.7 New Relic.md @@ -0,0 +1,11 @@ +### 54.2.7 New Relic + +New Relic注册表定期将度量数据推送到[New Relic](http://micrometer.io/docs/registry/new-relic)。要将指标导出到[New Relic](https://newrelic.com/),必须提供API密钥和帐户id: +```properties +management.metrics.export.newrelic.api-key=YOUR_KEY +management.metrics.export.newrelic.account-id=YOUR_ACCOUNT_ID +``` +你还可以更改将度量数据发送到New Relic的时间间隔: +```properties +management.metrics.export.newrelic.steps=30s +``` diff --git a/V. Spring Boot Actuator/54.2.8 Prometheus.md b/V. Spring Boot Actuator/54.2.8 Prometheus.md new file mode 100644 index 00000000..b57513c2 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.8 Prometheus.md @@ -0,0 +1,15 @@ +### 54.2.8 Prometheus + +[Prometheus](http://micrometer.io/docs/registry/prometheus)希望通过抓取或轮询单个应用程序实例来获得度量数据。Spring Boot在`/actuator/prometheus`上提供了一个执行器端点,可以用适当的格式显示[Prometheus刮片](https://prometheus.io/)。 + +**注** 缺省情况下端点不可用,必须公开端点,请参阅公开端点以获得更多详细信息。 + +下面是一个要添加到`prometheus.yml`中的`scrape_config`示例: + +```yml +scrape_configs: + - job_name: 'spring' + metrics_path: '/actuator/prometheus' + static_configs: + - targets: ['HOST:PORT'] +``` diff --git a/V. Spring Boot Actuator/54.2.9 SignalFx.md b/V. Spring Boot Actuator/54.2.9 SignalFx.md new file mode 100644 index 00000000..60eba558 --- /dev/null +++ b/V. Spring Boot Actuator/54.2.9 SignalFx.md @@ -0,0 +1,10 @@ +### 54.2.9 SignalFx + +SignalFx注册表定期将度量数据推送到[SignalFx](http://micrometer.io/docs/registry/signalfx)。要将度量数据导出到[SignalFx](https://signalfx.com/),必须提供您的访问令牌: +```properties +management.metrics.export.signalfx.access-token=YOUR_ACCESS_TOKEN +``` +你还可以更改度量数据发送到SignalFx的时间间隔: +```properties +management.metrics.export.signalfx.steps=30s +``` diff --git a/V. Spring Boot Actuator/54.3 Supported Metrics.md b/V. Spring Boot Actuator/54.3 Supported Metrics.md new file mode 100644 index 00000000..bc570059 --- /dev/null +++ b/V. Spring Boot Actuator/54.3 Supported Metrics.md @@ -0,0 +1,13 @@ +### 54.3 支持的指标 + +Spring Boot在适用时注册以下核心指标: +- JVM指标,报告利用率: + - 各种内存和缓冲池 + - 与垃圾收集相关的统计信息 + - 线程的利用率 + - 加载/卸载的类的数量 +- CPU指标 +- 文件描述符指标 +- Logback指标:记录每个级别登录到Logback的事件数量 +- 正常运行时间指标:报告正常运行时间的指标和表示应用程序绝对启动时间的固定指标 +- Tomcat指标 diff --git a/V. Spring Boot Actuator/54.3.1 Spring MVC Metrics.md b/V. Spring Boot Actuator/54.3.1 Spring MVC Metrics.md new file mode 100644 index 00000000..7dd30640 --- /dev/null +++ b/V. Spring Boot Actuator/54.3.1 Spring MVC Metrics.md @@ -0,0 +1,27 @@ +### 54.3.1 Spring MVC指标 + +自动配置允许使用Spring MVC处理请求。当`management.metrics.web.server.auto-time-requests`为`true`,此检测用于所有请求。或者,当设置为`false`时,你可以通过向请求处理方法添加`@Timed`来启用: +```java +@RestController +@Timed 1 +public class MyController { + + @GetMapping("/api/people") + @Timed(extraTags = { "region", "us-east-1" }) 2 + @Timed(value = "all.people", longTask = true) 3 + public List listPeople() { ... } + +} +``` +1. 一个控制器类,用于对控制器中的每个请求处理程序启用计时。 +2. 为单个端点启用的方法。如果你在类中有计时器,则没有必要这样做,但是可以使用它进一步定制此特定端点的计时器。 +3. 具有`longTask = true`的方法,用于为该方法启用长任务计时器。长任务计时器需要一个单独的度量名称,可以使用短任务计时器进行堆叠。 + +默认情况下,使用`http.server.requests`来生成度量标准。可以通过设置`management.metrics.web.server.requests-metric-name`属性来定制名称。 + +默认情况下,与Spring MVC相关的指标用以下信息标记: +- `方法`,请求的方法(例如,`GET`或`POST`)。 +- `uri`,请求在变量替换之前的uri模板,如果可能的话(例如`/api/person/{id}`)。 +- `状态`,响应的HTTP状态码(例如,`200`或`500`)。 +- `异常`,处理请求时抛出的任何异常的简单类名。 +要自定义标记,请提供一个实现`WebMvcTagsProvider`的`@Bean`。 diff --git a/V. Spring Boot Actuator/54.3.2 Spring WebFlux Metrics.md b/V. Spring Boot Actuator/54.3.2 Spring WebFlux Metrics.md new file mode 100644 index 00000000..21f53b50 --- /dev/null +++ b/V. Spring Boot Actuator/54.3.2 Spring WebFlux Metrics.md @@ -0,0 +1,19 @@ +### 54.3.2 Spring WebFlux指标 + +自动配置可以检测WebFlux控制器处理的所有请求。你还可以使用一个助手类`RouterFunctionMetrics`来检测使用WebFlux函数式编程模型的应用程序。 + +默认情况下,使用`http.server.requests`这个名称来生成度量标准。你可以通过设置`management.metrics.web.server.requests-metric-name`属性来自定义名称。 + +默认情况下,基于注解的编程模型的webflux相关指标会被标记上以下信息: +- `方法`,请求的方法(例如,`GET`或`POST`)。 +- `uri`,请求在变量替换之前的uri模板,如果可能的话(例如`/api/person/{id}`)。 +- `状态`,响应的HTTP状态码(例如,`200`或`500`)。 +- `异常`,处理请求时抛出的任何异常的简单类名。 +要自定义标签,请提供一个实现`WebFluxTagsProvider`的`@Bean`。 + +默认情况下,函数式编程模型的指标会被标记上以下信息: + +- `方法`,请求的方法(例如,`GET`或`POST`)。 +- `uri`,请求在变量替换之前的uri模板,如果可能的话(例如`/api/person/{id}`)。 +- `状态`,响应的HTTP状态码(例如,`200`或`500`)。 +要自定义标签,请在`RouterFunctionMetrics`实例上使用`defaultTags`方法。 diff --git a/V. Spring Boot Actuator/54.3.3 RestTemplate Metrics.md b/V. Spring Boot Actuator/54.3.3 RestTemplate Metrics.md new file mode 100644 index 00000000..95d2578f --- /dev/null +++ b/V. Spring Boot Actuator/54.3.3 RestTemplate Metrics.md @@ -0,0 +1,13 @@ +### 54.3.3 RestTemplate指标 + +使用自动配置的`RestTemplateBuilder`创建的任何`RestTemplate`工具都是启用的。也可以手动应用`MetricsRestTemplateCustomizer`。 + +默认情况下,使用名称`http.client.requests`生成度量标准。可以通过设置`management.metrics.web.client.requests-metric-name`属性来定制名称。 + +默认情况下,由装备的`RestTemplate`生成的指标用以下信息标记: + +- `方法`,请求的方法(例如,`GET`或`POST`)。 +- `uri`,请求在变量替换之前的uri模板,如果可能的话(例如`/api/person/{id}`)。 +- `状态`,响应的HTTP状态码(例如,`200`或`500`)。 +- `客户端名称`, URI的主机部分。 +要自定义标记,请提供一个实现`RestTemplateExchangeTagsProvider`的`@Bean`。在`RestTemplateExchangeTags`中有方便的静态函数。 diff --git a/V. Spring Boot Actuator/54.3.4 Spring Integration metrics.md b/V. Spring Boot Actuator/54.3.4 Spring Integration metrics.md new file mode 100644 index 00000000..a1acb441 --- /dev/null +++ b/V. Spring Boot Actuator/54.3.4 Spring Integration metrics.md @@ -0,0 +1,3 @@ +### 54.3.4 Spring集成指标 + +当Spring集成可用时,为每个`MessageHandler`和`MessageChannel`注册一个`计时器`和一个`错误计数器`。对于每个`MessageSource`,都注册了一个`计数器`。 diff --git a/V. Spring Boot Actuator/54.3.5 Cache Metrics.md b/V. Spring Boot Actuator/54.3.5 Cache Metrics.md new file mode 100644 index 00000000..8f7120cd --- /dev/null +++ b/V. Spring Boot Actuator/54.3.5 Cache Metrics.md @@ -0,0 +1,13 @@ +### 54.3.5 缓存指标 + +自动配置允许在启动时对所有可用的`缓存`进行检测,其中的指标以`cache`为前缀。缓存检测是针对一组基本指标进行标准化的。另外,特定于缓存的度量也是可用的。 + +支持以下缓存库: +- Caffeine +- EhCache 2 +- Hazelcast +- 任何兼容的JCache(JSR-107)实现 + +根据缓存的名称和从bean名称派生的`CacheManager`的名称对指标进行标记。 + +**注** 只有在启动时可用的缓存才绑定到注册表。对于在启动阶段之后动态创建或以编程方式创建的缓存,需要显式注册。可以使用`CacheMetricsRegistrar` bean来简化这个过程。 diff --git a/V. Spring Boot Actuator/54.3.6 DataSource Metrics.md b/V. Spring Boot Actuator/54.3.6 DataSource Metrics.md new file mode 100644 index 00000000..ce5e2e35 --- /dev/null +++ b/V. Spring Boot Actuator/54.3.6 DataSource Metrics.md @@ -0,0 +1,7 @@ +### 54.3.6 数据源指标 + +自动配置允许使用一个名为`jdbc`的度量来检测所有可用的数据源对象。数据源插装产生的仪表表示当前池中活动的、允许的最大连接数和允许的最小连接数。每个量规都有一个由`jdbc`前缀的名称。 + +度量标准还根据基于bean名称计算的`数据源`名称进行标记。 + +此外,hikari特定的度量标准以`hikaricp`前缀公开。每个度量都使用池的名称进行标记(可以使用`spring.datasource.name`进行控制)。 diff --git a/V. Spring Boot Actuator/54.3.7 RabbitMQ Metrics.md b/V. Spring Boot Actuator/54.3.7 RabbitMQ Metrics.md new file mode 100644 index 00000000..b1148073 --- /dev/null +++ b/V. Spring Boot Actuator/54.3.7 RabbitMQ Metrics.md @@ -0,0 +1,3 @@ +### 54.3.7 RabbitMQ指标 + +自动配置将使用名为`RabbitMQ`的度量启用所有可用RabbitMQ连接工厂的检测。 diff --git a/V. Spring Boot Actuator/54.4 Registering custom metrics.md b/V. Spring Boot Actuator/54.4 Registering custom metrics.md new file mode 100644 index 00000000..28e59dd6 --- /dev/null +++ b/V. Spring Boot Actuator/54.4 Registering custom metrics.md @@ -0,0 +1,3 @@ +### 54.4 注册自定义指标 + +要注册自定义指标,请创建一个`MeterBinder` bean。默认情况下,所有`MeterBinder` bean都将自动应用到micrometer `MeterRegistry.Config`。 diff --git a/V. Spring Boot Actuator/54.5 Customizing individual metrics.md b/V. Spring Boot Actuator/54.5 Customizing individual metrics.md new file mode 100644 index 00000000..70d4e71c --- /dev/null +++ b/V. Spring Boot Actuator/54.5 Customizing individual metrics.md @@ -0,0 +1,11 @@ +### 54.5 自定义单个指标 + +如果需要对特定的`Meter`实例应用定制,可以使用`io.micrometer.core.instrument.config。MeterFilter`接口。默认情况下,所有的`MeterFilter` bean都将自动应用到micrometer `MeterRegistry.Config`。 + +例如,如果你想把所有以`com.example`开头的meter ID,由`mytag.region`标签重命名为`mytag.area`。你可以这样做: +```java +@Bean +public MeterFilter renameRegionTagMeterFilter() { + return MeterFilter.renameTag("com.example", "mytag.region", "mytag.area"); +} +``` diff --git a/V. Spring Boot Actuator/54.5.1 Per-meter properties.md b/V. Spring Boot Actuator/54.5.1 Per-meter properties.md new file mode 100644 index 00000000..179e8cec --- /dev/null +++ b/V. Spring Boot Actuator/54.5.1 Per-meter properties.md @@ -0,0 +1,19 @@ +### 54.5.1 Per-meter属性 + +除了`MeterFilter` bean之外,还可以使用属性在per-meter的基础上应用一组有限的定制。per-meter自定义适用于任何以给定名称开头的meter ID。例如,下面将禁用ID以`example.remote`开头的任何meter: +```properties +management.metrics.enable.example.remote = false +``` + +以下属性允许per-meter自定义: + +**表 54.1. Per-meter自定义** + +|名称|描述| +|:----|:----| +|`management.metrics.enable`|是否拒绝meter发出任何指标数据| +|`management.metrics.distribution.percentiles-histogram`|是否发布适合计算可聚合(跨维度)百分比近似值的直方图| +|`management.metrics.distribution.percentiles`|发布应用程序中计算的百分比值| +|`management.metrics.distribution.sla`|发布带有sla定义的桶的累积直方图| + +有关`百分比直方图`、`百分比`和`sla`背后概念的更多细节,请参阅micrometer文档中的[“直方图和百分比”部分](https://micrometer.io/docs/concepts#_histograms_and_percentiles)。 diff --git a/V. Spring Boot Actuator/54.6 Metrics endpoint.md b/V. Spring Boot Actuator/54.6 Metrics endpoint.md new file mode 100644 index 00000000..eef9c75c --- /dev/null +++ b/V. Spring Boot Actuator/54.6 Metrics endpoint.md @@ -0,0 +1,11 @@ +### 54.6 度量端点 + +Spring Boot提供了一个`metrics`端点,可以使用它来检查应用程序收集的度量数据。该端点在缺省情况下不可用,必须公开。更多详细信息,请参阅[公开端点](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-endpoints-exposing-endpoints)。 + +导航到`/actuator/metrics`显示可用的meter名称列表。你可以通过提供一个选择器(例如`/actuator/metrics/jvm.memory.max`),来查看关于某个特定仪表的信息。 + +**注** 这里使用的名称应该与代码中使用的名称相匹配,而不是经过约定之后的名称——对于将其发送到的监视系统来说,这是一种规范化的命名约定。换句话说,如果`jvm.memory.max`在Prometheus中显示为`jvm_memory_max`,因为它的snake case命名约定,你仍然应该使用`jvm.memory.max`。在检查`metrics`端点中的度量数据时,将其作为选择器。 + +你还可以在URL的末尾添加任意数量的`tag=KEY:VALUE`查询参数,以便按维向下钻取一个meter,例如`/actuator/metrics/jvm.memory.max?tag=area:nonheap`。 + +**注** 报告的测量值是所有与meter名称和所应用的任何标记匹配的meter的统计数据的总和。因此,在上面的示例中,返回的“值”统计量是堆的“代码缓存”、“压缩类空间”和“元空间”区域的最大内存占用的总和。如果您只是想查看“Metaspace”的最大大小,你可以添加一个额外的`tag=id:Metaspace`,即`/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace`。 diff --git a/V. Spring Boot Actuator/55. Auditing.md b/V. Spring Boot Actuator/55. Auditing.md new file mode 100644 index 00000000..e3507717 --- /dev/null +++ b/V. Spring Boot Actuator/55. Auditing.md @@ -0,0 +1,5 @@ +### 55. 审计 + +一旦Spring Security处于活动状态,Spring Boot执行器有一个灵活的审计框架会发布事件(默认抛出“authentication success”、“failure”和“access denied”异常)。这对于报告非常有用,同时可以基于认证失败实现一个锁定策略。为了自定义发布的安全事件,你可以提供自己的`AbstractAuthenticationAuditListener`,`AbstractAuthorizationAuditListener`实现。 + +你也可以使用审计服务处理自己的业务事件。为此,你可以将存在的`AuditEventRepository`注入到自己的组件,并直接使用它,或者只是简单地通过Spring `ApplicationEventPublisher`发布`AuditApplicationEvent`(使用`ApplicationEventPublisherAware`)。 diff --git a/V. Spring Boot Actuator/55. Process monitoring.md b/V. Spring Boot Actuator/55. Process monitoring.md deleted file mode 100644 index 1f0f7f55..00000000 --- a/V. Spring Boot Actuator/55. Process monitoring.md +++ /dev/null @@ -1,6 +0,0 @@ -### 55. 进程监控 -在Spring Boot执行器中,你可以找到几个类,它们创建的文件利于进程监控: -- `ApplicationPidFileWriter`创建一个包含应用PID的文件(默认位于应用目录,文件名为`application.pid`)。 -- `EmbeddedServerPortFileWriter`创建一个或多个包含内嵌服务器端口的文件(默认位于应用目录,文件名为`application.port`)。 - -这些writers默认没被激活,但你可以使用以下描述的任何方式来启用它们。 diff --git a/V. Spring Boot Actuator/55.1 Extend configuration.md b/V. Spring Boot Actuator/55.1 Extend configuration.md deleted file mode 100644 index cb0ac840..00000000 --- a/V. Spring Boot Actuator/55.1 Extend configuration.md +++ /dev/null @@ -1,7 +0,0 @@ -### 55.1 扩展配置 -在`META-INF/spring.factories`文件中,你可以激活创建PID文件的`listener(s)`,示例: -```java -org.springframework.context.ApplicationListener=\ -org.springframework.boot.system.ApplicationPidFileWriter,\ -org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter -``` diff --git a/V. Spring Boot Actuator/55.2 Programmatically.md b/V. Spring Boot Actuator/55.2 Programmatically.md deleted file mode 100644 index 845f8da4..00000000 --- a/V. Spring Boot Actuator/55.2 Programmatically.md +++ /dev/null @@ -1,3 +0,0 @@ - -### 55.2 以编程方式 -你也可以通过调用`SpringApplication.addListeners(…)`方法并传递相应的`Writer`对象来激活一个监听器,该方法允许你通过`Writer`构造器自定义文件名和路径。 diff --git a/V. Spring Boot Actuator/56. Cloud Foundry support.md b/V. Spring Boot Actuator/56. Cloud Foundry support.md deleted file mode 100644 index 4d2a4abb..00000000 --- a/V. Spring Boot Actuator/56. Cloud Foundry support.md +++ /dev/null @@ -1,7 +0,0 @@ -### 56. Cloud Foundry支持 - -当你部署到一个兼容的Cloud Foundry实例时,Spring Boot的执行器模块包含的额外支持将会被激活。`/cloudfoundryapplication`路径向所有的`NamedMvcEndpoint`bean提供替代的安全的路径。 - -扩展的支持允许Cloud Foundry management UIs(比如你可以用来查看部署好的应用的网络应用程序)增加Spring Boot执行器信息。例如,应用状态页面包含了所有的健康信息,而不是典型的“运行中”或者“已停止”状态。 - -**注** `/cloudfoundryapplication`路径不能被常规用户直接访问。为了使用端点,必须在请求时传递一个有效的UAA token。 \ No newline at end of file diff --git a/V. Spring Boot Actuator/56. HTTP Tracing.md b/V. Spring Boot Actuator/56. HTTP Tracing.md new file mode 100644 index 00000000..e8a5c132 --- /dev/null +++ b/V. Spring Boot Actuator/56. HTTP Tracing.md @@ -0,0 +1,3 @@ +### 56. HTTP追踪 + +对于所有的HTTP请求,Spring Boot自动启用追踪。你可以查看`httptrace`端点获取最近100条请求-响应的基本信息。 diff --git a/V. Spring Boot Actuator/56.1 Custom HTTP tracing.md b/V. Spring Boot Actuator/56.1 Custom HTTP tracing.md new file mode 100644 index 00000000..f8ce189e --- /dev/null +++ b/V. Spring Boot Actuator/56.1 Custom HTTP tracing.md @@ -0,0 +1,5 @@ +### 56.1 自定义HTTP追踪 + +要自定义每个跟踪中包含的项,请使用`management.trace.http.include`配置属性。 + +默认情况下,使用一个`InMemoryHttpTraceRepository`来存储最后100个请求-响应交换的跟踪。如果需要扩展容量,可以定义自己的`InMemoryHttpTraceRepository` bean实例。你还可以创建自己的替代`HttpTraceRepository`实现。 diff --git a/V. Spring Boot Actuator/56.1 Disabling extended Cloud Foundry actuator support.md b/V. Spring Boot Actuator/56.1 Disabling extended Cloud Foundry actuator support.md deleted file mode 100644 index 15b993d1..00000000 --- a/V. Spring Boot Actuator/56.1 Disabling extended Cloud Foundry actuator support.md +++ /dev/null @@ -1,8 +0,0 @@ -### 56.1 禁用扩展的Cloud Foundry执行器支持 - -如果你想要完全禁用`/cloudfoundryapplication`端点,你可以将如下内容加入你的`application.properties`文件: - -**application.properties.** -```properties -management.cloudfoundry.enabled=false -``` \ No newline at end of file diff --git a/V. Spring Boot Actuator/56.2 Cloud Foundry self signed certificates.md b/V. Spring Boot Actuator/56.2 Cloud Foundry self signed certificates.md deleted file mode 100644 index d0c0f845..00000000 --- a/V. Spring Boot Actuator/56.2 Cloud Foundry self signed certificates.md +++ /dev/null @@ -1,8 +0,0 @@ -### 56.2 Cloud Foundry自签名证书 - -默认地,对`/cloudfoundryapplication`端点的安全验证会使用SSL调用不同的Cloud Foundry服务。如果你的Cloud Foundry UAA或者Cloud Controller服务使用自签名证书,你将会需要设置如下属性: - -**application.properties.** -```properties -management.cloudfoundry.skip-ssl-validation=true -``` \ No newline at end of file diff --git a/V. Spring Boot Actuator/56.3 Custom security configuration.md b/V. Spring Boot Actuator/56.3 Custom security configuration.md deleted file mode 100644 index 4016db73..00000000 --- a/V. Spring Boot Actuator/56.3 Custom security configuration.md +++ /dev/null @@ -1,19 +0,0 @@ -### 56.3 自定义安全配置 - -如果你设定了自定义的安全配置,同时你想要扩展Cloud Foundry执行器支持,你应当确保`/cloudfoundryapplication/**`路径开放。没有一个直接开放的路径,你的Cloud Foundry应用管理器将无法获得端点数据。 - -对于Spring Security,你将要在你的配置里包含类似与`mvcMatchers("/cloudfoundryapplication/**").permitAll()`的东西: -```java -@Override -protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .mvcMatchers("/cloudfoundryapplication/**") - .permitAll() - .mvcMatchers("/mypath") - .hasAnyRole("SUPERUSER") - .anyRequest() - .authenticated().and() - .httpBasic(); -} -``` \ No newline at end of file diff --git a/V. Spring Boot Actuator/57. Process Monitoring.md b/V. Spring Boot Actuator/57. Process Monitoring.md new file mode 100644 index 00000000..6d968322 --- /dev/null +++ b/V. Spring Boot Actuator/57. Process Monitoring.md @@ -0,0 +1,9 @@ +### 55. 进程监控 + +在`Spring Boot`模块中,你可以找到两个类来创建通常对进程监控有用的文件: +- `ApplicationPidFileWriter`创建一个包含应用PID的文件(默认位于应用目录,文件名为`application.pid`)。 +- `WebServerPortFileWriter`创建一个或多个包含运行的服务器端口的文件(默认位于应用目录,文件名为`application.port`)。 + +这些writers默认没被激活,但你可以启用它们: +- [55.1 扩展配置](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-process-monitoring-configuration) +- [57.2 以编程方式](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-process-monitoring-programmatically) diff --git a/V. Spring Boot Actuator/57. What to read next.md b/V. Spring Boot Actuator/57. What to read next.md deleted file mode 100644 index 4db99e20..00000000 --- a/V. Spring Boot Actuator/57. What to read next.md +++ /dev/null @@ -1,4 +0,0 @@ -### 57. 接下来阅读什么 -如果想探索本章节讨论的某些内容,你可以看下执行器的[示例应用](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-samples),你也可能想了解图形工具比如[Graphite](http://graphite.wikidot.com/)。 - -此外,你可以继续了解[‘deployment options’](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#deployment)或直接跳到Spring Boot的[build tool plugins](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#build-tool-plugins)。 diff --git a/V. Spring Boot Actuator/57.1 Extend Configuration.md b/V. Spring Boot Actuator/57.1 Extend Configuration.md new file mode 100644 index 00000000..d9a91467 --- /dev/null +++ b/V. Spring Boot Actuator/57.1 Extend Configuration.md @@ -0,0 +1,8 @@ +### 57.1 扩展配置 + +在`META-INF/spring.factories`文件中,你可以激活创建PID文件的`listener(s)`,示例: +```java +org.springframework.context.ApplicationListener=\ +org.springframework.boot.system.ApplicationPidFileWriter,\ +org.springframework.boot.system.EmbeddedServerPortFileWriter +``` diff --git a/V. Spring Boot Actuator/57.2 Programmatically.md b/V. Spring Boot Actuator/57.2 Programmatically.md new file mode 100644 index 00000000..e2d38190 --- /dev/null +++ b/V. Spring Boot Actuator/57.2 Programmatically.md @@ -0,0 +1,4 @@ + +### 57.2 以编程方式 + +你也可以通过调用`SpringApplication.addListeners(…)`方法并传递相应的`Writer`对象来激活一个监听器,该方法允许你通过`Writer`构造器自定义文件名和路径。 diff --git a/V. Spring Boot Actuator/58. Cloud Foundry Support.md b/V. Spring Boot Actuator/58. Cloud Foundry Support.md new file mode 100644 index 00000000..208ad50f --- /dev/null +++ b/V. Spring Boot Actuator/58. Cloud Foundry Support.md @@ -0,0 +1,7 @@ +### 58. Cloud Foundry支持 + +当你部署到一个兼容的Cloud Foundry实例时,Spring Boot的执行器模块包含的额外支持将会被激活。`/cloudfoundryapplication`路径向所有的`@Endpoint`bean提供替代的安全的路径。 + +扩展的支持允许Cloud Foundry management UIs(比如你可以用来查看部署好的应用的网络应用程序)增加Spring Boot执行器信息。例如,应用状态页面包含了所有的健康信息,而不是典型的“运行中”或者“已停止”状态。 + +**注** `/cloudfoundryapplication`路径不能被常规用户直接访问。为了使用端点,必须在请求时传递一个有效的UAA token。 diff --git a/V. Spring Boot Actuator/58.1 Disabling Extended Cloud Foundry Actuator Support.md b/V. Spring Boot Actuator/58.1 Disabling Extended Cloud Foundry Actuator Support.md new file mode 100644 index 00000000..18a06a51 --- /dev/null +++ b/V. Spring Boot Actuator/58.1 Disabling Extended Cloud Foundry Actuator Support.md @@ -0,0 +1,8 @@ +### 58.1 禁用扩展的Cloud Foundry执行器支持 + +如果你想要完全禁用`/cloudfoundryapplication`端点,你可以将如下内容加入你的`application.properties`文件: + +**application.properties.** +```properties +management.cloudfoundry.enabled=false +``` diff --git a/V. Spring Boot Actuator/58.2 Cloud Foundry Self-signed Certificates.md b/V. Spring Boot Actuator/58.2 Cloud Foundry Self-signed Certificates.md new file mode 100644 index 00000000..70503534 --- /dev/null +++ b/V. Spring Boot Actuator/58.2 Cloud Foundry Self-signed Certificates.md @@ -0,0 +1,8 @@ +### 58.2 Cloud Foundry自签名证书 + +默认地,对`/cloudfoundryapplication`端点的安全验证会使用SSL调用不同的Cloud Foundry服务。如果你的Cloud Foundry UAA或者Cloud Controller服务使用自签名证书,你将会需要设置如下属性: + +**application.properties.** +```properties +management.cloudfoundry.skip-ssl-validation=true +``` diff --git a/V. Spring Boot Actuator/58.3 Custom context path.md b/V. Spring Boot Actuator/58.3 Custom context path.md new file mode 100644 index 00000000..3eb11469 --- /dev/null +++ b/V. Spring Boot Actuator/58.3 Custom context path.md @@ -0,0 +1,45 @@ +### 58.3 自定义上下文路径 + +如果服务器的上下文路径没有配置为`/`,则云计算端点在应用程序的根上不可用。例如,如果配置为`server.servlet.context-path=/foo`, 则Cloud Foundry的端点位于`/foo/cloudfoundryapplication/*`。 + +如果你希望云计算端点始终在`/cloudfoundryapplication/*`上可用,无论服务器的上下文路径如何,你都需要在应用程序中显式地配置它。配置将根据使用的web服务器而有所不同。对于Tomcat,可以添加以下配置: +```java +@Bean +public TomcatServletWebServerFactory servletWebServerFactory() { + return new TomcatServletWebServerFactory() { + + @Override + protected void prepareContext(Host host, + ServletContextInitializer[] initializers) { + super.prepareContext(host, initializers); + StandardContext child = new StandardContext(); + child.addLifecycleListener(new Tomcat.FixContextListener()); + child.setPath("/cloudfoundryapplication"); + ServletContainerInitializer initializer = getServletContextInitializer( + getContextPath()); + child.addServletContainerInitializer(initializer, Collections.emptySet()); + child.setCrossContext(true); + host.addChild(child); + } + + }; +} + +private ServletContainerInitializer getServletContextInitializer(String contextPath) { + return (c, context) -> { + Servlet servlet = new GenericServlet() { + + @Override + public void service(ServletRequest req, ServletResponse res) + throws ServletException, IOException { + ServletContext context = req.getServletContext() + .getContext(contextPath); + context.getRequestDispatcher("/cloudfoundryapplication").forward(req, + res); + } + + }; + context.addServlet("cloudfoundry", servlet).addMapping("/*"); + }; +} +``` diff --git a/V. Spring Boot Actuator/59. What to Read Next.md b/V. Spring Boot Actuator/59. What to Read Next.md new file mode 100644 index 00000000..19b5ee3c --- /dev/null +++ b/V. Spring Boot Actuator/59. What to Read Next.md @@ -0,0 +1,5 @@ +### 59. 接下来阅读什么 + +如果想探索本章节讨论的某些内容,你可以看下执行器的[示例应用](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-samples),你也可能想了解图形工具比如[Graphite](http://graphite.wikidot.com/)。 + +此外,你可以继续了解[部署选项](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#deployment)或直接跳到Spring Boot的[构建工具插件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#build-tool-plugins)。 diff --git a/V. Spring Boot Actuator/README.md b/V. Spring Boot Actuator/README.md index 8b70f203..29f790f0 100644 --- a/V. Spring Boot Actuator/README.md +++ b/V. Spring Boot Actuator/README.md @@ -1,5 +1,3 @@ -### Spring Boot执行器:Production-ready特性 +### Spring Boot执行器:用于生产环境的特性 Spring Boot包含很多其他特性,可用来帮你监控和管理发布到生产环境的应用。你可以选择使用HTTP端点,或者JMX来管理和监控应用。审计(Auditing),健康(health)和数据采集(metrics gathering)会自动应用到你的应用。 - -Actuator HTTP端点只能用在基于Spring MVC的应用,特别地,它不能跟Jersey一块使用,除非你也[启用Spring MVC](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#howto-use-actuator-with-jersey)。 \ No newline at end of file diff --git a/VI. Deploying Spring Boot Applications/60. Deploying to the Cloud.md b/VI. Deploying Spring Boot Applications/60. Deploying to the Cloud.md new file mode 100644 index 00000000..1ba02362 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60. Deploying to the Cloud.md @@ -0,0 +1,9 @@ +### 60. 部署到云端 + +对于大多数流行云PaaS(平台即服务)提供商,Spring Boot的可执行jars就是为它们准备的。这些提供商往往要求你自己提供容器。它们只负责管理应用的进程(不特别针对Java应用程序),所以它们需要一个中间层来将你的应用适配到云概念中的一个运行进程。 + +两个流行的云提供商,Heroku和Cloud Foundry,采取一个打包('buildpack')方法。为了启动你的应用程序,不管需要什么,buildpack都会将它们打包到你的部署代码。它可能是一个JDK和一个java调用,也可能是一个内嵌的webserver,或者是一个成熟的应用服务器。buildpack是可插拔的,但你最好尽可能少的对它进行自定义设置。这可以减少不受你控制的功能范围,最小化部署和生产环境的发散。 + +理想情况下,你的应用就像一个Spring Boot可执行jar,所有运行需要的东西都打包到它内部。 + +本章节我们将看到在“Getting Started”章节[开发的简单应用](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#getting-started-first-application)是怎么在云端运行的。 diff --git a/VI. Deploying Spring Boot Applications/60.1 Cloud Foundry.md b/VI. Deploying Spring Boot Applications/60.1 Cloud Foundry.md new file mode 100644 index 00000000..131893e5 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.1 Cloud Foundry.md @@ -0,0 +1,51 @@ +### 60.1 Cloud Foundry + +如果不指定其他打包方式,Cloud Foundry会启用它提供的默认打包方式。Cloud Foundry的[Java buildpack](https://github.com/cloudfoundry/java-buildpack)对Spring应用有出色的支持,包括Spring Boot。你可以部署独立的可执行jar应用,也可以部署传统的`.war`形式的应用。 + +一旦你构建应用(比如,使用`mvn clean package`)并[安装`cf`命令行工具](https://docs.cloudfoundry.org/cf-cli/install-go-cli.html),你可以使用下面的`cf push`命令(将路径指向你编译后的`.jar`)来部署应用。在发布应用前,确保[你已登陆cf命令行客户端](https://docs.cloudfoundry.org/cf-cli/getting-started.html#login)。下面的代码行展示了如何使用`cf push`命令来部署应用程序: +```shell +$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar +``` + +**注** 在前面的例子中,我们将`acloudyspringtime`替换为你为应用程序指定的`cf`值。 + +查看[`cf push`文档](https://docs.cloudfoundry.org/cf-cli/getting-started.html#push)获取更多可选项。如果相同目录下存在[manifest.yml](https://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html),Cloud Foundry会使用它。 + +就此,`cf`将开始上传你的应用,生成如下图所示的输出: +``` +Uploading acloudyspringtime... OK +Preparing to start acloudyspringtime... OK +-----> Downloaded app package (8.9M) +-----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e +-----> Downloading Open Jdk JRE 1.8.0_121 from https://java-buildpack.cloudfoundry.org/openjdk/trusty/x86_64/openjdk-1.8.0_121.tar.gz (found in cache) + Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s) +-----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache) + Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K +-----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache) + Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s) +-----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache) +Checking status of app 'acloudyspringtime'... + 0 of 1 instances running (1 starting) + ... + 0 of 1 instances running (1 starting) + ... + 0 of 1 instances running (1 starting) + ... + 1 of 1 instances running (1 running) + +App started +``` +恭喜!应用现在处于运行状态! + +应用程序启动后,可以使用`cf apps`命令验证部署的应用程序的状态,如下例所示: +```shell +$ cf apps +Getting applications in ... +OK + +name requested state instances memory disk urls +... +acloudyspringtime started 1/1 512M 1G acloudyspringtime.cfapps.io +... +``` +一旦Cloud Foundry意识到你的应用已经部署,你就可以点击给定的应用URI。在前面的示例中,你可以通过[http://acloudyspringtime.cfapps.io/](http://acloudyspringtime.cfapps.io/)找到它。 diff --git a/VI. Deploying Spring Boot Applications/60.1.1 Binding to Services.md b/VI. Deploying Spring Boot Applications/60.1.1 Binding to Services.md new file mode 100644 index 00000000..4c534765 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.1.1 Binding to Services.md @@ -0,0 +1,23 @@ +### 60.1.1 绑定服务 + +默认情况下,运行应用的元数据和服务连接信息被暴露为应用的环境变量(比如`$VCAP_SERVICES`),采用这种架构的原因是因为Cloud Foundry多语言特性(任何语言和平台都支持作为buildpack),进程级别的环境变量是语言无关(language agnostic)的。 + +环境变量并不总是有利于设计最简单的API,所以Spring Boot自动提取它们,然后将这些数据导入能够通过Spring `Environment`抽象访问的属性里: +```java +@Component +class MyBean implements EnvironmentAware { + + private String instanceId; + + @Override + public void setEnvironment(Environment environment) { + this.instanceId = environment.getProperty("vcap.application.instance_id"); + } + + // ... + +} +``` +所有的Cloud Foundry属性都以`vcap`作为前缀,你可以使用vcap属性获取应用信息(比如应用的公共URL)和服务信息(比如数据库证书),具体参考[CloudFoundryVcapEnvironmentPostProcessor](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.html)的Javadoc。 + +**注**:[Spring Cloud Connectors](https://cloud.spring.io/spring-cloud-connectors/)项目很适合比如配置数据源的任务。Spring Boot为它提供了自动配置支持和一个`spring-boot-starter-cloud-connectors` starter。 diff --git a/VI. Deploying Spring Boot Applications/60.2 Heroku.md b/VI. Deploying Spring Boot Applications/60.2 Heroku.md new file mode 100644 index 00000000..83beb737 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.2 Heroku.md @@ -0,0 +1,53 @@ +### 60.2 Heroku + +Heroku是另外一个流行的Paas平台,你可以提供一个`Procfile`来定义Heroku的构建过程,它提供部署应用所需的指令。Heroku为Java应用分配一个端口,确保能够路由到外部URI。 + +你必须配置你的应用监听正确的端口,下面是用于我们的starter REST应用的`Procfile`: +``` +web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar +``` +Spring Boot将`-D`参数作为属性,通过Spring `Environment`实例访问。`server.port`配置属性适合于内嵌的Tomcat,Jetty或Undertow实例启用时使用,`$PORT`环境变量被分配给Heroku Paas使用。 + +这就是你需要做的所有内容,对于Heroku部署来说,经常做的工作就是使用`git push`将代码推送到生产环境。 +``` +$ git push heroku master + +Initializing repository, done. +Counting objects: 95, done. +Delta compression using up to 8 threads. +Compressing objects: 100% (78/78), done. +Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, done. +Total 95 (delta 31), reused 0 (delta 0) + +-----> Java app detected +-----> Installing OpenJDK 1.8... done +-----> Installing Maven 3.3.1... done +-----> Installing settings.xml... done +-----> Executing: mvn -B -DskipTests=true clean install + + [INFO] Scanning for projects... + Downloading: https://repo.spring.io/... + Downloaded: https://repo.spring.io/... (818 B at 1.8 KB/sec) + .... + Downloaded: http://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec) + [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/... + [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ... + [INFO] ------------------------------------------------------------------------ + [INFO] BUILD SUCCESS + [INFO] ------------------------------------------------------------------------ + [INFO] Total time: 59.358s + [INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014 + [INFO] Final Memory: 20M/493M + [INFO] ------------------------------------------------------------------------ + +-----> Discovering process types + Procfile declares types -> web + +-----> Compressing... done, 70.4MB +-----> Launching... done, v6 + http://agile-sierra-1405.herokuapp.com/ deployed to Heroku + +To git@heroku.com:agile-sierra-1405.git + * [new branch] master -> master +``` +现在你的应用已经启动并运行在Heroku。 diff --git a/VI. Deploying Spring Boot Applications/60.3 Openshift.md b/VI. Deploying Spring Boot Applications/60.3 Openshift.md new file mode 100644 index 00000000..478ce022 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.3 Openshift.md @@ -0,0 +1,8 @@ +### 60.3 Openshift + +[Openshift](https://www.openshift.com/)是Kubernetes容器编排平台的红帽公共(和企业)扩展。与Kubernetes类似,OpenShift有许多安装基于Spring Boot的应用程序的选项。OpenShift有很多描述如何部署Spring启动应用程序的资源,包括: + +- [使用S2I构建器](https://blog.openshift.com/using-openshift-enterprise-grade-spring-boot-deployments/) +- [架构指南](https://access.redhat.com/documentation/en-us/reference_architectures/2017/html-single/spring_boot_microservices_on_red_hat_openshift_container_platform_3/) +- [在Wildfly上作为传统web应用程序运行](https://blog.openshift.com/using-spring-boot-on-openshift/) +- [OpenShift Commons简报](https://blog.openshift.com/openshift-commons-briefing-96-cloud-native-applications-spring-rhoar/) diff --git "a/VI. Deploying Spring Boot Applications/60.4 Amazon Web Services\357\274\210AWS\357\274\211.md" "b/VI. Deploying Spring Boot Applications/60.4 Amazon Web Services\357\274\210AWS\357\274\211.md" new file mode 100644 index 00000000..0050a69d --- /dev/null +++ "b/VI. Deploying Spring Boot Applications/60.4 Amazon Web Services\357\274\210AWS\357\274\211.md" @@ -0,0 +1,11 @@ +### 60.4 亚马逊网络服务(AWS) + +亚马逊网络服务提供了多种安装基于Spring Boot的应用的方式, 比如传统的网络应用(war),又比如内嵌网络服务器的可执行jar文件。选项包括: + +- AWS Elastic Beanstalk +- AWS Code Deploy +- AWS OPS Works +- AWS Cloud Formation +- AWS Container Registry + +每个选项都有不同的特点和定价模式。在这里,我们只描述最简单的选项:AWS Elastic Beanstalk。 diff --git a/VI. Deploying Spring Boot Applications/60.4.1 AWS Elastic Beanstalk.md b/VI. Deploying Spring Boot Applications/60.4.1 AWS Elastic Beanstalk.md new file mode 100644 index 00000000..fbb377fb --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.4.1 AWS Elastic Beanstalk.md @@ -0,0 +1,25 @@ +### 60.4.1 AWS Elastic Beanstalk + +就像在官方的[Elastic Beanstalk Java指南](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html)里描述的那样,有两种主要的方式来部署Java应用。你可以使用“Tomcat平台”或者“Java SE平台”。 + +**使用Tomcat平台** + +这个选项适用于产生war文件的Spring Boot工程。不需要任何特殊的配置,按照官方的指南一步步来就好。 + +**使用Java SE平台** + +这个选项适用于产生jar文件并运行一个内嵌的网络容器的Spring Boot工程。Elastic Beanstalk环境在80端口上运行一个nginx实例,来代理运行在5000端口上的实际的应用。在你的`application.properties`文件中加入以下内容,来进行配置: +```properties +server.port=5000 +``` + +**注** 默认地,Elastic Beanstalk上传源码并在AWS进行编译。为了上传二进制文件作为替代,在你的`.elasticbeanstalk/config.yml`文件中加入以下内容: +```properties +deploy: + artifact: target/demo-0.0.1-SNAPSHOT.jar +``` + +**注** 默认地,Elastic Beanstalk环境负载均衡。负载均衡器会优先考虑成本,为了避免这个,按照[亚马逊文档](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity)里描述的那样,设置环境类型为“单个实例”。单个实例环境可以使用CLI或者以下命令进行创建: +```command +eb create -s +``` diff --git a/VI. Deploying Spring Boot Applications/60.4.2 Summary.md b/VI. Deploying Spring Boot Applications/60.4.2 Summary.md new file mode 100644 index 00000000..b8a58bb0 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.4.2 Summary.md @@ -0,0 +1,3 @@ +### 60.4.2 总结 + +这是接触AWS的最简单的方式之一,但还有更多的事情需要考虑。比如,怎么样使用Elastic Beanstalk maven插件代替CLI,把Elastic Beanstalk集成到CI/CD工具中,等等。有一个[博客](https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/)详细地讨论了这些主题。 diff --git a/VI. Deploying Spring Boot Applications/60.5 Boxfuse and Amazon Web Services.md b/VI. Deploying Spring Boot Applications/60.5 Boxfuse and Amazon Web Services.md new file mode 100644 index 00000000..354d1013 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.5 Boxfuse and Amazon Web Services.md @@ -0,0 +1,37 @@ +### 60.5 Boxfuse和亚马逊网络服务 + +[Boxfuse](https://boxfuse.com/)的工作机制是将你的Spring Boot可执行jar或war转换进一个最小化的VM镜像,该镜像不需改变就能部署到VirtualBox或AWS。Boxfuse深度集成Spring Boot并使用你的Spring Boot配置文件自动配置端口和健康检查URLs,它将该信息用于产生的镜像及它提供的所有资源(实例,安全分组,可伸缩的负载均衡等)。 + +一旦创建一个[Boxfuse账号](https://console.boxfuse.com/),并将它连接到你的AWS账号,安装最新版Boxfuse客户端,确保应用被Maven或Gradle构建过,比如`mvn clean package`)。你可以使用类似下面的命令将Spring Boot应用部署到AWS: +```shell +$ boxfuse run myapp-1.0.jar -env=prod +``` + +更多选项可查看[`boxfuse run`文档](https://boxfuse.com/docs/commandline/run.html),如果当前目录存在一个[boxfuse.conf](https://boxfuse.com/docs/commandline/#configuration)文件,Boxfuse将使用它。 + +**注** 如果你的可执行jar或war包含[`application-boxfuse.properties`](https://boxfuse.com/docs/payloads/springboot.html#configuration)文件,Boxfuse默认在启动时会激活一个名为`boxfuse`的Spring profile,然后在该profile包含的属性基础上构建自己的配置。 + +此刻,`boxfuse`将为你的应用创建一个镜像并上传到AWS,然后配置并启动需要的资源。其输出结果与下面的示例类似: +``` +Fusing Image for myapp-1.0.jar ... +Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0 +Creating axelfontaine/myapp ... +Pushing axelfontaine/myapp:1.0 ... +Verifying axelfontaine/myapp:1.0 ... +Creating Elastic IP ... +Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ... +Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ... +AMI created in 00:23.557s -> ami-d23f38cf +Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ... +Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ... +Instance launched in 00:30.306s -> i-92ef9f53 +Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at http://52.28.235.61/ ... +Payload started in 00:29.266s -> http://52.28.235.61/ +Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ... +Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ... +Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at http://myapp-axelfontaine.boxfuse.io/ +``` + +你的应用现在应该已经在AWS上启动并运行了。 + +请参阅有关[在EC2部署Spring Boot应用](https://boxfuse.com/blog/spring-boot-ec2.html)的博客,以及[Boxfuse集成Spring Boot文档](https://boxfuse.com/docs/payloads/springboot.html),以开始运行该应用程序的Maven构建。 diff --git a/VI. Deploying Spring Boot Applications/60.6 Google Cloud.md b/VI. Deploying Spring Boot Applications/60.6 Google Cloud.md new file mode 100644 index 00000000..993849e8 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/60.6 Google Cloud.md @@ -0,0 +1,44 @@ +### 60.6 Google Cloud + +谷歌云有几个用于启动Spring Boot应用程序的选项。最简单的入门方法可能是App Engine,但是你也可以找到用Container Engine在容器中运行Spring Boot的方法,或者用Compute Engine在虚拟机中运行Spring Boot的方法。 + +要在App Engine中运行,你可以首先在UI中创建一个项目,它为您设置一个惟一的标识符,并设置HTTP路由。将一个Java应用程序添加到项目中,并保持它为空,然后使用[谷歌云SDK](https://cloud.google.com/sdk/downloads)将你的Spring Boot应用程序从命令行或CI构建推入该位置。 + +App Engine需要你创建一个`app.yaml`文件来描述应用程序所需的资源。通常,你把这个文件放在`src/main/appengine`,它应该类似于以下文件: +```properties +service: default + +runtime: java +env: flex + +runtime_config: + jdk: openjdk8 + +handlers: +- url: /.* + script: this field is required, but ignored + +manual_scaling: + instances: 1 + +health_check: + enable_health_check: False + +env_variables: + ENCRYPT_KEY: your_encryption_key_here +``` + +你可以通过将项目ID添加到构建配置中来部署应用程序(例如,使用Maven插件),如下面的示例所示: +```xml + + com.google.cloud.tools + appengine-maven-plugin + 1.3.0 + + myproject + + +``` +然后使用`mvn appengine:deploy`进行部署(如果需要首先进行身份验证,则构建将失败)。 + +**注** 谷歌App Engine Classic与Servlet 2.5 API绑定在一起,因此如果不进行一些修改,就不能在那里部署Spring应用程序。请参阅本指南的[Servlet 2.5部分](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-servlet-2-5)。 diff --git a/VI. Deploying Spring Boot Applications/61. Installing Spring Boot Applications.md b/VI. Deploying Spring Boot Applications/61. Installing Spring Boot Applications.md new file mode 100644 index 00000000..c8ea7451 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/61. Installing Spring Boot Applications.md @@ -0,0 +1,23 @@ +### 61. 安装Spring Boot应用 + +除了使用`java -jar`运行Spring Boot应用,制作在Unix系统上完全可执行的应用也是可能的。完全可执行的jar可以像其它的可执行二进制文件一样被执行,或者可以用[`init.d`或`systemd`进行注册](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#deployment-service)。这会简化常见生产环境Spring Boot应用的安装和管理。 + +**警告⚠️** 通过在文件之前嵌入一段额外的脚本,来启动完全可执行的Jar。目前,一些工具尚不接受这种格式,所以你并不总是能够使用这项技术。比如,`jar -xf`可能会在解压一个完全可执行的jar或者war文件时悄悄地失败。建议你仅在想要直接执行它的情况下,将你的jar或者war文件制作为完全可执行的格式。不要在只是想要使用`java -jar`运行它,或者在一个servlet容器部署它的时候这样做。 + +在Maven中添加以下plugin配置可以创建一个"完全可执行"jar: +```xml + + org.springframework.boot + spring-boot-maven-plugin + + true + + +``` +对于Gradle,等价的配置如下: +```shell +bootJar { + launchScript() +} +``` +然后输入`./my-application.jar`运行应用(`my-application`是你的artifact name)。包含jar文件的目录会被当作你的应用工作目录使用。 diff --git a/VI. Deploying Spring Boot Applications/61.1 Supported Operating Systems.md b/VI. Deploying Spring Boot Applications/61.1 Supported Operating Systems.md new file mode 100644 index 00000000..def7ee5a --- /dev/null +++ b/VI. Deploying Spring Boot Applications/61.1 Supported Operating Systems.md @@ -0,0 +1,3 @@ +### 61.1 支持的操作系统 + +默认的脚本支持大部分的Linux发行版,同时在CentOS和Ubuntu上进行了测试。其它的平台,比如OS X和FreeBSD将会需要使用自定义的`embeddedLaunchScript`。 diff --git a/VI. Deploying Spring Boot Applications/61.2 Unix&Linux Services.md b/VI. Deploying Spring Boot Applications/61.2 Unix&Linux Services.md new file mode 100644 index 00000000..8f37db5e --- /dev/null +++ b/VI. Deploying Spring Boot Applications/61.2 Unix&Linux Services.md @@ -0,0 +1,3 @@ +### 61.2 Unix/Linux服务 + +你可以使用`init.d`或`systemd`启动Spring Boot应用,就像其他Unix/Linux服务那样。 diff --git "a/VI. Deploying Spring Boot Applications/61.2.1 Installation as an init.d Service\357\274\210System V\357\274\211.md" "b/VI. Deploying Spring Boot Applications/61.2.1 Installation as an init.d Service\357\274\210System V\357\274\211.md" new file mode 100644 index 00000000..d5945cfd --- /dev/null +++ "b/VI. Deploying Spring Boot Applications/61.2.1 Installation as an init.d Service\357\274\210System V\357\274\211.md" @@ -0,0 +1,49 @@ +### 61.2.1 安装为init.d服务(System V) + +如果你配置Spring Boot的Maven或Gradle插件产生一个[完全可执行jar](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#deployment-install),并且没有使用自定义的`embeddedLaunchScript`,那你的应用可以作为`init.d`服务使用。只要简单的建立jar到`init.d`的符号连接就能获取标准的`start`,`stop`,`restart `和`status`命令支持。 + +该脚本支持以下特性: +- 以拥有该jar文件的用户启动服务。 +- 使用`/var/run//.pid`跟踪应用的PID。 +- 将控制台日志输出到`/var/log/.log`。 + +假设你在`/var/myapp`目录安装了一个Spring Boot应用,只需要建立符号连接就能将Spring Boot应用安装成`init.d`服务: +```shell +$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp +``` +一旦安装成功,你就可以像平常那样启动和停止服务,例如,在一个基于Debian的系统: +```shell +$ service myapp start +``` +**注** 如果应用启动失败,检查下`/var/log/.log`中的错误日志。 + +你也可以标识应用使用标准的操作系统工具自启动,例如,在Debian上: +```shell +$ update-rc.d myapp defaults +``` + +**保护init.d服务** + +当使用`root`用户启动`init.d`服务时,默认的执行脚本将以拥有该jar文件的用户来运行应用。你最好不要使用`root`启动Spring Boot应用,也就是你的应用jar文件拥有者不能是`root`,而是创建一个特定用户运行应用,并使用`chown`指定该用户拥有jar文件,示例: +```shell +$ chown bootapp:bootapp your-app.jar +``` +本示例中,默认执行脚本将使用`bootapp`用户运行应用。 + +**注** 为减少应用用户账号冲突,你可以考虑防止它使用登陆shell,例如将账号shell设置为`/usr/sbin/nologin`。 + +你也要采取措施防止修改应用jar文件,首先配置jar文件权限只能被拥有者读取和执行,不能写入: +```shell +$ chmod 500 your-app.jar +``` +然后,你也应该采取措施限制应用或账号运行时的冲突造成的损坏。如果攻击者获取访问权,他们可能会让jar文件可写并改变它的内容,使用`chattr`让它变为不可变是唯一的保护措施: +```shell +$ sudo chattr +i your-app.jar +``` +这会防止任何用户修改jar文件,包括root。 + +如果root用户用来控制应用服务,并且你[使用`.conf`文件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#deployment-script-customization-conf-file)自定义它的启动,该`.conf`文件将被root用户读取和评估,因此它也需要保护。使用`chmod`改变文件权限只能被拥有者读取,然后使用`chown`改变文件拥有者为root: +```shell +$ chmod 400 your-app.conf +$ sudo chown root:root your-app.conf +``` diff --git a/VI. Deploying Spring Boot Applications/61.2.2 Installation as a systemd Service.md b/VI. Deploying Spring Boot Applications/61.2.2 Installation as a systemd Service.md new file mode 100644 index 00000000..506fdc81 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/61.2.2 Installation as a systemd Service.md @@ -0,0 +1,29 @@ +### 61.2.2 安装为Systemd服务 + +`systemd`是System V init系统的继任者,很多现代Linux分发版本都在使用。尽管你可以继续使用`init.d`脚本,但使用`systemd` ‘service’脚本启动Spring Boot应用是有可能的。 + +假设你在`/var/myapp`目录下安装一个Spring Boot应用,为了将它安装为一个`systemd`服务,你需要按照以下示例创建一个脚本,比如命名为`myapp.service`,然后将它放到`/etc/systemd/system`目录下: +```shell +[Unit] +Description=myapp +After=syslog.target + +[Service] +User=myapp +ExecStart=/var/myapp/myapp.jar +SuccessExitStatus=143 + +[Install] +WantedBy=multi-user.target +``` +**提示** 记得根据你的应用改变`Description`,`User`和`ExecStart`字段。 + +**提示** 注意`ExecStart`字段没有声明脚本行动命令,也就是说会使用默认的`run`命令。 + +注意跟作为`init.d`服务运行不同,使用`systemd`这种方式运行应用,PID文件和控制台日志文件是由系统自己进行管理的,因此必须在‘service’脚本配置正确的字段,具体参考[service unit configuration man page](https://www.freedesktop.org/software/systemd/man/systemd.service.html)。 + +使用以下命令标识应用自动在系统boot上启动: +```shell +$ systemctl enable myapp.service +``` +具体详情可参考`man systemctl`。 diff --git a/VI. Deploying Spring Boot Applications/61.2.3 Customizing the Startup Script.md b/VI. Deploying Spring Boot Applications/61.2.3 Customizing the Startup Script.md new file mode 100644 index 00000000..21e361d4 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/61.2.3 Customizing the Startup Script.md @@ -0,0 +1,66 @@ +### 61.2.3 自定义启动脚本 + +Maven或Gradle插件生成的默认内嵌启动脚本可以通过很多方法自定义,对于大多数开发者,使用默认脚本和一些自定义通常就足够了。如果发现不能自定义需要的东西,你可以使用`embeddedLaunchScript`选项生成自己的文件。 + +**在脚本生成时自定义** + +自定义写入jar文件的启动脚本元素是有意义的。例如,为`init.d`脚本提供“description”,既然知道这会展示到前端(并且,它不需改变),你可能会在生成jar时提供它。 + +为了自定义写入的元素,你需要为Spring Boot Maven或Gradle插件指定`embeddedLaunchScriptProperties`选项。 + +以下是默认脚本支持的可代替属性: + +|名称|描述| +|:----|:----| +|`mode`|脚本模式,默认为`auto`| +|`initInfoProvides`|'INIT INFO'部分的`Provides`,对于Gradle默认为`spring-boot-application`,对于Maven默认为`${project.artifactId}`| +|`initInfoRequiredStart`|'INIT INFO'部分的`Required-Start`,默认为`$remote_fs $syslog $network`| +|`initInfoRequiredStop`|'INIT INFO'部分的`Required-Stop`,默认为`$remote_fs $syslog $network`| +|`initInfoDefaultStart`|'INIT INFO'部分的`Default-Start`,默认为`2 3 4 5`| +|`initInfoDefaultStop`|'INIT INFO'部分的`Default-Stop`,默认为`0 1 6`| +|`initInfoShortDescription`|‘INIT INFO’部分的`Short-Description`,对于Gradle默认为`Spring Boot Application`,对于Maven默认为`${project.name}`| +|`initInfoDescription`|“INIT INFO”部分的`Description`,对于Gradle默认为`Spring Boot Application`,对于Maven默认为`${project.description}`(失败会回退到`${project.name}`)| +|`initInfoChkconfig`|“INIT INFO”部分的`chkconfig`,默认为`2345 99 01`| +|`confFolder`|`CONF_FOLDER`的默认值,默认为包含jar的文件夹| +|`inlinedConfScript`|对应该内联到默认启动脚本中的文件脚本的引用。这可以用来在加载任何外部配置文件之前设置环境变量,比如`JAVA_OPTS`| +|`logFolder`|`LOG_FOLDER`的默认值,只对`init.d`服务有效| +|`logFilename`|`LOG_FILENAME`的默认值,只对`init.d`服务有效| +|`pidFolder`|`PID_FOLDER`的默认值,只对`init.d`服务有效| +|`pidFilename`|`PID_FOLDER`里pid文件名的默认值,只对`init.d`服务有效| +|`useStartStopDaemon`|如果`start-stop-daemon`命令可用,它会控制该实例,默认为`true`| +|`stopWaitTime`|`STOP_WAIT_TIME`的默认值,只对`init.d`服务有效。默认到60秒| + +**在脚本运行时自定义** + +对于需要在jar文件生成后自定义的项目,你可以使用环境变量或配置文件。 + +默认脚本支持以下环境变量: + +|变量|描述| +|:----|:----| +|`MODE`|操作的模式,默认值依赖于jar构建方式,通常为`auto`(意味着它会尝试通过检查它是否为`init.d`目录的软连接来推断这是不是一个init脚本)。你可以显式将它设置为`service`,这样`stop|start|status|restart`命令就可以工作了,或如果你只是想在前台运行该脚本那只需`run`| +|`USE_START_STOP_DAEMON`|如果`start-stop-daemon`命令可用,它将被用来控制该实例,默认为`true`| +|`PID_FOLDER`|pid文件夹的根目录(默认为`/var/run`)| +|`LOG_FOLDER`|存放日志文件的文件夹(默认为`/var/log`)| +|`CONF_FOLDER`|读取`.conf`文件的文件夹| +|`LOG_FILENAME`|存放于`LOG_FOLDER`的日志文件名(默认为`.log`)| +|`APP_NAME`|应用名,如果jar运行自一个软连接,脚本会猜测它的应用名。如果不是软连接,或你想显式设置应用名,这就很有用了| +|`RUN_ARGS`|传递给程序的参数(Spring Boot应用)| +|`JAVA_HOME`|默认使用`PATH`指定`java`的位置,但如果在`$JAVA_HOME/bin/java`有可执行文件,你可以通过该属性显式设置| +|`JAVA_OPTS`|JVM启动时传递的配置项| +|`JARFILE`|在脚本启动没内嵌其内的jar文件时显式设置jar位置| +|`DEBUG`|如果shell实例的`-x`标识有设值,则你能轻松看到脚本的处理逻辑| +|`STOP_WAIT_TIME`|强制关闭应用之前的等待时间,单位为秒(默认为`60`秒)| + +**注** `PID_FOLDER`,`LOG_FOLDER`和`LOG_FILENAME`变量只对`init.d`服务有效。对于`systemd`等价的自定义方式是使用‘service’脚本。有关详细信息,请参阅[服务单元配置手册页](https://www.freedesktop.org/software/systemd/man/systemd.service.html)。 + +如果`JARFILE`和`APP_NAME`出现异常,上面的设置可以使用一个`.conf`文件进行配置。该文件预期是放到跟jar文件临近的地方,并且名字相同,但后缀为`.conf`而不是`.jar`。例如,一个命名为`/var/myapp/myapp.jar`的jar将使用名为`/var/myapp/myapp.conf`的配置文件: + +**myapp.conf** +```properties +JAVA_OPTS=-Xmx1024M +LOG_FOLDER=/custom/log/folder +``` +**注** 如果不喜欢配置文件放到jar附近,你可以使用`CONF_FOLDER`环境变量指定文件的位置。 + +想要学习如何正确的保护文件可以参考[the guidelines for securing an init.d service.](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#deployment-initd-service-securing)。 diff --git a/VI. Deploying Spring Boot Applications/61.3 Microsoft Windows Services.md b/VI. Deploying Spring Boot Applications/61.3 Microsoft Windows Services.md new file mode 100644 index 00000000..82e69f7f --- /dev/null +++ b/VI. Deploying Spring Boot Applications/61.3 Microsoft Windows Services.md @@ -0,0 +1,5 @@ +### 61.3 Microsoft Windows服务 + +在Window上,你可以使用[winsw](https://github.com/kohsuke/winsw)启动Spring Boot应用。 + +这里有个单独维护的[示例](https://github.com/snicoll-scratches/spring-boot-daemon)为你演示了怎么一步步为Spring Boot应用创建Windows服务。 diff --git a/VI. Deploying Spring Boot Applications/62. What to Read Next.md b/VI. Deploying Spring Boot Applications/62. What to Read Next.md new file mode 100644 index 00000000..83a4df32 --- /dev/null +++ b/VI. Deploying Spring Boot Applications/62. What to Read Next.md @@ -0,0 +1,5 @@ +### 62. 接下来阅读什么 + +打开[Cloud Foundry](https://www.cloudfoundry.com/),[Heroku](https://www.heroku.com/),[OpenShift](https://www.openshift.com/)和[Boxfuse](https://boxfuse.com/)网站获取更多Paas能提供的特性信息。这里只提到4个比较流行的Java PaaS提供商,由于Spring Boot遵从基于云的部署原则,所以你也可以自由考虑其他提供商。 + +下章节将继续讲解[Spring Boot CLI](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#cli)。你也可以直接跳到[构建工具插件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#build-tool-plugins)。 diff --git a/VI. Deploying Spring Boot applications/README.md b/VI. Deploying Spring Boot Applications/README.md similarity index 100% rename from VI. Deploying Spring Boot applications/README.md rename to VI. Deploying Spring Boot Applications/README.md diff --git a/VI. Deploying Spring Boot applications/58. Deploying to the cloud.md b/VI. Deploying Spring Boot applications/58. Deploying to the cloud.md deleted file mode 100644 index 11f67a10..00000000 --- a/VI. Deploying Spring Boot applications/58. Deploying to the cloud.md +++ /dev/null @@ -1,8 +0,0 @@ -###58. 部署到云端 -对于大多数流行云PaaS(平台即服务)提供商,Spring Boot的可执行jars就是为它们准备的。这些提供商往往要求你自己提供容器,它们只负责管理应用的进程(不特别针对Java应用程序),所以它们需要一些中间层来将你的应用适配到云概念中的一个运行进程。 - -两个流行的云提供商,Heroku和Cloud Foundry,采取一个打包('buildpack')方法。为了启动你的应用程序,不管需要什么,buildpack都会将它们打包到你的部署代码:它可能是一个JDK和一个java调用,也可能是一个内嵌的webserver,或者是一个成熟的应用服务器。buildpack是可插拔的,但你最好尽可能少的对它进行自定义设置。这可以减少不受你控制的功能范围,最小化部署和生产环境的发散。 - -理想情况下,你的应用就像一个Spring Boot可执行jar,所有运行需要的东西都打包到它内部。 - -本章节我们将看到在“Getting Started”章节开发的简单应用是怎么在云端运行的。 diff --git a/VI. Deploying Spring Boot applications/58.1 Cloud Foundry.md b/VI. Deploying Spring Boot applications/58.1 Cloud Foundry.md deleted file mode 100644 index 48803fc7..00000000 --- a/VI. Deploying Spring Boot applications/58.1 Cloud Foundry.md +++ /dev/null @@ -1,49 +0,0 @@ -### 58.1 Cloud Foundry - -如果不指定其他打包方式,Cloud Foundry会启用它提供的默认打包方式。Cloud Foundry的[Java buildpack](https://github.com/cloudfoundry/java-buildpack)对Spring应用有出色的支持,包括Spring Boot。你可以部署独立的可执行jar应用,也可以部署传统的`.war`形式的应用。 - -一旦你构建应用(比如,使用`mvn clean package`)并[安装`cf`命令行工具](http://docs.cloudfoundry.org/devguide/installcf/install-go-cli.html),你可以使用下面的`cf push`命令(将路径指向你编译后的`.jar`)来部署应用。在发布应用前,确保[你已登陆cf命令行客户端](http://docs.cloudfoundry.org/devguide/installcf/whats-new-v6.html#login)。 -```shell -$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar -``` -查看[`cf push`文档](http://docs.cloudfoundry.org/devguide/installcf/whats-new-v6.html#push)获取更多可选项。如果相同目录下存在[manifest.yml](http://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html),Cloud Foundry会使用它。 - -就此,`cf`将开始上传你的应用: -```java -Uploading acloudyspringtime... OK -Uploading acloudyspringtime... OK -Preparing to start acloudyspringtime... OK ------> Downloaded app package (8.9M) ------> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e ------> Downloading Open Jdk JRE 1.8.0_121 from https://java-buildpack.cloudfoundry.org/openjdk/trusty/x86_64/openjdk-1.8.0_121.tar.gz (found in cache) - Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s) ------> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache) - Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K ------> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache) - Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s) ------> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache) -Checking status of app 'acloudyspringtime'... - 0 of 1 instances running (1 starting) - ... - 0 of 1 instances running (1 starting) - ... - 0 of 1 instances running (1 starting) - ... - 1 of 1 instances running (1 running) - -App started -``` -恭喜!应用现在处于运行状态! - -检验部署应用的状态是很简单的: -```shell -$ cf apps -Getting applications in ... -OK - -name requested state instances memory disk urls -... -acloudyspringtime started 1/1 512M 1G acloudyspringtime.cfapps.io -... -``` -一旦Cloud Foundry意识到你的应用已经部署,你就可以点击给定的应用URI,此处是[acloudyspringtime.cfapps.io/](http://acloudyspringtime.cfapps.io/)。 diff --git a/VI. Deploying Spring Boot applications/58.1.1 Binding to services.md b/VI. Deploying Spring Boot applications/58.1.1 Binding to services.md deleted file mode 100644 index 67f3f803..00000000 --- a/VI. Deploying Spring Boot applications/58.1.1 Binding to services.md +++ /dev/null @@ -1,23 +0,0 @@ -### 58.1.1 绑定服务 - -默认情况下,运行应用的元数据和服务连接信息被暴露为应用的环境变量(比如`$VCAP_SERVICES`),采用这种架构的原因是因为Cloud Foundry多语言特性(任何语言和平台都支持作为buildpack),进程级别的环境变量是语言无关(language agnostic)的。 - -环境变量并不总是有利于设计最简单的API,所以Spring Boot自动提取它们,然后将这些数据导入能够通过Spring `Environment`抽象访问的属性里: -```java -@Component -class MyBean implements EnvironmentAware { - - private String instanceId; - - @Override - public void setEnvironment(Environment environment) { - this.instanceId = environment.getProperty("vcap.application.instance_id"); - } - - // ... - -} -``` -所有的Cloud Foundry属性都以`vcap`作为前缀,你可以使用vcap属性获取应用信息(比如应用的公共URL)和服务信息(比如数据库证书),具体参考`CloudFoundryVcapEnvironmentPostProcessor` Javadoc。 - -**注**:[Spring Cloud Connectors](http://cloud.spring.io/spring-cloud-connectors/)项目很适合比如配置数据源的任务,Spring Boot为它提供了自动配置支持和一个`spring-boot-starter-cloud-connectors` starter。 diff --git a/VI. Deploying Spring Boot applications/58.2 Heroku.md b/VI. Deploying Spring Boot applications/58.2 Heroku.md deleted file mode 100644 index 0b7f5ad8..00000000 --- a/VI. Deploying Spring Boot applications/58.2 Heroku.md +++ /dev/null @@ -1,56 +0,0 @@ -###58.2 Heroku -Heroku是另外一个流行的Paas平台,你可以提供一个`Procfile`来定义Heroku的构建过程,它提供部署应用所需的指令。Heroku为Java应用分配一个端口,确保能够路由到外部URI。 - -你必须配置你的应用监听正确的端口,下面是用于我们的starter REST应用的`Procfile`: -```shell -web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar -``` -Spring Boot将`-D`参数作为属性,通过Spring `Environment`实例访问。`server.port`配置属性适合于内嵌的Tomcat,Jetty或Undertow实例启用时使用,`$PORT`环境变量被分配给Heroku Paas使用。 - -这就是你需要做的所有内容,对于Heroku部署来说,经常做的工作就是使用`git push`将代码推送到生产环境。 -```shell -$ git push heroku master - -Initializing repository, done. -Counting objects: 95, done. -Delta compression using up to 8 threads. -Compressing objects: 100% (78/78), done. -Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, done. -Total 95 (delta 31), reused 0 (delta 0) - ------> Java app detected ------> Installing OpenJDK 1.8... done ------> Installing Maven 3.3.1... done ------> Installing settings.xml... done ------> executing /app/tmp/cache/.maven/bin/mvn -B - -Duser.home=/tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229 - -Dmaven.repo.local=/app/tmp/cache/.m2/repository - -s /app/tmp/cache/.m2/settings.xml -DskipTests=true clean install - - [INFO] Scanning for projects... - Downloading: http://repo.spring.io/... - Downloaded: http://repo.spring.io/... (818 B at 1.8 KB/sec) - .... - Downloaded: http://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec) - [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/... - [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ... - [INFO] ------------------------------------------------------------------------ - [INFO] BUILD SUCCESS - [INFO] ------------------------------------------------------------------------ - [INFO] Total time: 59.358s - [INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014 - [INFO] Final Memory: 20M/493M - [INFO] ------------------------------------------------------------------------ - ------> Discovering process types - Procfile declares types -> web - ------> Compressing... done, 70.4MB ------> Launching... done, v6 - http://agile-sierra-1405.herokuapp.com/ deployed to Heroku - -To git@heroku.com:agile-sierra-1405.git - * [new branch] master -> master - -``` -现在你的应用已经启动并运行在Heroku。 diff --git a/VI. Deploying Spring Boot applications/58.3 Openshift.md b/VI. Deploying Spring Boot applications/58.3 Openshift.md deleted file mode 100644 index 9bfda368..00000000 --- a/VI. Deploying Spring Boot applications/58.3 Openshift.md +++ /dev/null @@ -1,41 +0,0 @@ -###58.3 Openshift - -[Openshift](https://www.openshift.com/)是RedHat公共(和企业)PaaS解决方案。和Heroku相似,它也是通过运行被git提交触发的脚本来工作的,所以你可以使用任何你喜欢的方式编写Spring Boot应用启动脚本,只要Java运行时环境可用(这是在Openshift上可以要求的一个标准特性)。为了实现这样的效果,你可以使用[DIY Cartridge](https://www.openshift.com/developers/do-it-yourself),并在`.openshift/action_scripts`下hooks你的仓库: - -基本模式如下: - -1.确保Java和构建工具已被远程安装,比如使用一个`pre_build` hook(默认会安装Java和Maven,不会安装Gradle)。 - -2.使用一个`build` hook去构建你的jar(使用Maven或Gradle),比如: -```shell -#!/bin/bash -cd $OPENSHIFT_REPO_DIR -mvn package -s .openshift/settings.xml -DskipTests=true -``` -3.添加一个调用`java -jar …`的`start` hook - -```shell -#!/bin/bash -cd $OPENSHIFT_REPO_DIR -nohup java -jar target/*.jar --server.port=${OPENSHIFT_DIY_PORT} --server.address=${OPENSHIFT_DIY_IP} & -``` -4.使用一个`stop` hook - -```shell -#!/bin/bash -source $OPENSHIFT_CARTRIDGE_SDK_BASH -PID=$(ps -ef | grep java.*\.jar | grep -v grep | awk '{ print $2 }') -if [ -z "$PID" ] -then - client_result "Application is already stopped" -else - kill $PID -fi -``` -5.将内嵌的服务绑定到平台提供的`application.properties`定义的环境变量,比如: -```shell -spring.datasource.url: jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_APP_NAME} -spring.datasource.username: ${OPENSHIFT_MYSQL_DB_USERNAME} -spring.datasource.password: ${OPENSHIFT_MYSQL_DB_PASSWORD} -``` -在Openshift的网站上有一篇[running Gradle in Openshift](https://www.openshift.com/blogs/run-gradle-builds-on-openshift)博客,如果想使用gradle构建运行的应用可以参考它。 diff --git "a/VI. Deploying Spring Boot applications/58.4 Amazon Web Services\357\274\210AWS\357\274\211.md" "b/VI. Deploying Spring Boot applications/58.4 Amazon Web Services\357\274\210AWS\357\274\211.md" deleted file mode 100644 index 541a77d2..00000000 --- "a/VI. Deploying Spring Boot applications/58.4 Amazon Web Services\357\274\210AWS\357\274\211.md" +++ /dev/null @@ -1,11 +0,0 @@ -### 58.4 亚马逊网络服务(AWS) - -亚马逊网络服务提供了多种安装基于Spring Boot的应用的方式, 比如传统的网络应用(war),又比如内嵌网络服务器的可执行jar文件。选项包括: - -- AWS Elastic Beanstalk -- AWS Code Deploy -- AWS OPS Works -- AWS Cloud Formation -- AWS Container Registry - -每个选项都有不同的特点和定价模式。在这里,我们只描述最简单的选项:AWS Elastic Beanstalk。 \ No newline at end of file diff --git a/VI. Deploying Spring Boot applications/58.4.1 AWS Elastic Beanstalk.md b/VI. Deploying Spring Boot applications/58.4.1 AWS Elastic Beanstalk.md deleted file mode 100644 index 7f097bc8..00000000 --- a/VI. Deploying Spring Boot applications/58.4.1 AWS Elastic Beanstalk.md +++ /dev/null @@ -1,28 +0,0 @@ -### 58.4.1 AWS Elastic Beanstalk - -就像在官方的[Elastic Beanstalk Java指南](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html)里描述的那样,有两种主要的方式来部署Java应用。你可以使用““Tomcat平台”或者“Java SE平台”。 - -**使用Tomcat平台** - -这个选项适用于产生war文件的Spring Boot工程。不需要任何特殊的配置,按照官方的指南一步步来就好。 - -**使用Java SE平台** - -这个选项适用于产生jar文件并运行一个内嵌的网络容器的Spring Boot工程。Elastic Beanstalk环境在80端口上运行一个nginx实例,来代理运行在5000端口上的实际的应用。在你的`application.properties`中加入以下内容,来进行配置: -```properties -server.port=5000 -``` -**最佳实践** - -**上传二进制文件代替源码** - -默认地,Elastic Beanstalk上传源码并在AWS进行编译。为了上传二进制文件作为替代,在你的`.elasticbeanstalk/config.yml`文件中加入以下内容: -```properties -deploy: - artifact: target/demo-0.0.1-SNAPSHOT.jar -Reduce costs by setting the environment type -``` -默认地,Elastic Beanstalk环境负载均衡。负载均衡器会优先考虑成本,为了避免这个,按照[亚马逊文档](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity)里描述的那样,设置环境类型为“单个实例”。单个实例环境可以使用CLI或者以下命令进行创建: -```command -eb create -s -``` \ No newline at end of file diff --git a/VI. Deploying Spring Boot applications/58.4.2 Summary.md b/VI. Deploying Spring Boot applications/58.4.2 Summary.md deleted file mode 100644 index 289a24df..00000000 --- a/VI. Deploying Spring Boot applications/58.4.2 Summary.md +++ /dev/null @@ -1,3 +0,0 @@ -### 58.4.2 总结 - -这是接触AWS的最简单的方式之一,但还有更多的事情需要考虑。比如,怎么样使用Elastic Beanstalk maven插件代替CLI,把Elastic Beanstalk集成到CI/CD工具中,等等。有一个[博客](https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/)详细地讨论了这些主题。 \ No newline at end of file diff --git a/VI. Deploying Spring Boot applications/58.5 Boxfuse and Amazon Web Services.md b/VI. Deploying Spring Boot applications/58.5 Boxfuse and Amazon Web Services.md deleted file mode 100644 index f42aee61..00000000 --- a/VI. Deploying Spring Boot applications/58.5 Boxfuse and Amazon Web Services.md +++ /dev/null @@ -1,35 +0,0 @@ -### 58.5 Boxfuse和亚马逊网络服务 - -[Boxfuse](https://boxfuse.com/)的工作机制是将你的Spring Boot可执行jar或war转换进一个最小化的VM镜像,该镜像不需改变就能部署到VirtualBox或AWS。Boxfuse深度集成Spring Boot并使用你的Spring Boot配置文件自动配置端口和健康检查URLs,它将该信息用于产生的镜像及它提供的所有资源(实例,安全分组,可伸缩的负载均衡等)。 - -一旦创建一个[Boxfuse account](https://console.boxfuse.com/),并将它连接到你的AWS账号,安装最新版Boxfuse客户端,你就能按照以下操作将Spring Boot应用部署到AWS(首先要确保应用被Maven或Gradle构建过,比如`mvn clean package`): -```shell -$ boxfuse run myapp-1.0.jar -env=prod -``` -更多选项可查看[`boxfuse run`文档](https://boxfuse.com/docs/commandline/run.html),如果当前目录存在一个[boxfuse.conf](https://boxfuse.com/docs/commandline/#configuration)文件,Boxfuse将使用它。 - -**注** 如果你的可执行jar或war包含[`application-boxfuse.properties`](https://boxfuse.com/docs/payloads/springboot.html#configuration)文件,Boxfuse默认在启动时会激活一个名为`boxfuse`的Spring profile,然后在该profile包含的属性基础上构建自己的配置。 - -此刻`boxfuse`将为你的应用创建一个镜像并上传到AWS,然后配置并启动需要的资源: -```shell -Fusing Image for myapp-1.0.jar ... -Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0 -Creating axelfontaine/myapp ... -Pushing axelfontaine/myapp:1.0 ... -Verifying axelfontaine/myapp:1.0 ... -Creating Elastic IP ... -Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ... -Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ... -AMI created in 00:23.557s -> ami-d23f38cf -Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ... -Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ... -Instance launched in 00:30.306s -> i-92ef9f53 -Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at http://52.28.235.61/ ... -Payload started in 00:29.266s -> http://52.28.235.61/ -Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ... -Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ... -Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at http://myapp-axelfontaine.boxfuse.io/ -``` -你的应用现在应该已经在AWS上启动并运行了。 - -这里有篇[在EC2部署Spring Boot应用](https://boxfuse.com/blog/spring-boot-ec2.html)的博客,Boxfuse官网也有[Boxfuse集成Spring Boot文档](https://boxfuse.com/docs/payloads/springboot.html),你可以拿来作为参考。 diff --git a/VI. Deploying Spring Boot applications/58.6 Google App Engine.md b/VI. Deploying Spring Boot applications/58.6 Google App Engine.md deleted file mode 100644 index 61b64f9c..00000000 --- a/VI. Deploying Spring Boot applications/58.6 Google App Engine.md +++ /dev/null @@ -1,3 +0,0 @@ -### 58.6 Google App Engine - -Google App Engine关联了Servlet 2.5 API,如果不做一些修改你是不能在其上部署Spring应用的,具体查看本指南的[Servlet 2.5章节](../IX. ‘How-to’ guides/81.5. Deploying a WAR in an Old (Servlet 2.5) Container.md)。 diff --git a/VI. Deploying Spring Boot applications/59. Installing Spring Boot applications.md b/VI. Deploying Spring Boot applications/59. Installing Spring Boot applications.md deleted file mode 100644 index 7cc163fe..00000000 --- a/VI. Deploying Spring Boot applications/59. Installing Spring Boot applications.md +++ /dev/null @@ -1,25 +0,0 @@ -### 59. 安装Spring Boot应用 - -除了使用`java -jar`运行Spring Boot应用,制作在Unix系统上完全可执行的应用也是可能的。完全可执行的jar可以像其它的可执行二进制文件一样被执行,或者可以用`init.d或systemd进行注册`。这会简化常见生产环境Spring Boot应用的安装和管理。 - -**警告⚠️** 通过在文件之前嵌入一段额外的脚本,来启动完全可执行的Jar。目前,一些工具尚不接受这种格式,所以你并不总是能够使用这项技术。比如,`jar -xf`可能会在解压一个完全可执行的jar或者war文件时悄悄地失败。建议你仅在想要直接执行它的情况下,将你的jar或者war文件制作为完全可执行的格式。不要在只是想要使用`java -jar`运行它,或者在一个servlet容器部署它的时候这样做。 - -在Maven中添加以下plugin配置可以创建一个"完全可执行"jar: -```xml - - org.springframework.boot - spring-boot-maven-plugin - - true - - -``` -对于Gradle等价的配置如下: -```shell -apply plugin: 'spring-boot' - -springBoot { - executable = true -} -``` -然后输入`./my-application.jar`运行应用(`my-application`是你的artifact name)。包含jar文件的目录会被当作你的应用工作目录使用。 \ No newline at end of file diff --git a/VI. Deploying Spring Boot applications/59.1 Supported operating systems.md b/VI. Deploying Spring Boot applications/59.1 Supported operating systems.md deleted file mode 100644 index 728525a3..00000000 --- a/VI. Deploying Spring Boot applications/59.1 Supported operating systems.md +++ /dev/null @@ -1,3 +0,0 @@ -### 59.1 支持的操作系统 - -默认的脚本支持大部分的Linux发行版,同时在CentOS和Ubuntu上进行了测试。其它的平台,比如OS X和FreeBSD将会需要使用自定义的`embeddedLaunchScript`。 diff --git a/VI. Deploying Spring Boot applications/59.2 Unix&Linux services.md b/VI. Deploying Spring Boot applications/59.2 Unix&Linux services.md deleted file mode 100644 index 8bd35ff6..00000000 --- a/VI. Deploying Spring Boot applications/59.2 Unix&Linux services.md +++ /dev/null @@ -1,3 +0,0 @@ -### 59.2 Unix/Linux服务 - -你可以使用`init.d`或`systemd`启动Spring Boot应用,就像其他Unix/Linux服务那样。 diff --git "a/VI. Deploying Spring Boot applications/59.2.1 Installation as an init.d service\357\274\210System V\357\274\211.md" "b/VI. Deploying Spring Boot applications/59.2.1 Installation as an init.d service\357\274\210System V\357\274\211.md" deleted file mode 100644 index 83e84abd..00000000 --- "a/VI. Deploying Spring Boot applications/59.2.1 Installation as an init.d service\357\274\210System V\357\274\211.md" +++ /dev/null @@ -1,49 +0,0 @@ -### 59.2.1 安装为init.d服务(System V) - -如果你配置Spring Boot的Maven或Gradle插件产生一个[完全可执行jar](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#deployment-install),并且没有使用自定义的`embeddedLaunchScript`,那你的应用可以作为`init.d`服务使用。只要简单的建立jar到`init.d`的符号连接就能获取标准的`start`,`stop`,`restart `和`status`命令支持。 - -该脚本支持以下特性: -- 以拥有该jar文件的用户启动服务。 -- 使用`/var/run//.pid`跟踪应用的PID。 -- 将控制台日志输出到`/var/log/.log`。 - -假设你在`/var/myapp`目录安装了一个Spring Boot应用,只需要建立符号连接就能将Spring Boot应用安装成`init.d`服务: -```shell -$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp -``` -一旦安装成功,你就可以像平常那样启动和停止服务,例如,在一个基于Debian的系统: -```shell -$ service myapp start -``` -**注** 如果应用启动失败,检查下`/var/log/.log`中的错误日志。 - -你也可以标识应用使用标准的操作系统工具自启动,例如,在Debian上: -```shell -$ update-rc.d myapp defaults -``` - -**保护init.d服务** - -当使用`root`用户启动`init.d`服务时,默认的执行脚本将以拥有该jar文件的用户来运行应用。你最好不要使用`root`启动Spring Boot应用,也就是你的应用jar文件拥有者不能是`root`,而是创建一个特定用户运行应用,并使用`chown`指定该用户拥有jar文件,示例: -```shell -$ chown bootapp:bootapp your-app.jar -``` -本示例中,默认执行脚本将使用`bootapp`用户运行应用。 - -**注** 为减少应用用户账号冲突,你可以考虑防止它使用登陆shell,例如将账号shell设置为`/usr/sbin/nologin`。 - -你也要采取措施防止修改应用jar文件,首先配置jar文件权限只能被拥有者读取和执行,不能写入: -```shell -$ chmod 500 your-app.jar -``` -然后,你也应该采取措施限制应用或账号运行时的冲突造成的损坏。如果攻击者获取访问权,他们可能会让jar文件可写并改变它的内容,使用`chattr`让它变为不可变是唯一的保护措施: -```shell -$ sudo chattr +i your-app.jar -``` -这会防止任何用户修改jar文件,包括root。 - -如果root用户用来控制应用服务,并且你使用[.conf文件](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#deployment-script-customization-conf-file)自定义它的启动,该`.conf`文件将被root用户读取和评估,因此它也需要保护。使用`chmod`改变文件权限只能被拥有者读取,然后使用`chown`改变文件拥有者为root: -```shell -$ chmod 400 your-app.conf -$ sudo chown root:root your-app.conf -``` diff --git a/VI. Deploying Spring Boot applications/59.2.2 Installation as a systemd service.md b/VI. Deploying Spring Boot applications/59.2.2 Installation as a systemd service.md deleted file mode 100644 index 7247a902..00000000 --- a/VI. Deploying Spring Boot applications/59.2.2 Installation as a systemd service.md +++ /dev/null @@ -1,29 +0,0 @@ -### 59.2.2 安装为Systemd服务 - -Systemd是System V init系统的继任者,很多现代Linux分发版本都在使用,尽管你可以继续使用`init.d`脚本,但使用`systemd` ‘service’脚本启动Spring Boot应用是有可能的。 - -假设你在`/var/myapp`目录下安装一个Spring Boot应用,为了将它安装为一个`systemd`服务,你需要按照以下示例创建一个脚本,比如命名为`myapp.service`,然后将它放到`/etc/systemd/system`目录下: -```shell -[Unit] -Description=myapp -After=syslog.target - -[Service] -User=myapp -ExecStart=/var/myapp/myapp.jar -SuccessExitStatus=143 - -[Install] -WantedBy=multi-user.target -``` -**提示** 记得根据你的应用改变`Description`,`User`和`ExecStart`字段。 - -**提示** 注意`ExecStart`字段没有声明脚本行动命令,也就是说会使用默认的`run`命令。 - -注意跟作为`init.d`服务运行不同,使用`systemd`这种方式运行应用,PID文件和控制台日志文件是由系统自己进行管理的,因此必须在‘service’脚本配置正确的字段,具体参考[service unit configuration man page](http://www.freedesktop.org/software/systemd/man/systemd.service.html)。 - -使用以下命令标识应用自动在系统boot上启动: -```shell -$ systemctl enable myapp.service -``` -具体详情可参考`man systemctl`。 diff --git a/VI. Deploying Spring Boot applications/59.2.3 Customizing the startup script.md b/VI. Deploying Spring Boot applications/59.2.3 Customizing the startup script.md deleted file mode 100644 index 8ecf1565..00000000 --- a/VI. Deploying Spring Boot applications/59.2.3 Customizing the startup script.md +++ /dev/null @@ -1,65 +0,0 @@ -### 59.2.3 自定义启动脚本 - -Maven或Gradle插件生成的默认内嵌启动脚本可以通过很多方法自定义,对于大多数开发者,使用默认脚本和一些自定义通常就足够了。如果发现不能自定义需要的东西,你可以使用`embeddedLaunchScript`选项生成自己的文件。 - -**在脚本生成时自定义** - -自定义写入jar文件的启动脚本元素是有意义的,例如,为`init.d`脚本提供`description`,既然知道这会展示到前端,你可能会在生成jar时提供它。 - -为了自定义写入的元素,你需要为Spring Boot Maven或Gradle插件指定`embeddedLaunchScriptProperties`选项。 - -以下是默认脚本支持的可代替属性: - -|名称|描述| -|:----|:----| -|`mode`|脚本模式,默认为`auto`| -|`initInfoProvides`|'INIT INFO'部分的`Provides`,对于Gradle默认为`spring-boot-application`,对于Maven默认为`${project.artifactId}`| -|`initInfoRequiredStart`|'INIT INFO'部分的`Required-Start`,默认为`$remote_fs $syslog $network`| -|`initInfoRequiredStop`|'INIT INFO'部分的`Required-Stop`,默认为`$remote_fs $syslog $network`| -|`initInfoDefaultStart`|'INIT INFO'部分的`Default-Start`,默认为`2 3 4 5`| -|`initInfoDefaultStop`|'INIT INFO'部分的`Default-Stop`,默认为`0 1 6`| -|`initInfoShortDescription`|‘INIT INFO’部分的`Short-Description`,对于Gradle默认为`Spring Boot Application`,对于Maven默认为`${project.name}`| -|`initInfoDescription`|“INIT INFO”部分的`Description`,对于Gradle默认为`Spring Boot Application`,对于Maven默认为`${project.description}`(失败会回退到`${project.name}`)| -|`initInfoChkconfig`|“INIT INFO”部分的`chkconfig`,默认为`2345 99 01`| -|`confFolder`|`CONF_FOLDER`的默认值,默认为包含jar的文件夹| -|`logFolder`|`LOG_FOLDER`的默认值,只对`init.d`服务有效| -|`logFilename`|`LOG_FILENAME`的默认值,只对`init.d`服务有效| -|`pidFolder`|`PID_FOLDER`的默认值,只对`init.d`服务有效| -|`pidFilename`|`PID_FOLDER`里pid文件名的默认值,只对`init.d`服务有效| -|`useStartStopDaemon`|如果`start-stop-daemon`命令可用,它会控制该实例,默认为`true`| -|`stopWaitTime`|`STOP_WAIT_TIME`的默认值,只对`init.d`服务有效。默认到60秒| - -**在脚本运行时自定义** - -对于需要在jar文件生成后自定义的项目,你可以使用环境变量或配置文件。 - -默认脚本支持以下环境变量: - -|变量|描述| -|:----|:----| -|`MODE`|操作的模式,默认值依赖于jar构建方式,通常为`auto`(意味着它会尝试通过检查它是否为`init.d`目录的软连接来推断这是不是一个init脚本)。你可以显式将它设置为`service`,这样`stop|start|status|restart`命令就可以工作了,或如果你只是想在前台运行该脚本那只需`run`| -|`USE_START_STOP_DAEMON`|如果`start-stop-daemon`命令可用,它将被用来控制该实例,默认为`true`| -|`PID_FOLDER`|pid文件夹的根目录(默认为`/var/run`)| -|`LOG_FOLDER`|存放日志文件的文件夹(默认为`/var/log`)| -|`CONF_FOLDER`|读取`.conf`文件的文件夹| -|`LOG_FILENAME`|存放于`LOG_FOLDER`的日志文件名(默认为`.log`)| -|`APP_NAME`|应用名,如果jar运行自一个软连接,脚本会猜测它的应用名。如果不是软连接,或你想显式设置应用名,这就很有用了| -|`RUN_ARGS`|传递给程序的参数(Spring Boot应用)| -|`JAVA_HOME`|默认使用`PATH`指定`java`的位置,但如果在`$JAVA_HOME/bin/java`有可执行文件,你可以通过该属性显式设置| -|`JAVA_OPTS`|JVM启动时传递的配置项| -|`JARFILE`|在脚本启动没内嵌其内的jar文件时显式设置jar位置| -|`DEBUG`|如果shell实例的`-x`标识有设值,则你能轻松看到脚本的处理逻辑| -|`STOP_WAIT_TIME`|强制关闭应用之前的等待时间,单位为秒(默认为`60`秒)| - -**注** `PID_FOLDER`,`LOG_FOLDER`和`LOG_FILENAME`变量只对`init.d`服务有效。对于`systemd`等价的自定义方式是使用‘service’脚本。 - -如果`JARFILE`和`APP_NAME`出现异常,上面的设置可以使用一个`.conf`文件进行配置。该文件预期是放到跟jar文件临近的地方,并且名字相同,但后缀为`.conf`而不是`.jar`。例如,一个命名为`/var/myapp/myapp.jar`的jar将使用名为`/var/myapp/myapp.conf`的配置文件: - -**myapp.conf** -```properties -JAVA_OPTS=-Xmx1024M -LOG_FOLDER=/custom/log/folder -``` -**注** 如果不喜欢配置文件放到jar附近,你可以使用`CONF_FOLDER`环境变量指定文件的位置。 - -想要学习如何正确的保护文件可以参考[the guidelines for securing an init.d service.](the guidelines for securing an init.d service)。 diff --git a/VI. Deploying Spring Boot applications/59.3 Microsoft Windows services.md b/VI. Deploying Spring Boot applications/59.3 Microsoft Windows services.md deleted file mode 100644 index 1864310e..00000000 --- a/VI. Deploying Spring Boot applications/59.3 Microsoft Windows services.md +++ /dev/null @@ -1,3 +0,0 @@ -### 59.3 Microsoft Windows服务 - -在Window上,你可以使用[winsw](https://github.com/kohsuke/winsw)启动Spring Boot应用。这里有个单独维护的[示例](https://github.com/snicoll-scratches/spring-boot-daemon)为你演示了怎么一步步为Spring Boot应用创建Windows服务。 diff --git a/VI. Deploying Spring Boot applications/60. What to read next.md b/VI. Deploying Spring Boot applications/60. What to read next.md deleted file mode 100644 index dc2138f9..00000000 --- a/VI. Deploying Spring Boot applications/60. What to read next.md +++ /dev/null @@ -1,5 +0,0 @@ -### 60. 接下来阅读什么 - -打开[Cloud Foundry](http://www.cloudfoundry.com/),[Heroku](https://www.heroku.com/),[OpenShift](https://www.openshift.com/)和[Boxfuse](https://boxfuse.com/)网站获取更多Paas能提供的特性信息。这里只提到4个比较流行的Java PaaS提供商,由于Spring Boot遵从基于云的部署原则,所以你也可以自由考虑其他提供商。 - -下章节将继续讲解[Spring Boot CLI](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#cli),你也可以直接跳到[build tool plugins](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#build-tool-plugins)。 diff --git a/VII. Spring Boot CLI/61. Installing the CLI.md b/VII. Spring Boot CLI/61. Installing the CLI.md deleted file mode 100644 index d7e6f881..00000000 --- a/VII. Spring Boot CLI/61. Installing the CLI.md +++ /dev/null @@ -1,3 +0,0 @@ -### 61. 安装CLI - -你可以手动安装Spring Boot CLI,也可以使用SDKMAN!(SDK管理器)或Homebrew,MacPorts(如果你是一个OSX用户),具体安装指令参考"Getting started"的[Section 10.2, “Installing the Spring Boot CLI” ](../II. Getting started/10.2. Installing the Spring Boot CLI.md)章节。 diff --git a/VII. Spring Boot CLI/62. Using the CLI.md b/VII. Spring Boot CLI/62. Using the CLI.md deleted file mode 100644 index 2a4df107..00000000 --- a/VII. Spring Boot CLI/62. Using the CLI.md +++ /dev/null @@ -1,41 +0,0 @@ -### 62. 使用CLI - -一旦安装好CLI,你可以输入`spring`来运行它。如果不使用任何参数运行`spring`,将会展现一个简单的帮助界面: -```shell -$ spring -usage: spring [--help] [--version] - [] - -Available commands are: - - run [options] [--] [args] - Run a spring groovy script - - ... more command help is shown here -``` -你可以使用`help`获取任何支持命令的详细信息,例如: -```shell -$ spring help run -spring run - Run a spring groovy script - -usage: spring run [options] [--] [args] - -Option Description ------- ----------- ---autoconfigure [Boolean] Add autoconfigure compiler - transformations (default: true) ---classpath, -cp Additional classpath entries --e, --edit Open the file with the default system - editor ---no-guess-dependencies Do not attempt to guess dependencies ---no-guess-imports Do not attempt to guess imports --q, --quiet Quiet logging --v, --verbose Verbose logging of dependency - resolution ---watch Watch the specified file for changes -``` -`version`命令提供一个检查你正在使用的Spring Boot版本的快速方式: -```shell -$ spring version -Spring CLI v2.0.0.M5 -``` diff --git a/VII. Spring Boot CLI/62.1. Running applications using the CLI.md b/VII. Spring Boot CLI/62.1. Running applications using the CLI.md deleted file mode 100644 index a7d23e8a..00000000 --- a/VII. Spring Boot CLI/62.1. Running applications using the CLI.md +++ /dev/null @@ -1,30 +0,0 @@ -### 62.1 使用CLI运行应用 - -你可以使用`run`命令编译和运行Groovy源代码。Spring Boot CLI完全自包含,以致于你不需要安装任何外部的Groovy。 - -下面是一个使用Groovy编写的"hello world" web应用: - -hello.grooy -```java -@RestController -class WebApplication { - - @RequestMapping("/") - String home() { - "Hello World!" - } - -} -``` -编译和运行应用可以输入: -```shell -$ spring run hello.groovy -``` -你可以使用`--`将命令行参数和"spring"命令参数区分开来,例如: -```shell -$ spring run hello.groovy -- --server.port=9000 -``` -你可以使用`JAVA_OPTS`环境变量设置JVM命令行参数,例如: -```shell -$ JAVA_OPTS=-Xmx1024m spring run hello.groovy -``` diff --git "a/VII. Spring Boot CLI/62.1.1 Deduced \342\200\234grab\342\200\235 dependencies.md" "b/VII. Spring Boot CLI/62.1.1 Deduced \342\200\234grab\342\200\235 dependencies.md" deleted file mode 100644 index 29e05b4b..00000000 --- "a/VII. Spring Boot CLI/62.1.1 Deduced \342\200\234grab\342\200\235 dependencies.md" +++ /dev/null @@ -1,25 +0,0 @@ -###62.1.1 推断"grab"依赖 - -标准的Groovy包含一个`@Grab`注解,它允许你声明对第三方库的依赖。这项有用的技术允许Groovy以和Maven或Gradle相同的方式下载jars,但不需要使用构建工具。 - -Spring Boot进一步延伸了该技术,它会基于你的代码尝试推导你"grab"哪个库。例如,由于`WebApplication`代码上使用了`@RestController`注解,"Tomcat"和"Spring MVC"将被获取(grabbed)。 - -下面items被用作"grab hints": - -|items|Grabs| -|-----|:-----| -|`JdbcTemplate`,`NamedParameterJdbcTemplate`,`DataSource`|JDBC应用| -|`@EnableJms`|JMS应用| -|`@EnableCaching`|缓存抽象| -|`@Test`|JUnit| -|`@EnableRabbit`|RabbitMQ| -|`@EnableReactor`|项目重构| -|extends `Specification`|Spock test| -|`@EnableBatchProcessing`|Spring Batch| -|`@MessageEndpoint`,`@EnableIntegrationPatterns`|Spring集成| -|`@EnableDeviceResolver`|Spring Mobile| -|`@Controller`,`@RestController`,`@EnableWebMvc`|Spring MVC + 内嵌Tomcat| -|`@EnableWebSecurity`|Spring Security| -|`@EnableTransactionManagement`|Spring Transaction Management| - -**注** 想要理解自定义是如何生效的,可以查看Spring Boot CLI源码中的[CompilerAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java)子类。 diff --git "a/VII. Spring Boot CLI/62.1.2 Deduced \342\200\234grab\342\200\235 coordinates.md" "b/VII. Spring Boot CLI/62.1.2 Deduced \342\200\234grab\342\200\235 coordinates.md" deleted file mode 100644 index fc64afcb..00000000 --- "a/VII. Spring Boot CLI/62.1.2 Deduced \342\200\234grab\342\200\235 coordinates.md" +++ /dev/null @@ -1,2 +0,0 @@ -###62.1.2 推断"grab"坐标 -Spring Boot扩展了Groovy标准`@Grab`注解,使其能够允许你指定一个没有`group`或`version`的依赖,例如`@Grab('freemarker')`。Spring Boot使用默认依赖元数据推断artifact’s的group和version,需要注意的是默认元数据和你使用的CLI版本有绑定关系-只有在迁移到新版本的CLI时它才会改变,这样你就可以控制何时改变依赖了,在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#appendix-dependency-versions)的表格中可以查看默认元数据包含的依赖和它们的版本。 diff --git a/VII. Spring Boot CLI/62.1.3 Default import statements.md b/VII. Spring Boot CLI/62.1.3 Default import statements.md deleted file mode 100644 index 57a1bace..00000000 --- a/VII. Spring Boot CLI/62.1.3 Default import statements.md +++ /dev/null @@ -1,5 +0,0 @@ -###62.1.3 默认import语句 - -为了帮助你减少Groovy代码量,一些`import`语句被自动包含进来了。注意上面的示例中引用`@Component`,`@RestController`和`@RequestMapping`而没有使用全限定名或`import`语句。 - -**注**:很多Spring注解在不使用`import`语句的情况下可以正常工作。尝试运行你的应用,看一下在添加imports之前哪些会失败。 diff --git a/VII. Spring Boot CLI/62.1.4 Automatic main method.md b/VII. Spring Boot CLI/62.1.4 Automatic main method.md deleted file mode 100644 index b3809be9..00000000 --- a/VII. Spring Boot CLI/62.1.4 Automatic main method.md +++ /dev/null @@ -1,3 +0,0 @@ -###62.1.4 自动创建main方法 - -跟等效的Java应用不同,你不需要在Groovy脚本中添加一个`public static void main(String[] args)`方法。Spring Boot会使用你编译后的代码自动创建一个`SpringApplication`。 diff --git a/VII. Spring Boot CLI/62.1.5 Custom dependency management.md b/VII. Spring Boot CLI/62.1.5 Custom dependency management.md deleted file mode 100644 index 1e4a0a43..00000000 --- a/VII. Spring Boot CLI/62.1.5 Custom dependency management.md +++ /dev/null @@ -1,18 +0,0 @@ -### 62.1.5 自定义依赖管理 -默认情况下,CLI使用在解析`@Grab`依赖时`spring-boot-dependencies`声明的依赖管理,其他的依赖管理会覆盖默认的依赖管理,并可以通过`@DependencyManagementBom`注解进行配置。该注解的值必须是一个或多个Maven BOMs的候选(`groupId:artifactId:version`)。 - -例如,以下声明: -```grovy -@DependencyManagementBom("com.example.custom-bom:1.0.0") -``` -将选择Maven仓库中`com/example/custom-versions/1.0.0/`下的`custom-bom-1.0.0.pom`。 - -当指定多个BOMs时,它们会以声明次序进行应用,例如: -```grovy -@DependencyManagementBom(["com.example.custom-bom:1.0.0", - "com.example.another-bom:1.0.0"]) -``` -意味着`another-bom`的依赖将覆盖`custom-bom`依赖。 - -能够使用`@Grab`的地方,你同样可以使用`@DependencyManagementBom`。然而,为了确保依赖管理的一致次序,你在应用中至多使用一次`@DependencyManagementBom`。[Spring IO Platform](http://platform.spring.io/)是一个非常有用的依赖元数据源(Spring Boot的超集),例如: -`@DependencyManagementBom('io.spring.platform:platform-bom:1.1.2.RELEASE')`。 diff --git a/VII. Spring Boot CLI/62.2 Applications with multiple source files.md b/VII. Spring Boot CLI/62.2 Applications with multiple source files.md deleted file mode 100644 index a5c39f6c..00000000 --- a/VII. Spring Boot CLI/62.2 Applications with multiple source files.md +++ /dev/null @@ -1,6 +0,0 @@ -### 62.2 多源文件应用 - -你可以在所有接收文件输入的命令中使用shell通配符。这允许你轻松处理来自一个目录下的多个文件,例如: -```shell -$ spring run *.groovy -``` diff --git a/VII. Spring Boot CLI/62.3 Packaging your application.md b/VII. Spring Boot CLI/62.3 Packaging your application.md deleted file mode 100644 index c0460bb5..00000000 --- a/VII. Spring Boot CLI/62.3 Packaging your application.md +++ /dev/null @@ -1,15 +0,0 @@ -### 62.3 应用打包 - -你可以使用`jar`命令打包应用程序为一个可执行的jar文件,例如: -```shell -$ spring jar my-app.jar *.groovy -``` -最终的jar包括编译应用产生的类和所有依赖,这样你就可以使用`java -jar`来执行它了。该jar文件也包含了来自应用classpath的实体。你可以使用`--include`和`--exclude`添加明确的路径(两者都是用逗号分割,同样都接收值为'+'和'-'的前缀,'-'意味着它们将从默认设置中移除),默认包含(includes): -```shell -public/**, resources/**, static/**, templates/**, META-INF/**, * -``` -默认排除(excludes): -```shell -.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy -``` -查看`spring help jar`可以获得更多信息。 diff --git a/VII. Spring Boot CLI/62.4 Initialize a new project.md b/VII. Spring Boot CLI/62.4 Initialize a new project.md deleted file mode 100644 index d4013ece..00000000 --- a/VII. Spring Boot CLI/62.4 Initialize a new project.md +++ /dev/null @@ -1,38 +0,0 @@ -### 62.4 初始化新工程 - -`init`命令允许你使用[start.spring.io](https://start.spring.io/)在不离开shell的情况下创建一个新的项目,例如: -```shell -$ spring init --dependencies=web,data-jpa my-project -Using service at https://start.spring.io -Project extracted to '/Users/developer/example/my-project' -``` -这创建了一个`my-project`目录,它是一个基于Maven且依赖`spring-boot-starter-web`和`spring-boot-starter-data-jpa`的项目。你可以使用`--list`参数列出该服务的能力。 -```shell -$ spring init --list -======================================= -Capabilities of https://start.spring.io -======================================= - -Available dependencies: ------------------------ -actuator - Actuator: Production ready features to help you monitor and manage your application -... -web - Web: Support for full-stack web development, including Tomcat and spring-webmvc -websocket - Websocket: Support for WebSocket development -ws - WS: Support for Spring Web Services - -Available project types: ------------------------- -gradle-build - Gradle Config [format:build, build:gradle] -gradle-project - Gradle Project [format:project, build:gradle] -maven-build - Maven POM [format:build, build:maven] -maven-project - Maven Project [format:project, build:maven] (default) - -... -``` -`init`命令支持很多选项,查看`help`输出可以获得更多详情。例如,下面的命令创建一个使用Java8和打包为`war`的gradle项目: -```shell -$ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip -Using service at https://start.spring.io -Content saved to 'sample-app.zip' -``` diff --git a/VII. Spring Boot CLI/62.5 Using the embedded shell.md b/VII. Spring Boot CLI/62.5 Using the embedded shell.md deleted file mode 100644 index 77a60e8f..00000000 --- a/VII. Spring Boot CLI/62.5 Using the embedded shell.md +++ /dev/null @@ -1,13 +0,0 @@ -### 62.5 使用内嵌shell -Spring Boot包括完整的BASH和zsh shells的命令行脚本,如果这两种你都不使用(可能你是一个Window用户),那你可以使用`shell`命令启用一个集成shell。 -```shell -$ spring shell -Spring Boot (v2.0.0.M5) -Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit. -``` -从内嵌shell中可以直接运行其他命令: -```shell -$ version -Spring CLI v2.0.0.M5 -``` -内嵌shell支持ANSI彩色输出和tab补全,如果需要运行一个原生命令,你可以使用`!`前缀,点击`ctrl-c`将退出内嵌shell。 diff --git a/VII. Spring Boot CLI/62.6 Adding extensions to the CLI.md b/VII. Spring Boot CLI/62.6 Adding extensions to the CLI.md deleted file mode 100644 index 3383f8c5..00000000 --- a/VII. Spring Boot CLI/62.6 Adding extensions to the CLI.md +++ /dev/null @@ -1,18 +0,0 @@ -### 62.6 为CLI添加扩展 - -使用`install`命令可以为CLI添加扩展,该命令接收一个或多个格式为`group:artifact:version`的artifact坐标集,例如: -```shell -$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE -``` -除安装你提供坐标的artifacts标识外,该artifacts的所有依赖也会被安装。 - -使用`uninstall`可以卸载一个依赖,和`install`命令一样,它也接收一个或多个格式为`group:artifact:version`的artifact坐标集,例如: -```shell -$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE -``` -它会通过你提供的坐标卸载相应的artifacts标识及它们的依赖。 - -为了卸载所有附加依赖,你可以使用`--all`选项,例如: -```shell -$ spring uninstall --all -``` diff --git a/VII. Spring Boot CLI/63. Developing application with the Groovy beans DSL.md b/VII. Spring Boot CLI/63. Developing application with the Groovy beans DSL.md deleted file mode 100644 index 7d68df5d..00000000 --- a/VII. Spring Boot CLI/63. Developing application with the Groovy beans DSL.md +++ /dev/null @@ -1,26 +0,0 @@ -### 63. 使用Groovy beans DSL开发应用 - -Spring框架4.0版本对`beans{}`"DSL"(借鉴自[Grails](http://grails.org/))提供原生支持,你可以使用相同格式在Groovy应用程序脚本中嵌入bean定义。有时这是引入外部特性的很好方式,比如中间件声明,例如: -```java -@Configuration -class Application implements CommandLineRunner { - - @Autowired - SharedService service - - @Override - void run(String... args) { - println service.message - } - -} - -import my.company.SharedService - -beans { - service(SharedService) { - message = "Hello World" - } -} -``` -你可以使用`beans{}`混合位于相同文件的类声明,只要它们都处于顶级,或如果喜欢的话,你可以将beans DSL放到一个单独的文件中。 diff --git a/VII. Spring Boot CLI/63. Installing the CLI.md b/VII. Spring Boot CLI/63. Installing the CLI.md new file mode 100644 index 00000000..7450527e --- /dev/null +++ b/VII. Spring Boot CLI/63. Installing the CLI.md @@ -0,0 +1,3 @@ +### 63. 安装CLI + +你可以使用SDKMAN!(SDK管理器),或者如果你是一个OSX用户的话,你可以使用Homebrew、MacPorts,手动安装Spring Boot CLI(命令行界面)。具体安装说明,请参考"开始"那一章的[10.2. Spring Boot CLI安装](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#getting-started-installing-the-cli)。 diff --git a/VII. Spring Boot CLI/64. Configuring the CLI with settings.xml.md b/VII. Spring Boot CLI/64. Configuring the CLI with settings.xml.md deleted file mode 100644 index 46a9876a..00000000 --- a/VII. Spring Boot CLI/64. Configuring the CLI with settings.xml.md +++ /dev/null @@ -1,16 +0,0 @@ -### 64. 使用settings.xml配置CLI -Spring Boot CLI使用Maven的依赖解析引擎Aether来解析依赖,它充分利用发现的`~/.m2/settings.xml` Maven设置去配置Aether。 - -CLI支持以下配置: - -* Offline -* Mirrors -* Servers -* Proxies -* Profiles - * Activation -   - * Repositories -* Active profiles - -更多信息可参考[Maven设置文档](https://maven.apache.org/settings.html)。 diff --git a/VII. Spring Boot CLI/64. Using the CLI.md b/VII. Spring Boot CLI/64. Using the CLI.md new file mode 100644 index 00000000..2910b07c --- /dev/null +++ b/VII. Spring Boot CLI/64. Using the CLI.md @@ -0,0 +1,42 @@ +### 64. 使用CLI + +一旦安装了CLI,就可以通过在命令行输入`spring`并按Enter来运行它。如果不使用任何参数运行`spring`,将会展现一个简单的帮助界面: +```shell +$ spring +usage: spring [--help] [--version] + [] + +Available commands are: + + run [options] [--] [args] + Run a spring groovy script + + ... more command help is shown here +``` + +你可以输入`help`获取任何支持命令的详细信息,例如: +```shell +$ spring help run +spring run - Run a spring groovy script + +usage: spring run [options] [--] [args] + +Option Description +------ ----------- +--autoconfigure [Boolean] Add autoconfigure compiler + transformations (default: true) +--classpath, -cp Additional classpath entries +-e, --edit Open the file with the default system + editor +--no-guess-dependencies Do not attempt to guess dependencies +--no-guess-imports Do not attempt to guess imports +-q, --quiet Quiet logging +-v, --verbose Verbose logging of dependency + resolution +--watch Watch the specified file for changes +``` +`version`命令提供一个检查你正在使用的Spring Boot版本的快速方式: +```shell +$ spring version +Spring CLI v2.0.0.RELEASE +``` diff --git a/VII. Spring Boot CLI/64.1. Running Applications with the CLI.md b/VII. Spring Boot CLI/64.1. Running Applications with the CLI.md new file mode 100644 index 00000000..3cec2dde --- /dev/null +++ b/VII. Spring Boot CLI/64.1. Running Applications with the CLI.md @@ -0,0 +1,32 @@ +### 64.1 使用CLI运行应用 + +你可以使用`run`命令编译和运行Groovy源代码。Spring Boot CLI完全自包含,以致于你不需要安装任何外部的Groovy。 + +下面是一个使用Groovy编写的"hello world" web应用: + +hello.grooy +```java +@RestController +class WebApplication { + + @RequestMapping("/") + String home() { + "Hello World!" + } + +} +``` +编译和运行应用可以输入: +```shell +$ spring run hello.groovy +``` +你可以使用`--`将命令行参数和"spring"命令参数区分开来,例如: +```shell +$ spring run hello.groovy -- --server.port=9000 +``` +你可以使用`JAVA_OPTS`环境变量设置JVM命令行参数,例如: +```shell +$ JAVA_OPTS=-Xmx1024m spring run hello.groovy +``` + +**注** 在微软Windows上设置`JAVA_OPTS`时,请确保引用整个指令,如`set "JAVA_OPTS=-Xms256m -Xmx2048m"`。这样做可以确保正确地将值传递给进程。 diff --git "a/VII. Spring Boot CLI/64.1.1 Deduced \342\200\234grab\342\200\235 Dependencies.md" "b/VII. Spring Boot CLI/64.1.1 Deduced \342\200\234grab\342\200\235 Dependencies.md" new file mode 100644 index 00000000..153deb23 --- /dev/null +++ "b/VII. Spring Boot CLI/64.1.1 Deduced \342\200\234grab\342\200\235 Dependencies.md" @@ -0,0 +1,24 @@ +### 64.1.1 推断"grab"依赖 + +标准的Groovy包含一个`@Grab`注解,它允许你声明对第三方库的依赖。这项有用的技术允许Groovy以和Maven或Gradle相同的方式下载jars,但不需要使用构建工具。 + +Spring Boot进一步延伸了该技术,它会基于你的代码尝试推导你"grab"哪个库。例如,由于`WebApplication`代码上使用了`@RestController`注解。Spring Boot会获取"Tomcat"和"Spring MVC"。 + +下列条目被用作"grab提示": + +|条目|Grabs| +|-----|:-----| +|`JdbcTemplate`,`NamedParameterJdbcTemplate`,`DataSource`|JDBC应用| +|`@EnableJms`|JMS应用| +|`@EnableCaching`|缓存抽象| +|`@Test`|JUnit| +|`@EnableRabbit`|RabbitMQ| +|`@EnableReactor`|项目重构| +|extends `Specification`|Spock测试| +|`@EnableBatchProcessing`|Spring Batch| +|`@MessageEndpoint`,`@EnableIntegration`|Spring集成| +|`@Controller`,`@RestController`,`@EnableWebMvc`|Spring MVC + 内嵌Tomcat| +|`@EnableWebSecurity`|Spring Security| +|`@EnableTransactionManagement`|Spring事务管理| + +**注** 想要理解自定义是如何生效的,可以查看Spring Boot CLI源码中的[CompilerAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java)子类。 diff --git "a/VII. Spring Boot CLI/64.1.2 Deduced \342\200\234grab\342\200\235 Coordinates.md" "b/VII. Spring Boot CLI/64.1.2 Deduced \342\200\234grab\342\200\235 Coordinates.md" new file mode 100644 index 00000000..0ee5a9a8 --- /dev/null +++ "b/VII. Spring Boot CLI/64.1.2 Deduced \342\200\234grab\342\200\235 Coordinates.md" @@ -0,0 +1,5 @@ +### 64.1.2 推断"grab"坐标 + +Spring Boot扩展了Groovy标准`@Grab`注解,使其能够允许你指定一个没有`group`或`version`的依赖,例如`@Grab('freemarker')`。Spring Boot使用默认依赖元数据推断artifact’s的group和version。 + +**注** 需要注意的是默认元数据和你使用的CLI版本有绑定关系-只有在迁移到新版本的CLI时它才会改变,这样你就可以控制何时改变依赖了,在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#appendix-dependency-versions)的表格中可以查看默认元数据包含的依赖和它们的版本。 diff --git a/VII. Spring Boot CLI/64.1.3 Default Import Statements.md b/VII. Spring Boot CLI/64.1.3 Default Import Statements.md new file mode 100644 index 00000000..ae9b2a23 --- /dev/null +++ b/VII. Spring Boot CLI/64.1.3 Default Import Statements.md @@ -0,0 +1,5 @@ +### 64.1.3 默认import语句 + +为了帮助你减少Groovy代码量,一些`import`语句被自动包含进来了。注意上面的示例中引用`@Component`,`@RestController`和`@RequestMapping`而没有使用全限定名或`import`语句。 + +**注**:很多Spring注解在不使用`import`语句的情况下可以正常工作。尝试运行你的应用,看一下在添加imports之前哪些会失败。 diff --git a/VII. Spring Boot CLI/64.1.4 Automatic Main Method.md b/VII. Spring Boot CLI/64.1.4 Automatic Main Method.md new file mode 100644 index 00000000..1e50939d --- /dev/null +++ b/VII. Spring Boot CLI/64.1.4 Automatic Main Method.md @@ -0,0 +1,3 @@ +### 64.1.4 自动创建main方法 + +跟等效的Java应用不同,你不需要在`Groovy`脚本中添加一个`public static void main(String[] args)`方法。Spring Boot会使用你编译后的代码自动创建一个`SpringApplication`。 diff --git a/VII. Spring Boot CLI/64.1.5 Custom Dependency Management.md b/VII. Spring Boot CLI/64.1.5 Custom Dependency Management.md new file mode 100644 index 00000000..ac35f9e9 --- /dev/null +++ b/VII. Spring Boot CLI/64.1.5 Custom Dependency Management.md @@ -0,0 +1,19 @@ +### 64.1.5 自定义依赖管理 + +默认情况下,CLI使用在解析`@Grab`依赖时`spring-boot-dependencies`声明的依赖管理,其他的依赖管理会覆盖默认的依赖管理,并可以通过`@DependencyManagementBom`注解进行配置。该注解的值必须是一个或多个Maven BOMs的候选(`groupId:artifactId:version`)。 + +例如,以下声明: +```grovy +@DependencyManagementBom("com.example.custom-bom:1.0.0") +``` +将选择Maven仓库中`com/example/custom-versions/1.0.0/`下的`custom-bom-1.0.0.pom`。 + +当指定多个BOMs时,它们会以声明次序进行应用,例如: +```grovy +@DependencyManagementBom(["com.example.custom-bom:1.0.0", + "com.example.another-bom:1.0.0"]) +``` +这意味着`another-bom`的依赖将覆盖`custom-bom`依赖。 + +能够使用`@Grab`的地方,你同样可以使用`@DependencyManagementBom`。然而,为了确保依赖管理的一致次序,你在应用中至多使用一次`@DependencyManagementBom`。[Spring IO Platform](https://platform.spring.io/)是一个非常有用的依赖元数据源(Spring Boot的超集),例如: +`@DependencyManagementBom('io.spring.platform:platform-bom:1.1.2.RELEASE')`。 diff --git a/VII. Spring Boot CLI/64.2 Applications with Multiple Source Files.md b/VII. Spring Boot CLI/64.2 Applications with Multiple Source Files.md new file mode 100644 index 00000000..fc179c2b --- /dev/null +++ b/VII. Spring Boot CLI/64.2 Applications with Multiple Source Files.md @@ -0,0 +1,6 @@ +### 64.2 多源文件应用 + +你可以在所有接收文件输入的命令中使用shell通配符。这允许你处理来自一个目录下的多个文件,例如: +```shell +$ spring run *.groovy +``` diff --git a/VII. Spring Boot CLI/64.3 Packaging Your Application.md b/VII. Spring Boot CLI/64.3 Packaging Your Application.md new file mode 100644 index 00000000..76a33b17 --- /dev/null +++ b/VII. Spring Boot CLI/64.3 Packaging Your Application.md @@ -0,0 +1,16 @@ +### 64.3 应用打包 + +你可以使用`jar`命令打包应用程序为一个可执行的jar文件,例如: +```shell +$ spring jar my-app.jar *.groovy +``` +最终的jar包括编译应用产生的类和所有依赖,这样你就可以使用`java -jar`来执行它了。该jar文件也包含了来自应用classpath的实体。你可以使用`--include`和`--exclude`添加或排除明确的路径。两者都是用逗号分割,同样都接收'+'和'-'形式的前缀。'-'意味着它们将从默认设置中移除。默认包含(includes): +```shell +public/**, resources/**, static/**, templates/**, META-INF/**, * +``` + +默认排除(excludes): +```shell +.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy +``` +在命令行中输入`spring help jar`,获得更多信息。 diff --git a/VII. Spring Boot CLI/64.4 Initialize a New Project.md b/VII. Spring Boot CLI/64.4 Initialize a New Project.md new file mode 100644 index 00000000..14af702a --- /dev/null +++ b/VII. Spring Boot CLI/64.4 Initialize a New Project.md @@ -0,0 +1,40 @@ +### 64.4 初始化新工程 + +`init`命令允许你使用[start.spring.io](https://start.spring.io/)在不离开shell的情况下创建一个新的项目,例如: +```shell +$ spring init --dependencies=web,data-jpa my-project +Using service at https://start.spring.io +Project extracted to '/Users/developer/example/my-project' +``` + +这创建了一个`my-project`目录,它是一个基于Maven且依赖`spring-boot-starter-web`和`spring-boot-starter-data-jpa`的项目。你可以使用`--list`参数列出该服务的能力。 +```shell +$ spring init --list +======================================= +Capabilities of https://start.spring.io +======================================= + +Available dependencies: +----------------------- +actuator - Actuator: Production ready features to help you monitor and manage your application +... +web - Web: Support for full-stack web development, including Tomcat and spring-webmvc +websocket - Websocket: Support for WebSocket development +ws - WS: Support for Spring Web Services + +Available project types: +------------------------ +gradle-build - Gradle Config [format:build, build:gradle] +gradle-project - Gradle Project [format:project, build:gradle] +maven-build - Maven POM [format:build, build:maven] +maven-project - Maven Project [format:project, build:maven] (default) + +... +``` + +`init`命令支持很多选项,查看`help`输出可以获得更多详情。例如,下面的命令创建一个使用Java8和打包为`war`的Gradle项目: +```shell +$ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip +Using service at https://start.spring.io +Content saved to 'sample-app.zip' +``` diff --git a/VII. Spring Boot CLI/64.5 Using the Embedded Shell.md b/VII. Spring Boot CLI/64.5 Using the Embedded Shell.md new file mode 100644 index 00000000..65246b23 --- /dev/null +++ b/VII. Spring Boot CLI/64.5 Using the Embedded Shell.md @@ -0,0 +1,15 @@ +### 64.5 使用内嵌shell + +Spring Boot包括完整的BASH和zsh shells的命令行脚本,如果这两种你都不使用(可能你是一个Window用户),那你可以使用`shell`命令启用一个集成shell。 +```shell +$ spring shell +Spring Boot (v2.0.0.RELEASE) +Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit. +``` + +在内嵌shell中,可以直接运行其他命令: +```shell +$ version +Spring CLI v2.0.0.RELEASE +``` +内嵌shell支持ANSI彩色输出和tab补全。如果需要运行一个原生命令,你可以使用`!`前缀,点击`ctrl-c`将退出内嵌shell。 diff --git a/VII. Spring Boot CLI/64.6 Adding Extensions to the CLI.md b/VII. Spring Boot CLI/64.6 Adding Extensions to the CLI.md new file mode 100644 index 00000000..08eae2b3 --- /dev/null +++ b/VII. Spring Boot CLI/64.6 Adding Extensions to the CLI.md @@ -0,0 +1,18 @@ +### 64.6 为CLI添加扩展 + +使用`install`命令可以为CLI添加扩展,该命令接收一个或多个格式为`group:artifact:version`的artifact坐标集,例如: +```shell +$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE +``` +除安装你提供坐标的artifacts标识外,该artifacts的所有依赖也会被安装。 + +使用`uninstall`可以卸载一个依赖,和`install`命令一样,它也接收一个或多个格式为`group:artifact:version`的artifact坐标集,例如: +```shell +$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE +``` +它会通过你提供的坐标卸载相应的artifacts标识及它们的依赖。 + +为了卸载所有附加依赖,你可以使用`--all`选项,例如: +```shell +$ spring uninstall --all +``` diff --git a/VII. Spring Boot CLI/65. Developing Application with the Groovy Beans DSL.md b/VII. Spring Boot CLI/65. Developing Application with the Groovy Beans DSL.md new file mode 100644 index 00000000..9a7f086f --- /dev/null +++ b/VII. Spring Boot CLI/65. Developing Application with the Groovy Beans DSL.md @@ -0,0 +1,26 @@ +### 65. 使用Groovy beans DSL开发应用 + +Spring框架4.0版本对`beans{}`"DSL"(借鉴自[Grails](http://grails.org/))提供原生支持,你可以使用相同格式在Groovy应用程序脚本中嵌入bean定义。有时这是引入外部特性的很好方式,比如中间件声明,例如: +```java +@Configuration +class Application implements CommandLineRunner { + + @Autowired + SharedService service + + @Override + void run(String... args) { + println service.message + } + +} + +import my.company.SharedService + +beans { + service(SharedService) { + message = "Hello World" + } +} +``` +你可以使用`beans{}`混合位于相同文件的类声明,只要它们都处于顶级,或如果喜欢的话,你可以将beans DSL放到一个单独的文件中。 diff --git a/VII. Spring Boot CLI/65. What to read next.md b/VII. Spring Boot CLI/65. What to read next.md deleted file mode 100644 index 620b07e6..00000000 --- a/VII. Spring Boot CLI/65. What to read next.md +++ /dev/null @@ -1,4 +0,0 @@ -### 65. 接下来阅读什么 -GitHub仓库有一些[groovy脚本示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-cli/samples)可用于尝试Spring Boot CLI,[源码](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-cli/src/main/java/org/springframework/boot/cli)里也有丰富的文档说明。 - -如果发现已触及CLI工具的限制,你可以将应用完全转换为Gradle或Maven构建的groovy工程。下一章节将覆盖Spring Boot的[构建工具](../VIII. Build tool plugins/README.md),这些工具可以跟Gradle或Maven一起使用。 diff --git a/VII. Spring Boot CLI/66. Configuring the CLI with settings.xml.md b/VII. Spring Boot CLI/66. Configuring the CLI with settings.xml.md new file mode 100644 index 00000000..445da720 --- /dev/null +++ b/VII. Spring Boot CLI/66. Configuring the CLI with settings.xml.md @@ -0,0 +1,17 @@ +### 66. 使用settings.xml配置CLI + +Spring Boot CLI使用Maven的依赖解析引擎Aether来解析依赖,它充分利用发现的`~/.m2/settings.xml` Maven设置去配置Aether。 + +CLI支持以下配置: + +* Offline +* Mirrors +* Servers +* Proxies +* Profiles + * Activation +   + * Repositories +* Active profiles + +更多信息可参考[Maven设置文档](https://maven.apache.org/settings.html)。 diff --git a/VII. Spring Boot CLI/67. What to Read Next.md b/VII. Spring Boot CLI/67. What to Read Next.md new file mode 100644 index 00000000..ff7e8d7e --- /dev/null +++ b/VII. Spring Boot CLI/67. What to Read Next.md @@ -0,0 +1,5 @@ +### 67. 接下来阅读什么 + +GitHub仓库有一些[groovy脚本示例](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-cli/samples)可用于尝试Spring Boot CLI。[源码](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli)里也有丰富的文档说明。 + +如果发现已触及CLI工具的限制,你可以将应用完全转换为Gradle或Maven构建的Groovy工程。下一章节将覆盖Spring Boot的[构建工具](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#build-tool-plugins)。这些工具可以跟Gradle或Maven一起使用。 diff --git a/VIII. Build tool plugins/66. Spring Boot Maven plugin.md b/VIII. Build tool plugins/66. Spring Boot Maven plugin.md deleted file mode 100644 index 22c81878..00000000 --- a/VIII. Build tool plugins/66. Spring Boot Maven plugin.md +++ /dev/null @@ -1,5 +0,0 @@ -### 66. Spring Boot Maven插件 - -[Spring Boot Maven插件](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin/)为Maven提供Spring Boot支持,它允许你打包可执行jar或war存档,然后就地运行应用。为了使用它,你需要使用Maven 3.2(或更高版本)。 - -**注** 参考[Spring Boot Maven Plugin Site](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin//)可以获取全部的插件文档。 diff --git a/VIII. Build tool plugins/66.1 Including the plugin.md b/VIII. Build tool plugins/66.1 Including the plugin.md deleted file mode 100644 index 395ee214..00000000 --- a/VIII. Build tool plugins/66.1 Including the plugin.md +++ /dev/null @@ -1,52 +0,0 @@ -### 66.1 包含该插件 - -想要使用Spring Boot Maven插件只需简单地在你的pom.xml的`plugins`部分包含相应的XML: -```xml - - - 4.0.0 - - - - - org.springframework.boot - spring-boot-maven-plugin - 2.0.0.M5 - - - - repackage - - - - - - - -``` -该配置会在Maven生命周期的`package`阶段重新打包一个jar或war。下面的示例展示在`target`目录下既有重新打包后的jar,也有原始的jar: -```shell -$ mvn package -$ ls target/*.jar -target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original -``` -如果不包含像上面那样的``,你可以自己运行该插件(但只有在package目标也被使用的情况),例如: -```shell -$ mvn package spring-boot:repackage -$ ls target/*.jar -target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original -``` -如果使用一个里程碑或快照版本,你还需要添加正确的`pluginRepository`元素: -```xml - - - spring-snapshots - http://repo.spring.io/snapshot - - - spring-milestones - http://repo.spring.io/milestone - - -``` diff --git a/VIII. Build tool plugins/66.2 Packaging executable jar and war files.md b/VIII. Build tool plugins/66.2 Packaging executable jar and war files.md deleted file mode 100644 index e376ca9c..00000000 --- a/VIII. Build tool plugins/66.2 Packaging executable jar and war files.md +++ /dev/null @@ -1,44 +0,0 @@ -### 66.2 打包可执行jar和war文件 - -一旦`spring-boot-maven-plugin`被包含到你的`pom.xml`中,Spring Boot就会自动尝试使用`spring-boot:repackage`目标重写存档以使它们能够执行。为了构建一个jar或war,你应该使用常规的`packaging`元素配置你的项目: -```xml - - - - jar - - -``` -生成的存档在`package`阶段会被Spring Boot增强。你想启动的main类即可以通过指定一个配置选项,也可以通过为manifest添加一个`Main-Class`属性这种常规的方式实现。如果你没有指定一个main类,该插件会搜索带有`public static void main(String[] args)`方法的类。 - -为了构建和运行一个项目的artifact,你可以输入以下命令: -```shell -$ mvn package -$ java -jar target/mymodule-0.0.1-SNAPSHOT.jar -``` -为了构建一个即可执行,又能部署到外部容器的war文件,你需要标记内嵌容器依赖为"provided",例如: -```xml - - - - war - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - - -``` -**注** 具体参考[“Section 85.1, “Create a deployable war file”” ](../IX. ‘How-to’ guides/85.1. Create a deployable war file.md)章节。 - -高级配置选项和示例可在[插件信息页面](https://docs.spring.io/spring-boot/docs/2.0.0.M5/maven-plugin/)获取。 diff --git a/VIII. Build tool plugins/67. Spring Boot Gradle plugin.md b/VIII. Build tool plugins/67. Spring Boot Gradle plugin.md deleted file mode 100644 index 0fbb1519..00000000 --- a/VIII. Build tool plugins/67. Spring Boot Gradle plugin.md +++ /dev/null @@ -1,5 +0,0 @@ -### 67. Spring Boot Gradle插件 - -Spring Boot Gradle插件为Gradle提供Spring Boot支持,它允许你打包可执行jar或war存档,运行Spring Boot应用,使用`spring-boot-dependencies`提供的依赖管理。需要Gradle 3.4或之后的版本。更多细节请参考插件的文档: -- 参考 ([HTML](https://docs.spring.io/spring-boot/docs/2.0.0.M5/gradle-plugin//reference/html) 与 [PDF](https://docs.spring.io/spring-boot/docs/2.0.0.M5/gradle-plugin//reference/pdf/spring-boot-gradle-plugin-reference.pdf)) -- [API](https://docs.spring.io/spring-boot/docs/2.0.0.M5/gradle-plugin//api) diff --git a/VIII. Build tool plugins/68. Spring Boot AntLib module.md b/VIII. Build tool plugins/68. Spring Boot AntLib module.md deleted file mode 100644 index 71410851..00000000 --- a/VIII. Build tool plugins/68. Spring Boot AntLib module.md +++ /dev/null @@ -1,16 +0,0 @@ -###68. Spring Boot AntLib模块 - -Spring Boot AntLib模块为Apache Ant提供基本的Spring Boot支持,你可以使用该模块创建可执行的jars。在`build.xml`添加额外的`spring-boot`命名空间就可以使用该模块了: -```xml - - ... - -``` -你需要记得在启动Ant时使用`-lib`选项,例如: -```shell -$ ant -lib -``` -**注** 详细示例可参考[using Apache Ant with `spring-boot-antlib` -](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#using-boot-ant)。 diff --git a/VIII. Build tool plugins/68. Spring Boot Maven Plugin.md b/VIII. Build tool plugins/68. Spring Boot Maven Plugin.md new file mode 100644 index 00000000..a66dae7e --- /dev/null +++ b/VIII. Build tool plugins/68. Spring Boot Maven Plugin.md @@ -0,0 +1,5 @@ +### 68. Spring Boot Maven插件 + +[Spring Boot Maven插件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin)为Maven提供Spring Boot支持,它允许你打包可执行jar或war存档,然后就地运行应用。为了使用它,你需要使用Maven 3.2(或更高版本)。 + +**注** 参考[Spring Boot Maven Plugin Site](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin)可以获取全部的插件文档。 diff --git a/VIII. Build tool plugins/68.1 Including the Plugin.md b/VIII. Build tool plugins/68.1 Including the Plugin.md new file mode 100644 index 00000000..24193ade --- /dev/null +++ b/VIII. Build tool plugins/68.1 Including the Plugin.md @@ -0,0 +1,52 @@ +### 68.1 包含该插件 + +想要使用Spring Boot Maven插件只需在你的`pom.xml`的`plugins`部分包含相应的XML: +```xml + + + 4.0.0 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.0.0.RELEASE + + + + repackage + + + + + + + +``` +该配置会在Maven生命周期的`package`阶段重新打包一个jar或war。下面的示例展示在`target`目录下既有重新打包后的jar,也有原始的jar: +```shell +$ mvn package +$ ls target/*.jar +target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original +``` +如果不包含像上面那样的``,你可以自己运行该插件(但只有在package目标也被使用的情况),例如: +```shell +$ mvn package spring-boot:repackage +$ ls target/*.jar +target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original +``` +如果使用一个里程碑或快照版本,你还需要添加正确的`pluginRepository`元素: +```xml + + + spring-snapshots + https://repo.spring.io/snapshot + + + spring-milestones + https://repo.spring.io/milestone + + +``` diff --git a/VIII. Build tool plugins/68.1. Spring Boot Ant tasks.md b/VIII. Build tool plugins/68.1. Spring Boot Ant tasks.md deleted file mode 100644 index 1b42d1da..00000000 --- a/VIII. Build tool plugins/68.1. Spring Boot Ant tasks.md +++ /dev/null @@ -1,2 +0,0 @@ -###68.1. Spring Boot Ant任务 -一旦声明`spring-boot-antlib`命名空间,以下任务就可用了。 diff --git a/VIII. Build tool plugins/68.1.1. spring-boot:exejar.md b/VIII. Build tool plugins/68.1.1. spring-boot:exejar.md deleted file mode 100644 index ebe13e3c..00000000 --- a/VIII. Build tool plugins/68.1.1. spring-boot:exejar.md +++ /dev/null @@ -1,16 +0,0 @@ -###68.1.1. spring-boot:exejar - -`exejar`任务可用于创建Spring Boot可执行jar,该任务支持以下属性: - -|属性|描述|是否必须| -|:----|:----|:-----| -|`destfile`|将要创建的目的jar文件|是| -|`classes`|Java类文件的根目录|是| -|`start-class`|运行的main类|否(默认为找到的第一个声明`main`方法的类)| - -以下元素可以跟任务一块使用: - -|元素|描述| -|:----|:----| -|`resources`|一个或多个[Resource Collections](http://ant.apache.org/manual/Types/resources.html#collection),描述将添加到创建的jar文件中的资源集合| -|`lib`|一个或多个[Resource Collections](http://ant.apache.org/manual/Types/resources.html#collection),表示需要添加进jar库的集合,组成了应用运行时的classpath依赖| diff --git a/VIII. Build tool plugins/68.1.2. Examples.md b/VIII. Build tool plugins/68.1.2. Examples.md deleted file mode 100644 index 2e55fb70..00000000 --- a/VIII. Build tool plugins/68.1.2. Examples.md +++ /dev/null @@ -1,23 +0,0 @@ -### 68.1.2. 示例 - -**指定start-class** -```xml - - - - - - - - -``` - -**探测start-class** -```xml - - - - - -``` diff --git a/VIII. Build tool plugins/68.2 Packaging Executable Jar and War Files.md b/VIII. Build tool plugins/68.2 Packaging Executable Jar and War Files.md new file mode 100644 index 00000000..a5590014 --- /dev/null +++ b/VIII. Build tool plugins/68.2 Packaging Executable Jar and War Files.md @@ -0,0 +1,44 @@ +### 68.2 打包可执行jar和war文件 + +一旦`spring-boot-maven-plugin`被包含到你的`pom.xml`中,Spring Boot就会自动尝试使用`spring-boot:repackage`目标重写存档以使它们能够执行。为了构建一个jar或war,你应该使用常规的`packaging`元素配置你的项目: +```xml + + + + jar + + +``` +生成的存档在`package`阶段会被Spring Boot增强。你想启动的main类即可以通过指定一个配置选项,也可以通过为manifest添加一个`Main-Class`属性这种常规的方式实现。如果你没有指定一个main类,该插件会搜索带有`public static void main(String[] args)`方法的类。 + +为了构建和运行一个项目的artifact,你可以输入以下命令: +```shell +$ mvn package +$ java -jar target/mymodule-0.0.1-SNAPSHOT.jar +``` +为了构建一个即可执行,又能部署到外部容器的war文件,你需要标记内嵌容器依赖为"provided",例如: +```xml + + + + war + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + +``` +**注** 具体参考[87.1 创建可部署的war文件](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-create-a-deployable-war-file)章节。 + +高级配置选项和示例可在[插件信息页面](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/maven-plugin)获取。 diff --git a/VIII. Build tool plugins/68.2. spring-boot:findmainclass.md b/VIII. Build tool plugins/68.2. spring-boot:findmainclass.md deleted file mode 100644 index 41c5c72a..00000000 --- a/VIII. Build tool plugins/68.2. spring-boot:findmainclass.md +++ /dev/null @@ -1,9 +0,0 @@ -###68.2. spring-boot:findmainclass - -`findmainclass`任务是`exejar`内部用于定位声明`main`方法类的,如果构建需要,你可以直接使用该任务,支持属性如下: - -|属性|描述|是否必需| -|:-----|:-----|:------| -|`classesroot`|Java类文件的根目录|是(除非指定`mainclass`)| -|`mainclass`|可用于缩减`main`类的查找|否| -|`property`|Ant属性必须使用result设值|否(没有指定则result会记录日志中)| diff --git a/VIII. Build tool plugins/68.2.1. Examples.md b/VIII. Build tool plugins/68.2.1. Examples.md deleted file mode 100644 index c0a04862..00000000 --- a/VIII. Build tool plugins/68.2.1. Examples.md +++ /dev/null @@ -1,14 +0,0 @@ -###68.2.1. 示例 -**查找并记录** -```xml - -``` -**查找并设置** -```xml - -``` - -**覆盖并设置** -```xml - -``` diff --git a/VIII. Build tool plugins/69. Spring Boot Gradle Plugin.md b/VIII. Build tool plugins/69. Spring Boot Gradle Plugin.md new file mode 100644 index 00000000..d587caba --- /dev/null +++ b/VIII. Build tool plugins/69. Spring Boot Gradle Plugin.md @@ -0,0 +1,5 @@ +### 69. Spring Boot Gradle插件 + +Spring Boot Gradle插件为Gradle提供Spring Boot支持。它允许你打包可执行jar或war存档,运行Spring Boot应用,使用`spring-boot-dependencies`提供的依赖管理。需要Gradle 4.0或之后的版本。更多细节请参考插件的文档: +- 参考 ([HTML](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/gradle-plugin/reference/html) 与 [PDF](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/gradle-plugin/reference/pdf/spring-boot-gradle-plugin-reference.pdf)) +- [API](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/gradle-plugin/api) diff --git a/VIII. Build tool plugins/69. Supporting other build systems.md b/VIII. Build tool plugins/69. Supporting other build systems.md deleted file mode 100644 index 651d6f43..00000000 --- a/VIII. Build tool plugins/69. Supporting other build systems.md +++ /dev/null @@ -1,5 +0,0 @@ -### 69. 对其他构建系统的支持 - -如果想使用除了Maven和Gradle之外的构建工具,你可能需要开发自己的插件。可执行jars需要遵循一个特定格式,并且一些实体需要以不压缩的方式写入(详情查看附录中的[可执行jar格式](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#executable-jar)章节)。 - -Spring Boot Maven和Gradle插件在实际生成jars的过程中会使用`spring-boot-loader-tools`,如果需要,你也可以自由地使用该library。 diff --git a/VIII. Build tool plugins/69.1. Repackaging archives.md b/VIII. Build tool plugins/69.1. Repackaging archives.md deleted file mode 100644 index 8c611581..00000000 --- a/VIII. Build tool plugins/69.1. Repackaging archives.md +++ /dev/null @@ -1,3 +0,0 @@ -### 69.1. 重新打包存档 - -使用`org.springframework.boot.loader.tools.Repackager`可以将一个存在的存档重新打包,这样它就变成一个自包含的可执行存档。`Repackager`类需要提供单一的构造器参数,该参数指向一个存在的jar或war包。你可以使用两个可用的`repackage()`方法中的一个来替换原始的文件或写入新的目标,在repackager运行前还可以指定各种配置。 diff --git a/VIII. Build tool plugins/69.2.Nested libraries.md b/VIII. Build tool plugins/69.2.Nested libraries.md deleted file mode 100644 index c7a3f709..00000000 --- a/VIII. Build tool plugins/69.2.Nested libraries.md +++ /dev/null @@ -1,5 +0,0 @@ -### 69.2. 内嵌库 - -当重新打包一个存档时,你可以使用`org.springframework.boot.loader.tools.Libraries`接口来包含对依赖文件的引用。在这里我们不提供任何该`Libraries`接口的具体实现,因为它们通常跟具体的构建系统相关。 - -如果存档已经包含libraries,你可以使用`Libraries.NONE`。 diff --git a/VIII. Build tool plugins/69.3. Finding a main class.md b/VIII. Build tool plugins/69.3. Finding a main class.md deleted file mode 100644 index 96615993..00000000 --- a/VIII. Build tool plugins/69.3. Finding a main class.md +++ /dev/null @@ -1,3 +0,0 @@ -### 69.3. 查找main类 - -如果你没有使用`Repackager.setMainClass()`指定一个main类,该repackager将使用[ASM](http://asm.ow2.org/)去读取class文件,然后尝试查找一个合适的,具有`public static void main(String[] args)`方法的类。如果发现多个候选者,将会抛出异常。 diff --git a/VIII. Build tool plugins/69.4. Example repackage implementation.md b/VIII. Build tool plugins/69.4. Example repackage implementation.md deleted file mode 100644 index 232be81a..00000000 --- a/VIII. Build tool plugins/69.4. Example repackage implementation.md +++ /dev/null @@ -1,14 +0,0 @@ -### 69.4. repackage实现示例 - -这是一个典型的repackage示例: -```java -Repackager repackager = new Repackager(sourceJarFile); -repackager.setBackupSource(false); -repackager.repackage(new Libraries() { - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - // Build system specific implementation, callback for each dependency - // callback.library(new Library(nestedFile, LibraryScope.COMPILE)); - } - }); -``` diff --git a/VIII. Build tool plugins/70. Spring Boot AntLib Module.md b/VIII. Build tool plugins/70. Spring Boot AntLib Module.md new file mode 100644 index 00000000..fcac8c6d --- /dev/null +++ b/VIII. Build tool plugins/70. Spring Boot AntLib Module.md @@ -0,0 +1,16 @@ +### 70. Spring Boot AntLib模块 + +Spring Boot AntLib模块为Apache Ant提供基本的Spring Boot支持,你可以使用该模块创建可执行的jars。在`build.xml`添加额外的`spring-boot`命名空间就可以使用该模块了: +```xml + + ... + +``` +你需要记得在启动Ant时使用`-lib`选项,例如: +```shell +$ ant -lib +``` +**注** 详细示例可参考[using Apache Ant with `spring-boot-antlib` +](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-ant)。 diff --git a/VIII. Build tool plugins/70. What to read next.md b/VIII. Build tool plugins/70. What to read next.md deleted file mode 100644 index c2b09150..00000000 --- a/VIII. Build tool plugins/70. What to read next.md +++ /dev/null @@ -1,5 +0,0 @@ -### 70. 接下来阅读什么 - -如果对构建工具插件如何工作感兴趣,你可以查看GitHub上的[spring-boot-tools](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-tools)模块,附加中有详细的[可执行jar格式](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#executable-jar)。 - -如果有特定构建相关的问题,可以查看[how-to](../IX. ‘How-to’ guides/README.md)指南。 diff --git a/VIII. Build tool plugins/70.1. Spring Boot Ant Tasks.md b/VIII. Build tool plugins/70.1. Spring Boot Ant Tasks.md new file mode 100644 index 00000000..3cbb722d --- /dev/null +++ b/VIII. Build tool plugins/70.1. Spring Boot Ant Tasks.md @@ -0,0 +1,5 @@ +### 68.1. Spring Boot Ant任务 + +一旦声明`spring-boot-antlib`命名空间,以下任务就可用了: +- [70.1.1. spring-boot:exejar](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-ant-exejar) +- [70.2. spring-boot:findmainclass](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#spring-boot-ant-findmainclass) diff --git a/VIII. Build tool plugins/70.1.1. spring-boot:exejar.md b/VIII. Build tool plugins/70.1.1. spring-boot:exejar.md new file mode 100644 index 00000000..9164fb0f --- /dev/null +++ b/VIII. Build tool plugins/70.1.1. spring-boot:exejar.md @@ -0,0 +1,16 @@ +### 70.1.1. spring-boot:exejar + +`exejar`任务可用于创建Spring Boot可执行jar,该任务支持以下属性: + +|属性|描述|是否必须| +|:----|:----|:-----| +|`destfile`|将要创建的目的jar文件|是| +|`classes`|Java类文件的根目录|是| +|`start-class`|运行的main类|否(默认为找到的第一个声明`main`方法的类)| + +以下元素可以跟任务一块使用: + +|元素|描述| +|:----|:----| +|`resources`|一个或多个[Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection),描述将添加到创建的jar文件中的[资源](https://ant.apache.org/manual/Types/resources.html)集合| +|`lib`|一个或多个[Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection),表示需要添加进jar库的集合,组成了应用运行时的classpath依赖| diff --git a/VIII. Build tool plugins/70.1.2. Examples.md b/VIII. Build tool plugins/70.1.2. Examples.md new file mode 100644 index 00000000..fb3a3a5e --- /dev/null +++ b/VIII. Build tool plugins/70.1.2. Examples.md @@ -0,0 +1,25 @@ +### 70.1.2. 示例 + +本节将展示Ant任务的两个示例。 + +**指定start-class** +```xml + + + + + + + + +``` + +**探测start-class** +```xml + + + + + +``` diff --git a/VIII. Build tool plugins/70.2. spring-boot:findmainclass.md b/VIII. Build tool plugins/70.2. spring-boot:findmainclass.md new file mode 100644 index 00000000..abd38c91 --- /dev/null +++ b/VIII. Build tool plugins/70.2. spring-boot:findmainclass.md @@ -0,0 +1,9 @@ +### 70.2. spring-boot:findmainclass + +`findmainclass`任务是`exejar`内部用于定位声明`main`方法类的,如果构建需要,你可以直接使用该任务,支持属性如下: + +|属性|描述|是否必需| +|:-----|:-----|:------| +|`classesroot`|Java类文件的根目录|是(除非指定`mainclass`)| +|`mainclass`|可用于缩减`main`类的查找|否| +|`property`|Ant属性必须使用result设值|否(没有指定则result会记录日志中)| diff --git a/VIII. Build tool plugins/70.2.1. Examples.md b/VIII. Build tool plugins/70.2.1. Examples.md new file mode 100644 index 00000000..e1f0aa46 --- /dev/null +++ b/VIII. Build tool plugins/70.2.1. Examples.md @@ -0,0 +1,17 @@ +### 70.2.1. 示例 + +本节包含三个使用`findmainclass`的示例。 + +**查找并记录** +```xml + +``` +**查找并设置** +```xml + +``` + +**覆盖并设置** +```xml + +``` diff --git a/VIII. Build tool plugins/71. Supporting Other Build Systems.md b/VIII. Build tool plugins/71. Supporting Other Build Systems.md new file mode 100644 index 00000000..a747195f --- /dev/null +++ b/VIII. Build tool plugins/71. Supporting Other Build Systems.md @@ -0,0 +1,5 @@ +### 71. 对其他构建系统的支持 + +如果想使用除了Maven、Gradle和Ant之外的构建工具,你可能需要开发自己的插件。可执行jars需要遵循一个特定格式,并且一些实体需要以不压缩的方式写入(详情查看附录中的[可执行jar格式](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#executable-jar)章节)。 + +Spring Boot Maven和Gradle插件在实际生成jars的过程中会使用`spring-boot-loader-tools`,如果需要,你也可以自由地使用该library。 diff --git a/VIII. Build tool plugins/71.1. Repackaging Archives.md b/VIII. Build tool plugins/71.1. Repackaging Archives.md new file mode 100644 index 00000000..5448c9f7 --- /dev/null +++ b/VIII. Build tool plugins/71.1. Repackaging Archives.md @@ -0,0 +1,3 @@ +### 71.1. 重新打包存档 + +使用`org.springframework.boot.loader.tools.Repackager`可以将一个存在的存档重新打包,这样它就变成一个自包含的可执行存档。`Repackager`类需要提供单一的构造器参数,该参数指向一个存在的jar或war包。你可以使用两个可用的`repackage()`方法中的一个来替换原始的文件或写入新的目标,在repackager运行前还可以指定各种配置。 diff --git a/VIII. Build tool plugins/71.2. Nested Libraries.md b/VIII. Build tool plugins/71.2. Nested Libraries.md new file mode 100644 index 00000000..7ff76837 --- /dev/null +++ b/VIII. Build tool plugins/71.2. Nested Libraries.md @@ -0,0 +1,5 @@ +### 71.2. 内嵌库 + +当重新打包一个存档时,你可以使用`org.springframework.boot.loader.tools.Libraries`接口来包含对依赖文件的引用。在这里我们不提供任何该`Libraries`接口的具体实现,因为它们通常跟具体的构建系统相关。 + +如果存档已经包含libraries,你可以使用`Libraries.NONE`。 diff --git a/VIII. Build tool plugins/71.3. Finding a Main Class.md b/VIII. Build tool plugins/71.3. Finding a Main Class.md new file mode 100644 index 00000000..19217c03 --- /dev/null +++ b/VIII. Build tool plugins/71.3. Finding a Main Class.md @@ -0,0 +1,3 @@ +### 71.3. 查找main类 + +如果你没有使用`Repackager.setMainClass()`指定一个main类,该repackager将使用[ASM](http://asm.ow2.org/)去读取class文件,然后尝试查找一个合适的,具有`public static void main(String[] args)`方法的类。如果发现多个候选者,将会抛出异常。 diff --git a/VIII. Build tool plugins/71.4. Example Repackage Implementation.md b/VIII. Build tool plugins/71.4. Example Repackage Implementation.md new file mode 100644 index 00000000..0fcb5311 --- /dev/null +++ b/VIII. Build tool plugins/71.4. Example Repackage Implementation.md @@ -0,0 +1,14 @@ +### 71.4. repackage实现示例 + +这是一个典型的repackage示例: +```java +Repackager repackager = new Repackager(sourceJarFile); +repackager.setBackupSource(false); +repackager.repackage(new Libraries() { + @Override + public void doWithLibraries(LibraryCallback callback) throws IOException { + // Build system specific implementation, callback for each dependency + // callback.library(new Library(nestedFile, LibraryScope.COMPILE)); + } + }); +``` diff --git a/VIII. Build tool plugins/72. What to Read Next.md b/VIII. Build tool plugins/72. What to Read Next.md new file mode 100644 index 00000000..67542b36 --- /dev/null +++ b/VIII. Build tool plugins/72. What to Read Next.md @@ -0,0 +1,5 @@ +### 72. 接下来阅读什么 + +如果对构建工具插件如何工作感兴趣,你可以查看GitHub上的[spring-boot-tools](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-tools)模块。附加中有详细的[可执行jar格式](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#executable-jar)。 + +如果有特定构建相关的问题,可以查看[how-to](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto)指南。 diff --git a/VIII. Build tool plugins/README.md b/VIII. Build tool plugins/README.md index a726c8bf..d4fd38c3 100644 --- a/VIII. Build tool plugins/README.md +++ b/VIII. Build tool plugins/README.md @@ -1,3 +1,3 @@ ### 构建工具插件 -Spring Boot为Maven和Gradle提供构建工具插件,该插件提供各种各样的特性,包括打包可执行jars。本章节提供关于插件的更多详情及用于扩展一个不支持的构建系统所需的帮助信息。如果你是刚刚开始,那可能需要先阅读[Part III, “Using Spring Boot”](../III. Using Spring Boot/README.md)章节的[“Chapter 13, Build systems”](../III. Using Spring Boot/13. Build systems.md)。 +Spring Boot为Maven和Gradle提供构建工具插件,该插件提供各种各样的特性,包括打包可执行jars。本章节提供关于插件的更多详情及用于扩展一个不支持的构建系统所需的帮助信息。如果你是刚刚开始,那可能需要先阅读[第三部分 使用Spring Boot](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot)章节的[13. 构建系统](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#using-boot-build-systems)。 diff --git a/X. Appendices/A. Common application properties.md b/X. Appendices/A. Common application properties.md index f7bde356..8bd45139 100644 --- a/X. Appendices/A. Common application properties.md +++ b/X. Appendices/A. Common application properties.md @@ -11,64 +11,73 @@ # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its -# entirety to your own application. ^^^ +# entirety to your own application. ^^^ # =================================================================== # ---------------------------------------- # CORE PROPERTIES # ---------------------------------------- - -# BANNER -banner.charset=UTF-8 # Banner file encoding. -banner.location=classpath:banner.txt # Banner file location. -banner.image.location=classpath:banner.gif # Banner image file location (jpg/png can also be used). -banner.image.width= # Width of the banner image in chars (default 76) -banner.image.height= # Height of the banner image in chars (default based on image height) -banner.image.margin= # Left hand image margin in chars (default 2) -banner.image.invert= # If images should be inverted for dark terminal themes (default false) +debug=false # Enable debug logs. +trace=false # Enable trace logs. # LOGGING -logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback +logging.config= # Location of the logging configuration file. For instance, `classpath:logback.xml` for Logback. logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions. -logging.file= # Log file name. For instance `myapp.log` -logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG` -logging.path= # Location of the log file. For instance `/var/log` -logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup. -logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup. -logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup. +logging.file= # Log file name (for instance, `myapp.log`). Names can be an exact location or relative to the current directory. +logging.file.max-history=0 # Maximum of archive log files to keep. Only supported with the default logback setup. +logging.file.max-size=10MB # Maximum log file size. Only supported with the default logback setup. +logging.level.*= # Log levels severity mapping. For instance, `logging.level.org.springframework=DEBUG`. +logging.path= # Location of the log file. For instance, `/var/log`. +logging.pattern.console= # Appender pattern for output to the console. Supported only with the default Logback setup. +logging.pattern.dateformat=yyyy-MM-dd HH:mm:ss.SSS # Appender pattern for log date format. Supported only with the default Logback setup. +logging.pattern.file= # Appender pattern for output to a file. Supported only with the default Logback setup. +logging.pattern.level=%5p # Appender pattern for log level. Supported only with the default Logback setup. logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized. # AOP spring.aop.auto=true # Add @EnableAspectJAutoProxy. -spring.aop.proxy-target-class=true # Whether subclass-based (CGLIB) proxies are to be created (true) as opposed to standard Java interface-based proxies (false). +spring.aop.proxy-target-class=true # Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false). # IDENTITY (ContextIdApplicationContextInitializer) -spring.application.index= # Application index. spring.application.name= # Application name. # ADMIN (SpringApplicationAdminJmxAutoConfiguration) -spring.application.admin.enabled=false # Enable admin features for the application. +spring.application.admin.enabled=false # Whether to enable admin features for the application. spring.application.admin.jmx-name=org.springframework.boot:type=Admin,name=SpringApplication # JMX name of the application admin MBean. # AUTO-CONFIGURATION spring.autoconfigure.exclude= # Auto-configuration classes to exclude. +# BANNER +spring.banner.charset=UTF-8 # Banner file encoding. +spring.banner.location=classpath:banner.txt # Banner text resource location. +spring.banner.image.location=classpath:banner.gif # Banner image file location (jpg or png can also be used). +spring.banner.image.width=76 # Width of the banner image in chars. +spring.banner.image.height= # Height of the banner image in chars (default based on image height). +spring.banner.image.margin=2 # Left hand image margin in chars. +spring.banner.image.invert=false # Whether images should be inverted for dark terminal themes. + # SPRING CORE -spring.beaninfo.ignore=true # Skip search of BeanInfo classes. +spring.beaninfo.ignore=true # Whether to skip search of BeanInfo classes. # SPRING CACHE (CacheProperties) spring.cache.cache-names= # Comma-separated list of cache names to create if supported by the underlying cache manager. -spring.cache.caffeine.spec= # The spec to use to create caches. Check CaffeineSpec for more details on the spec format. -spring.cache.couchbase.expiration=0 # Entry expiration in milliseconds. By default the entries never expire. +spring.cache.caffeine.spec= # The spec to use to create caches. See CaffeineSpec for more details on the spec format. +spring.cache.couchbase.expiration=0ms # Entry expiration. By default the entries never expire. Note that this value is ultimately converted to seconds. spring.cache.ehcache.config= # The location of the configuration file to use to initialize EhCache. spring.cache.infinispan.config= # The location of the configuration file to use to initialize Infinispan. spring.cache.jcache.config= # The location of the configuration file to use to initialize the cache manager. -spring.cache.jcache.provider= # Fully qualified name of the CachingProvider implementation to use to retrieve the JSR-107 compliant cache manager. Only needed if more than one JSR-107 implementation is available on the classpath. -spring.cache.type= # Cache type, auto-detected according to the environment by default. +spring.cache.jcache.provider= # Fully qualified name of the CachingProvider implementation to use to retrieve the JSR-107 compliant cache manager. Needed only if more than one JSR-107 implementation is available on the classpath. +spring.cache.redis.cache-null-values=true # Allow caching null values. +spring.cache.redis.key-prefix= # Key prefix. +spring.cache.redis.time-to-live=0ms # Entry expiration. By default the entries never expire. +spring.cache.redis.use-key-prefix=true # Whether to use the key prefix when writing to Redis. +spring.cache.type= # Cache type. By default, auto-detected according to the environment. # SPRING CONFIG - using environment property only (ConfigFileApplicationListener) -spring.config.location= # Config file locations. +spring.config.additional-location= # Config file locations used in addition to the defaults. +spring.config.location= # Config file locations that replace the defaults. spring.config.name=application # Config file name. # HAZELCAST (HazelcastProperties) @@ -85,54 +94,55 @@ spring.jmx.server=mbeanServer # MBeanServer bean name. # Email (MailProperties) spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding. -spring.mail.host= # SMTP server host. For instance `smtp.example.com` -spring.mail.jndi-name= # Session JNDI name. When set, takes precedence to others mail settings. +spring.mail.host= # SMTP server host. For instance, `smtp.example.com`. +spring.mail.jndi-name= # Session JNDI name. When set, takes precedence over other mail settings. spring.mail.password= # Login password of the SMTP server. spring.mail.port= # SMTP server port. spring.mail.properties.*= # Additional JavaMail session properties. spring.mail.protocol=smtp # Protocol used by the SMTP server. -spring.mail.test-connection=false # Test that the mail server is available on startup. +spring.mail.test-connection=false # Whether to test that the mail server is available on startup. spring.mail.username= # Login user of the SMTP server. # APPLICATION SETTINGS (SpringApplication) spring.main.banner-mode=console # Mode used to display the banner when the application runs. -spring.main.sources= # Sources (class name, package name or XML resource location) to include in the ApplicationContext. -spring.main.web-application-type= # Flag to explicitly request a specific type of web application. Auto-detected based on the classpath if not set. +spring.main.sources= # Sources (class names, package names, or XML resource locations) to include in the ApplicationContext. +spring.main.web-application-type= # Flag to explicitly request a specific type of web application. If not set, auto-detected based on the classpath. # FILE ENCODING (FileEncodingApplicationListener) spring.mandatory-file-encoding= # Expected character encoding the application must use. -# INTERNATIONALIZATION (MessageSourceAutoConfiguration) -spring.messages.always-use-message-format=false # Set whether to always apply the MessageFormat rules, parsing even messages without arguments. -spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention. -spring.messages.cache-seconds=-1 # Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever. +# INTERNATIONALIZATION (MessageSourceProperties) +spring.messages.always-use-message-format=false # Whether to always apply the MessageFormat rules, parsing even messages without arguments. +spring.messages.basename=messages # Comma-separated list of basenames (essentially a fully-qualified classpath location), each following the ResourceBundle convention with relaxed support for slash based locations. +spring.messages.cache-duration= # Loaded resource bundle files cache duration. When not set, bundles are cached forever. If a duration suffix is not specified, seconds will be used. spring.messages.encoding=UTF-8 # Message bundles encoding. -spring.messages.fallback-to-system-locale=true # Set whether to fall back to the system Locale if no files for a specific Locale have been found. +spring.messages.fallback-to-system-locale=true # Whether to fall back to the system Locale if no files for a specific Locale have been found. +spring.messages.use-code-as-default-message=false # Whether to use the message code as the default message instead of throwing a "NoSuchMessageException". Recommended during development only. # OUTPUT -spring.output.ansi.enabled=detect # Configure the ANSI output. +spring.output.ansi.enabled=detect # Configures the ANSI output. # PID FILE (ApplicationPidFileWriter) -spring.pid.fail-on-write-error= # Fail if ApplicationPidFileWriter is used but it cannot write the PID file. +spring.pid.fail-on-write-error= # Fails if ApplicationPidFileWriter is used but it cannot write the PID file. spring.pid.file= # Location of the PID file to write (if ApplicationPidFileWriter is used). # PROFILES -spring.profiles.active= # Comma-separated list (or list if using YAML) of active profiles. -spring.profiles.include= # Unconditionally activate the specified comma separated profiles (or list of profiles if using YAML). +spring.profiles.active= # Comma-separated list of active profiles. Can be overridden by a command line switch. +spring.profiles.include= # Unconditionally activate the specified comma-separated list of profiles (or list of profiles if using YAML). # QUARTZ SCHEDULER (QuartzProperties) +spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode. +spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema. spring.quartz.job-store-type=memory # Quartz job store type. spring.quartz.properties.*= # Additional Quartz Scheduler properties. -spring.quartz.jdbc.initialize-schema=false # Create the required Quartz Scheduler tables on startup. -spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema. -# Reactor -spring.reactor.stacktrace-mode.enabled=false # Set whether Reactor should collect stacktrace information at runtime. +# REACTOR (ReactorCoreProperties) +spring.reactor.stacktrace-mode.enabled=false # Whether Reactor should collect stacktrace information at runtime. # SENDGRID (SendGridAutoConfiguration) -spring.sendgrid.api-key= # SendGrid api key (alternative to username/password) -spring.sendgrid.proxy.host= # SendGrid proxy host -spring.sendgrid.proxy.port= # SendGrid proxy port +spring.sendgrid.api-key= # SendGrid API key. +spring.sendgrid.proxy.host= # SendGrid proxy host. +spring.sendgrid.proxy.port= # SendGrid proxy port. # ---------------------------------------- @@ -140,53 +150,54 @@ spring.sendgrid.proxy.port= # SendGrid proxy port # ---------------------------------------- # EMBEDDED SERVER CONFIGURATION (ServerProperties) -server.address= # Network address to which the server should bind to. -server.compression.enabled=false # If response compression is enabled. +server.address= # Network address to which the server should bind. +server.compression.enabled=false # Whether response compression is enabled. server.compression.excluded-user-agents= # List of user-agents to exclude from compression. -server.compression.mime-types= # Comma-separated list of MIME types that should be compressed. For instance `text/html,text/css,application/json` -server.compression.min-response-size= # Minimum response size that is required for compression to be performed. For instance 2048 -server.connection-timeout= # Time in milliseconds that connectors will wait for another HTTP request before closing the connection. When not set, the connector's container-specific default will be used. Use a value of -1 to indicate no (i.e. infinite) timeout. -server.display-name=application # Display name of the application. -server.max-http-header-size=0 # Maximum size in bytes of the HTTP message header. +server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript # Comma-separated list of MIME types that should be compressed. +server.compression.min-response-size=2048 # Minimum "Content-Length" value that is required for compression to be performed. +server.connection-timeout= # Time that connectors wait for another HTTP request before closing the connection. When not set, the connector's container-specific default is used. Use a value of -1 to indicate no (that is, an infinite) timeout. server.error.include-exception=false # Include the "exception" attribute. server.error.include-stacktrace=never # When to include a "stacktrace" attribute. server.error.path=/error # Path of the error controller. -server.error.whitelabel.enabled=true # Enable the default error page displayed in browsers in case of a server error. +server.error.whitelabel.enabled=true # Whether to enable the default error page displayed in browsers in case of a server error. +server.http2.enabled=false # Whether to enable HTTP/2 support, if the current environment supports it. server.jetty.acceptors= # Number of acceptor threads to use. server.jetty.accesslog.append=false # Append to log. server.jetty.accesslog.date-format=dd/MMM/yyyy:HH:mm:ss Z # Timestamp format of the request log. server.jetty.accesslog.enabled=false # Enable access log. server.jetty.accesslog.extended-format=false # Enable extended NCSA format. server.jetty.accesslog.file-date-format= # Date format to place in log file name. -server.jetty.accesslog.filename= # Log filename. If not specified, logs will be redirected to "System.err". +server.jetty.accesslog.filename= # Log filename. If not specified, logs redirect to "System.err". server.jetty.accesslog.locale= # Locale of the request log. server.jetty.accesslog.log-cookies=false # Enable logging of the request cookies. server.jetty.accesslog.log-latency=false # Enable logging of request processing time. server.jetty.accesslog.log-server=false # Enable logging of the request hostname. server.jetty.accesslog.retention-period=31 # Number of days before rotated log files are deleted. server.jetty.accesslog.time-zone=GMT # Timezone of the request log. -server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content. +server.jetty.max-http-post-size=0 # Maximum size, in bytes, of the HTTP post or put content. server.jetty.selectors= # Number of selector threads to use. +server.max-http-header-size=0 # Maximum size, in bytes, of the HTTP message header. server.port=8080 # Server HTTP port. -server.server-header= # Value to use for the Server response header (no header is sent if empty) -server.use-forward-headers= # If X-Forwarded-* headers should be applied to the HttpRequest. -server.servlet.context-parameters.*= # Servlet context init parameters +server.server-header= # Value to use for the Server response header (if empty, no header is sent). +server.use-forward-headers= # Whether X-Forwarded-* headers should be applied to the HttpRequest. +server.servlet.context-parameters.*= # Servlet context init parameters. server.servlet.context-path= # Context path of the application. +server.servlet.application-display-name=application # Display name of the application. server.servlet.jsp.class-name=org.apache.jasper.servlet.JspServlet # The class name of the JSP servlet. -server.servlet.jsp.init-parameters.*= # Init parameters used to configure the JSP servlet -server.servlet.jsp.registered=true # Whether or not the JSP servlet is registered +server.servlet.jsp.init-parameters.*= # Init parameters used to configure the JSP servlet. +server.servlet.jsp.registered=true # Whether the JSP servlet is registered. server.servlet.path=/ # Path of the main dispatcher servlet. -server.session.cookie.comment= # Comment for the session cookie. -server.session.cookie.domain= # Domain for the session cookie. -server.session.cookie.http-only= # "HttpOnly" flag for the session cookie. -server.session.cookie.max-age= # Maximum age of the session cookie in seconds. -server.session.cookie.name= # Session cookie name. -server.session.cookie.path= # Path of the session cookie. -server.session.cookie.secure= # "Secure" flag for the session cookie. -server.session.persistent=false # Persist session data between restarts. -server.session.store-dir= # Directory used to store session data. -server.session.timeout= # Session timeout in seconds. -server.session.tracking-modes= # Session tracking modes (one or more of the following: "cookie", "url", "ssl"). +server.servlet.session.cookie.comment= # Comment for the session cookie. +server.servlet.session.cookie.domain= # Domain for the session cookie. +server.servlet.session.cookie.http-only= # "HttpOnly" flag for the session cookie. +server.servlet.session.cookie.max-age= # Maximum age of the session cookie. If a duration suffix is not specified, seconds will be used. +server.servlet.session.cookie.name= # Session cookie name. +server.servlet.session.cookie.path= # Path of the session cookie. +server.servlet.session.cookie.secure= # "Secure" flag for the session cookie. +server.servlet.session.persistent=false # Whether to persist session data between restarts. +server.servlet.session.store-dir= # Directory used to store session data. +server.servlet.session.timeout= # Session timeout. If a duration suffix is not specified, seconds will be used. +server.servlet.session.tracking-modes= # Session tracking modes (one or more of the following: "cookie", "url", "ssl"). server.ssl.ciphers= # Supported SSL ciphers. server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. server.ssl.enabled= # Enable SSL support. @@ -202,82 +213,84 @@ server.ssl.trust-store= # Trust store that holds SSL certificates. server.ssl.trust-store-password= # Password used to access the trust store. server.ssl.trust-store-provider= # Provider for the trust store. server.ssl.trust-store-type= # Type of the trust store. -server.tomcat.accept-count= # Maximum queue length for incoming connection requests when all possible request processing threads are in use. -server.tomcat.accesslog.buffered=true # Buffer output such that it is only flushed periodically. -server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be relative to the tomcat base dir or absolute. +server.tomcat.accept-count=0 # Maximum queue length for incoming connection requests when all possible request processing threads are in use. +server.tomcat.accesslog.buffered=true # Whether to buffer output such that it is flushed only periodically. +server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be absolute or relative to the Tomcat base dir. server.tomcat.accesslog.enabled=false # Enable access log. -server.tomcat.accesslog.file-date-format=.yyyy-MM-dd # Date format to place in log file name. +server.tomcat.accesslog.file-date-format=.yyyy-MM-dd # Date format to place in the log file name. server.tomcat.accesslog.pattern=common # Format pattern for access logs. server.tomcat.accesslog.prefix=access_log # Log file name prefix. -server.tomcat.accesslog.rename-on-rotate=false # Defer inclusion of the date stamp in the file name until rotate time. -server.tomcat.accesslog.request-attributes-enabled=false # Set request attributes for IP address, Hostname, protocol and port used for the request. -server.tomcat.accesslog.rotate=true # Enable access log rotation. +server.tomcat.accesslog.rename-on-rotate=false # Whether to defer inclusion of the date stamp in the file name until rotate time. +server.tomcat.accesslog.request-attributes-enabled=false # Set request attributes for the IP address, Hostname, protocol, and port used for the request. +server.tomcat.accesslog.rotate=true # Whether to enable access log rotation. server.tomcat.accesslog.suffix=.log # Log file name suffix. server.tomcat.additional-tld-skip-patterns= # Comma-separated list of additional patterns that match jars to ignore for TLD scanning. -server.tomcat.background-processor-delay=30 # Delay in seconds between the invocation of backgroundProcess methods. -server.tomcat.basedir= # Tomcat base directory. If not specified a temporary directory will be used. +server.tomcat.background-processor-delay=30s # Delay between the invocation of backgroundProcess methods. If a duration suffix is not specified, seconds will be used. +server.tomcat.basedir= # Tomcat base directory. If not specified, a temporary directory is used. server.tomcat.internal-proxies=10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\ - 192\\.168\\.\\d{1,3}\\.\\d{1,3}|\\ - 169\\.254\\.\\d{1,3}\\.\\d{1,3}|\\ - 127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\ - 172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\ - 172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\ - 172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3} # regular expression matching trusted IP addresses. -server.tomcat.max-connections= # Maximum number of connections that the server will accept and process at any given time. -server.tomcat.max-http-header-size=0 # Maximum size in bytes of the HTTP message header. -server.tomcat.max-http-post-size=0 # Maximum size in bytes of the HTTP post content. -server.tomcat.max-threads=0 # Maximum amount of worker threads. -server.tomcat.min-spare-threads=0 # Minimum amount of worker threads. + 192\\.168\\.\\d{1,3}\\.\\d{1,3}|\\ + 169\\.254\\.\\d{1,3}\\.\\d{1,3}|\\ + 127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\ + 172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\ + 172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|\\ + 172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3} # Regular expression matching trusted IP addresses. +server.tomcat.max-connections=0 # Maximum number of connections that the server accepts and processes at any given time. +server.tomcat.max-http-header-size=0 # Maximum size, in bytes, of the HTTP message header. +server.tomcat.max-http-post-size=0 # Maximum size, in bytes, of the HTTP post content. +server.tomcat.max-threads=0 # Maximum number of worker threads. +server.tomcat.min-spare-threads=0 # Minimum number of worker threads. server.tomcat.port-header=X-Forwarded-Port # Name of the HTTP header used to override the original port value. server.tomcat.protocol-header= # Header that holds the incoming protocol, usually named "X-Forwarded-Proto". -server.tomcat.protocol-header-https-value=https # Value of the protocol header that indicates that the incoming request uses SSL. +server.tomcat.protocol-header-https-value=https # Value of the protocol header indicating whether the incoming request uses SSL. server.tomcat.redirect-context-root= # Whether requests to the context root should be redirected by appending a / to the path. -server.tomcat.remote-ip-header= # Name of the http header from which the remote ip is extracted. For instance `X-FORWARDED-FOR` +server.tomcat.remote-ip-header= # Name of the HTTP header from which the remote IP is extracted. For instance, `X-FORWARDED-FOR`. +server.tomcat.resource.cache-ttl= # Time-to-live of the static resource cache. server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI. +server.tomcat.use-relative-redirects= # Whether HTTP 1.1 and later location headers generated by a call to sendRedirect will use relative or absolute redirects. server.undertow.accesslog.dir= # Undertow access log directory. -server.undertow.accesslog.enabled=false # Enable access log. +server.undertow.accesslog.enabled=false # Whether to enable the access log. server.undertow.accesslog.pattern=common # Format pattern for access logs. server.undertow.accesslog.prefix=access_log. # Log file name prefix. -server.undertow.accesslog.rotate=true # Enable access log rotation. +server.undertow.accesslog.rotate=true # Whether to enable access log rotation. server.undertow.accesslog.suffix=log # Log file name suffix. -server.undertow.buffer-size= # Size of each buffer in bytes. -server.undertow.direct-buffers= # Allocate buffers outside the Java heap. +server.undertow.buffer-size= # Size of each buffer, in bytes. +server.undertow.direct-buffers= # Whether to allocate buffers outside the Java heap. server.undertow.io-threads= # Number of I/O threads to create for the worker. server.undertow.eager-filter-init=true # Whether servlet filters should be initialized on startup. -server.undertow.max-http-post-size=0 # Maximum size in bytes of the HTTP post content. +server.undertow.max-http-post-size=0 # Maximum size, in bytes, of the HTTP post content. server.undertow.worker-threads= # Number of worker threads. -# FREEMARKER (FreeMarkerAutoConfiguration) -spring.freemarker.allow-request-override=false # Set whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. -spring.freemarker.allow-session-override=false # Set whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. -spring.freemarker.cache=false # Enable template caching. +# FREEMARKER (FreeMarkerProperties) +spring.freemarker.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.freemarker.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.freemarker.cache=false # Whether to enable template caching. spring.freemarker.charset=UTF-8 # Template encoding. -spring.freemarker.check-template-location=true # Check that the templates location exists. +spring.freemarker.check-template-location=true # Whether to check that the templates location exists. spring.freemarker.content-type=text/html # Content-Type value. -spring.freemarker.enabled=true # Enable MVC view resolution for this technology. -spring.freemarker.expose-request-attributes=false # Set whether all request attributes should be added to the model prior to merging with the template. -spring.freemarker.expose-session-attributes=false # Set whether all HttpSession attributes should be added to the model prior to merging with the template. -spring.freemarker.expose-spring-macro-helpers=true # Set whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". -spring.freemarker.prefer-file-system-access=true # Prefer file system access for template loading. File system access enables hot detection of template changes. +spring.freemarker.enabled=true # Whether to enable MVC view resolution for this technology. +spring.freemarker.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template. +spring.freemarker.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template. +spring.freemarker.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". +spring.freemarker.prefer-file-system-access=true # Whether to prefer file system access for template loading. File system access enables hot detection of template changes. spring.freemarker.prefix= # Prefix that gets prepended to view names when building a URL. spring.freemarker.request-context-attribute= # Name of the RequestContext attribute for all views. -spring.freemarker.settings.*= # Well-known FreeMarker keys which will be passed to FreeMarker's Configuration. -spring.freemarker.suffix= # Suffix that gets appended to view names when building a URL. +spring.freemarker.settings.*= # Well-known FreeMarker keys which are passed to FreeMarker's Configuration. +spring.freemarker.suffix=.ftl # Suffix that gets appended to view names when building a URL. spring.freemarker.template-loader-path=classpath:/templates/ # Comma-separated list of template paths. spring.freemarker.view-names= # White list of view names that can be resolved. -# GROOVY TEMPLATES (GroovyTemplateAutoConfiguration) -spring.groovy.template.allow-request-override=false # Set whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. -spring.groovy.template.allow-session-override=false # Set whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. -spring.groovy.template.cache= # Enable template caching. +# GROOVY TEMPLATES (GroovyTemplateProperties) +spring.groovy.template.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.groovy.template.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.groovy.template.cache=false # Whether to enable template caching. spring.groovy.template.charset=UTF-8 # Template encoding. -spring.groovy.template.check-template-location=true # Check that the templates location exists. +spring.groovy.template.check-template-location=true # Whether to check that the templates location exists. spring.groovy.template.configuration.*= # See GroovyMarkupConfigurer -spring.groovy.template.content-type=test/html # Content-Type value. -spring.groovy.template.enabled=true # Enable MVC view resolution for this technology. -spring.groovy.template.expose-request-attributes=false # Set whether all request attributes should be added to the model prior to merging with the template. -spring.groovy.template.expose-session-attributes=false # Set whether all HttpSession attributes should be added to the model prior to merging with the template. -spring.groovy.template.expose-spring-macro-helpers=true # Set whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". +spring.groovy.template.content-type=text/html # Content-Type value. +spring.groovy.template.enabled=true # Whether to enable MVC view resolution for this technology. +spring.groovy.template.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template. +spring.groovy.template.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template. +spring.groovy.template.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". spring.groovy.template.prefix= # Prefix that gets prepended to view names when building a URL. spring.groovy.template.request-context-attribute= # Name of the RequestContext attribute for all views. spring.groovy.template.resource-loader-path=classpath:/templates/ # Template path. @@ -285,173 +298,193 @@ spring.groovy.template.suffix=.tpl # Suffix that gets appended to view names whe spring.groovy.template.view-names= # White list of view names that can be resolved. # SPRING HATEOAS (HateoasProperties) -spring.hateoas.use-hal-as-default-json-media-type=true # Specify if application/hal+json responses should be sent to requests that accept application/json. +spring.hateoas.use-hal-as-default-json-media-type=true # Whether application/hal+json responses should be sent to requests that accept application/json. # HTTP message conversion -spring.http.converters.preferred-json-mapper=jackson # Preferred JSON mapper to use for HTTP message conversion. Set to "gson" to force the use of Gson when both it and Jackson are on the classpath. +spring.http.converters.preferred-json-mapper= # Preferred JSON mapper to use for HTTP message conversion. By default, auto-detected according to the environment. # HTTP encoding (HttpEncodingProperties) spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly. -spring.http.encoding.enabled=true # Enable http encoding support. -spring.http.encoding.force= # Force the encoding to the configured charset on HTTP requests and responses. -spring.http.encoding.force-request= # Force the encoding to the configured charset on HTTP requests. Defaults to true when "force" has not been specified. -spring.http.encoding.force-response= # Force the encoding to the configured charset on HTTP responses. -spring.http.encoding.mapping= # Locale to Encoding mapping. +spring.http.encoding.enabled=true # Whether to enable http encoding support. +spring.http.encoding.force= # Whether to force the encoding to the configured charset on HTTP requests and responses. +spring.http.encoding.force-request= # Whether to force the encoding to the configured charset on HTTP requests. Defaults to true when "force" has not been specified. +spring.http.encoding.force-response= # Whether to force the encoding to the configured charset on HTTP responses. +spring.http.encoding.mapping= # Locale in which to encode mapping. # MULTIPART (MultipartProperties) -spring.servlet.multipart.enabled=true # Enable support of multipart uploads. -spring.servlet.multipart.file-size-threshold=0 # Threshold after which files will be written to disk. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes respectively. +spring.servlet.multipart.enabled=true # Whether to enable support of multipart uploads. +spring.servlet.multipart.file-size-threshold=0 # Threshold after which files are written to disk. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes, respectively. spring.servlet.multipart.location= # Intermediate location of uploaded files. -spring.servlet.multipart.max-file-size=1MB # Max file size. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes respectively. -spring.servlet.multipart.max-request-size=10MB # Max request size. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes respectively. +spring.servlet.multipart.max-file-size=1MB # Max file size. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes, respectively. +spring.servlet.multipart.max-request-size=10MB # Max request size. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes, respectively. spring.servlet.multipart.resolve-lazily=false # Whether to resolve the multipart request lazily at the time of file or parameter access. # JACKSON (JacksonProperties) -spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance `yyyy-MM-dd HH:mm:ss`. -spring.jackson.default-property-inclusion= # Controls the inclusion of properties during serialization. +spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`. +spring.jackson.default-property-inclusion= # Controls the inclusion of properties during serialization. Configured with one of the values in Jackson's JsonInclude.Include enumeration. spring.jackson.deserialization.*= # Jackson on/off features that affect the way Java objects are deserialized. spring.jackson.generator.*= # Jackson on/off features for generators. -spring.jackson.joda-date-time-format= # Joda date time format string. If not configured, "date-format" will be used as a fallback if it is configured with a format string. +spring.jackson.joda-date-time-format= # Joda date time format string. If not configured, "date-format" is used as a fallback if it is configured with a format string. spring.jackson.locale= # Locale used for formatting. spring.jackson.mapper.*= # Jackson general purpose on/off features. spring.jackson.parser.*= # Jackson on/off features for parsers. spring.jackson.property-naming-strategy= # One of the constants on Jackson's PropertyNamingStrategy. Can also be a fully-qualified class name of a PropertyNamingStrategy subclass. spring.jackson.serialization.*= # Jackson on/off features that affect the way Java objects are serialized. -spring.jackson.time-zone= # Time zone used when formatting dates. For instance `America/Los_Angeles` +spring.jackson.time-zone= # Time zone used when formatting dates. For instance, "America/Los_Angeles" or "GMT+10". + +# GSON (GsonProperties) +spring.gson.date-format= # Format to use when serializing Date objects. +spring.gson.disable-html-escaping= # Whether to disable the escaping of HTML characters such as '<', '>', etc. +spring.gson.disable-inner-class-serialization= # Whether to exclude inner classes during serialization. +spring.gson.enable-complex-map-key-serialization= # Whether to enable serialization of complex map keys (i.e. non-primitives). +spring.gson.exclude-fields-without-expose-annotation= # Whether to exclude all fields from consideration for serialization or deserialization that do not have the "Expose" annotation. +spring.gson.field-naming-policy= # Naming policy that should be applied to an object's field during serialization and deserialization. +spring.gson.generate-non-executable-json= # Whether to generate non executable JSON by prefixing the output with some special text. +spring.gson.lenient= # Whether to be lenient about parsing JSON that doesn't conform to RFC 4627. +spring.gson.long-serialization-policy= # Serialization policy for Long and long types. +spring.gson.pretty-printing= # Whether to output serialized JSON that fits in a page for pretty printing. +spring.gson.serialize-nulls= # Whether to serialize null fields. # JERSEY (JerseyProperties) -spring.jersey.application-path= # Path that serves as the base URI for the application. Overrides the value of "@ApplicationPath" if specified. +spring.jersey.application-path= # Path that serves as the base URI for the application. If specified, overrides the value of "@ApplicationPath". spring.jersey.filter.order=0 # Jersey filter chain order. -spring.jersey.init.*= # Init parameters to pass to Jersey via the servlet or filter. +spring.jersey.init.*= # Init parameters to pass to Jersey through the servlet or filter. spring.jersey.servlet.load-on-startup=-1 # Load on startup priority of the Jersey servlet. spring.jersey.type=servlet # Jersey integration type. # SPRING LDAP (LdapProperties) -spring.ldap.urls= # LDAP URLs of the server. +spring.ldap.anonymous-read-only=false # Whether read-only operations should use an anonymous environment. spring.ldap.base= # Base suffix from which all operations should originate. -spring.ldap.username= # Login user of the server. -spring.ldap.password= # Login password of the server. spring.ldap.base-environment.*= # LDAP specification settings. +spring.ldap.password= # Login password of the server. +spring.ldap.urls= # LDAP URLs of the server. +spring.ldap.username= # Login username of the server. # EMBEDDED LDAP (EmbeddedLdapProperties) -spring.ldap.embedded.base-dn= # The base DN +spring.ldap.embedded.base-dn= # List of base DNs. spring.ldap.embedded.credential.username= # Embedded LDAP username. spring.ldap.embedded.credential.password= # Embedded LDAP password. spring.ldap.embedded.ldif=classpath:schema.ldif # Schema (LDIF) script resource reference. -spring.ldap.embedded.port= # Embedded LDAP port. -spring.ldap.embedded.validation.enabled=true # Enable LDAP schema validation. +spring.ldap.embedded.port=0 # Embedded LDAP port. +spring.ldap.embedded.validation.enabled=true # Whether to enable LDAP schema validation. spring.ldap.embedded.validation.schema= # Path to the custom schema. -# SPRING MOBILE DEVICE VIEWS (DeviceDelegatingViewResolverAutoConfiguration) -spring.mobile.devicedelegatingviewresolver.enable-fallback=false # Enable support for fallback resolution. -spring.mobile.devicedelegatingviewresolver.enabled=false # Enable device view resolver. -spring.mobile.devicedelegatingviewresolver.mobile-prefix=mobile/ # Prefix that gets prepended to view names for mobile devices. -spring.mobile.devicedelegatingviewresolver.mobile-suffix= # Suffix that gets appended to view names for mobile devices. -spring.mobile.devicedelegatingviewresolver.normal-prefix= # Prefix that gets prepended to view names for normal devices. -spring.mobile.devicedelegatingviewresolver.normal-suffix= # Suffix that gets appended to view names for normal devices. -spring.mobile.devicedelegatingviewresolver.tablet-prefix=tablet/ # Prefix that gets prepended to view names for tablet devices. -spring.mobile.devicedelegatingviewresolver.tablet-suffix= # Suffix that gets appended to view names for tablet devices. - -# SPRING MOBILE SITE PREFERENCE (SitePreferenceAutoConfiguration) -spring.mobile.sitepreference.enabled=true # Enable SitePreferenceHandler. - # MUSTACHE TEMPLATES (MustacheAutoConfiguration) -spring.mustache.allow-request-override= # Set whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. -spring.mustache.allow-session-override= # Set whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. -spring.mustache.cache= # Enable template caching. -spring.mustache.charset= # Template encoding. -spring.mustache.check-template-location= # Check that the templates location exists. -spring.mustache.content-type= # Content-Type value. -spring.mustache.enabled= # Enable MVC view resolution for this technology. -spring.mustache.expose-request-attributes= # Set whether all request attributes should be added to the model prior to merging with the template. -spring.mustache.expose-session-attributes= # Set whether all HttpSession attributes should be added to the model prior to merging with the template. -spring.mustache.expose-spring-macro-helpers= # Set whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". +spring.mustache.allow-request-override=false # Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.mustache.allow-session-override=false # Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.mustache.cache=false # Whether to enable template caching. +spring.mustache.charset=UTF-8 # Template encoding. +spring.mustache.check-template-location=true # Whether to check that the templates location exists. +spring.mustache.content-type=text/html # Content-Type value. +spring.mustache.enabled=true # Whether to enable MVC view resolution for this technology. +spring.mustache.expose-request-attributes=false # Whether all request attributes should be added to the model prior to merging with the template. +spring.mustache.expose-session-attributes=false # Whether all HttpSession attributes should be added to the model prior to merging with the template. +spring.mustache.expose-spring-macro-helpers=true # Whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". spring.mustache.prefix=classpath:/templates/ # Prefix to apply to template names. spring.mustache.request-context-attribute= # Name of the RequestContext attribute for all views. spring.mustache.suffix=.mustache # Suffix to apply to template names. spring.mustache.view-names= # White list of view names that can be resolved. # SPRING MVC (WebMvcProperties) -spring.mvc.async.request-timeout= # Amount of time (in milliseconds) before asynchronous request handling times out. -spring.mvc.date-format= # Date format to use. For instance `dd/MM/yyyy`. -spring.mvc.dispatch-trace-request=false # Dispatch TRACE requests to the FrameworkServlet doService method. -spring.mvc.dispatch-options-request=true # Dispatch OPTIONS requests to the FrameworkServlet doService method. -spring.mvc.favicon.enabled=true # Enable resolution of favicon.ico. -spring.mvc.formcontent.putfilter.enabled=true # Enable Spring's HttpPutFormContentFilter. -spring.mvc.ignore-default-model-on-redirect=true # If the content of the "default" model should be ignored during redirect scenarios. +spring.mvc.async.request-timeout= # Amount of time before asynchronous request handling times out. +spring.mvc.contentnegotiation.favor-parameter=false # Whether a request parameter ("format" by default) should be used to determine the requested media type. +spring.mvc.contentnegotiation.favor-path-extension=false # Whether the path extension in the URL path should be used to determine the requested media type. +spring.mvc.contentnegotiation.media-types.*= # Map file extensions to media types for content negotiation. For instance, yml to text/yaml. +spring.mvc.contentnegotiation.parameter-name= # Query parameter name to use when "favor-parameter" is enabled. +spring.mvc.date-format= # Date format to use. For instance, `dd/MM/yyyy`. +spring.mvc.dispatch-trace-request=false # Whether to dispatch TRACE requests to the FrameworkServlet doService method. +spring.mvc.dispatch-options-request=true # Whether to dispatch OPTIONS requests to the FrameworkServlet doService method. +spring.mvc.favicon.enabled=true # Whether to enable resolution of favicon.ico. +spring.mvc.formcontent.putfilter.enabled=true # Whether to enable Spring's HttpPutFormContentFilter. +spring.mvc.ignore-default-model-on-redirect=true # Whether the content of the "default" model should be ignored during redirect scenarios. spring.mvc.locale= # Locale to use. By default, this locale is overridden by the "Accept-Language" header. spring.mvc.locale-resolver=accept-header # Define how the locale should be resolved. -spring.mvc.log-resolved-exception=false # Enable warn logging of exceptions resolved by a "HandlerExceptionResolver". -spring.mvc.media-types.*= # Maps file extensions to media types for content negotiation. -spring.mvc.message-codes-resolver-format= # Formatting strategy for message codes. For instance `PREFIX_ERROR_CODE`. -spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the Spring Web Services servlet. +spring.mvc.log-resolved-exception=false # Whether to enable warn logging of exceptions resolved by a "HandlerExceptionResolver". +spring.mvc.message-codes-resolver-format= # Formatting strategy for message codes. For instance, `PREFIX_ERROR_CODE`. +spring.mvc.pathmatch.use-registered-suffix-pattern=false # Whether suffix pattern matching should work only against extensions registered with "spring.mvc.contentnegotiation.media-types.*". +spring.mvc.pathmatch.use-suffix-pattern=false # Whether to use suffix pattern match (".*") when matching patterns to requests. +spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet. spring.mvc.static-path-pattern=/** # Path pattern used for static resources. -spring.mvc.throw-exception-if-no-handler-found=false # If a "NoHandlerFoundException" should be thrown if no Handler was found to process a request. +spring.mvc.throw-exception-if-no-handler-found=false # Whether a "NoHandlerFoundException" should be thrown if no Handler was found to process a request. spring.mvc.view.prefix= # Spring MVC view prefix. spring.mvc.view.suffix= # Spring MVC view suffix. # SPRING RESOURCES HANDLING (ResourceProperties) -spring.resources.add-mappings=true # Enable default resource handling. -spring.resources.cache-period= # Cache period for the resources served by the resource handler, in seconds. -spring.resources.chain.cache=true # Enable caching in the Resource chain. -spring.resources.chain.enabled= # Enable the Spring Resource Handling chain. Disabled by default unless at least one strategy has been enabled. -spring.resources.chain.gzipped=false # Enable resolution of already gzipped resources. -spring.resources.chain.html-application-cache=false # Enable HTML5 application cache manifest rewriting. -spring.resources.chain.strategy.content.enabled=false # Enable the content Version Strategy. -spring.resources.chain.strategy.content.paths=/** # Comma-separated list of patterns to apply to the Version Strategy. -spring.resources.chain.strategy.fixed.enabled=false # Enable the fixed Version Strategy. -spring.resources.chain.strategy.fixed.paths=/** # Comma-separated list of patterns to apply to the Version Strategy. -spring.resources.chain.strategy.fixed.version= # Version string to use for the Version Strategy. +spring.resources.add-mappings=true # Whether to enable default resource handling. +spring.resources.cache.cachecontrol.cache-private= # Indicate that the response message is intended for a single user and must not be stored by a shared cache. +spring.resources.cache.cachecontrol.cache-public= # Indicate that any cache may store the response. +spring.resources.cache.cachecontrol.max-age= # Maximum time the response should be cached, in seconds if no duration suffix is not specified. +spring.resources.cache.cachecontrol.must-revalidate= # Indicate that once it has become stale, a cache must not use the response without re-validating it with the server. +spring.resources.cache.cachecontrol.no-cache= # Indicate that the cached response can be reused only if re-validated with the server. +spring.resources.cache.cachecontrol.no-store= # Indicate to not cache the response in any case. +spring.resources.cache.cachecontrol.no-transform= # Indicate intermediaries (caches and others) that they should not transform the response content. +spring.resources.cache.cachecontrol.proxy-revalidate= # Same meaning as the "must-revalidate" directive, except that it does not apply to private caches. +spring.resources.cache.cachecontrol.s-max-age= # Maximum time the response should be cached by shared caches, in seconds if no duration suffix is not specified. +spring.resources.cache.cachecontrol.stale-if-error= # Maximum time the response may be used when errors are encountered, in seconds if no duration suffix is not specified. +spring.resources.cache.cachecontrol.stale-while-revalidate= # Maximum time the response can be served after it becomes stale, in seconds if no duration suffix is not specified. +spring.resources.cache.period= # Cache period for the resources served by the resource handler. If a duration suffix is not specified, seconds will be used. +spring.resources.chain.cache=true # Whether to enable caching in the Resource chain. +spring.resources.chain.enabled= # Whether to enable the Spring Resource Handling chain. By default, disabled unless at least one strategy has been enabled. +spring.resources.chain.gzipped=false # Whether to enable resolution of already gzipped resources. +spring.resources.chain.html-application-cache=false # Whether to enable HTML5 application cache manifest rewriting. +spring.resources.chain.strategy.content.enabled=false # Whether to enable the content Version Strategy. +spring.resources.chain.strategy.content.paths=/** # Comma-separated list of patterns to apply to the content Version Strategy. +spring.resources.chain.strategy.fixed.enabled=false # Whether to enable the fixed Version Strategy. +spring.resources.chain.strategy.fixed.paths=/** # Comma-separated list of patterns to apply to the fixed Version Strategy. +spring.resources.chain.strategy.fixed.version= # Version string to use for the fixed Version Strategy. spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ # Locations of static resources. # SPRING SESSION (SessionProperties) -spring.session.hazelcast.flush-mode=on-save # Sessions flush mode. -spring.session.hazelcast.map-name=spring:session:sessions # Name of the map used to store sessions. -spring.session.jdbc.initializer.enabled= # Create the required session tables on startup if necessary. Enabled automatically if the default table name is set or a custom schema is configured. -spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. -spring.session.jdbc.table-name=SPRING_SESSION # Name of database table used to store sessions. -spring.session.redis.flush-mode=on-save # Sessions flush mode. -spring.session.redis.namespace= # Namespace for keys used to store sessions. spring.session.store-type= # Session store type. +spring.session.servlet.filter-order=-2147483598 # Session repository filter order. +spring.session.servlet.filter-dispatcher-types=async,error,request # Session repository filter dispatcher types. -# SPRING SOCIAL (SocialWebAutoConfiguration) -spring.social.auto-connection-views=false # Enable the connection status view for supported providers. +# SPRING SESSION HAZELCAST (HazelcastSessionProperties) +spring.session.hazelcast.flush-mode=on-save # Sessions flush mode. +spring.session.hazelcast.map-name=spring:session:sessions # Name of the map used to store sessions. -# SPRING SOCIAL FACEBOOK (FacebookAutoConfiguration) -spring.social.facebook.app-id= # your application's Facebook App ID -spring.social.facebook.app-secret= # your application's Facebook App Secret +# SPRING SESSION JDBC (JdbcSessionProperties) +spring.session.jdbc.cleanup-cron=0 * * * * * # Cron expression for expired session cleanup job. +spring.session.jdbc.initialize-schema=embedded # Database schema initialization mode. +spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. +spring.session.jdbc.table-name=SPRING_SESSION # Name of the database table used to store sessions. -# SPRING SOCIAL LINKEDIN (LinkedInAutoConfiguration) -spring.social.linkedin.app-id= # your application's LinkedIn App ID -spring.social.linkedin.app-secret= # your application's LinkedIn App Secret +# SPRING SESSION MONGODB (MongoSessionProperties) +spring.session.mongodb.collection-name=sessions # Collection name used to store sessions. -# SPRING SOCIAL TWITTER (TwitterAutoConfiguration) -spring.social.twitter.app-id= # your application's Twitter App ID -spring.social.twitter.app-secret= # your application's Twitter App Secret +# SPRING SESSION REDIS (RedisSessionProperties) +spring.session.redis.cleanup-cron=0 * * * * * # Cron expression for expired session cleanup job. +spring.session.redis.flush-mode=on-save # Sessions flush mode. +spring.session.redis.namespace=spring:session # Namespace for keys used to store sessions. # THYMELEAF (ThymeleafAutoConfiguration) -spring.thymeleaf.cache=true # Enable template caching. -spring.thymeleaf.check-template=true # Check that the template exists before rendering it. -spring.thymeleaf.check-template-location=true # Check that the templates location exists. -spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks. +spring.thymeleaf.cache=true # Whether to enable template caching. +spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it. +spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists. +spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks. +spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions. spring.thymeleaf.encoding=UTF-8 # Template files encoding. -spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution. -spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers. +spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution. +spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum. spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL. -spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes. +spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set. +spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set. +spring.thymeleaf.reactive.max-chunk-size=0 # Maximum size of data buffers used for writing to the response, in bytes. spring.thymeleaf.reactive.media-types= # Media types supported by the view technology. spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses. spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL. spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. -spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved. +spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved. -# SPRING WEB FLUX (WebFluxProperties) +# SPRING WEBFLUX (WebFluxProperties) +spring.webflux.date-format= # Date format to use. For instance, `dd/MM/yyyy`. spring.webflux.static-path-pattern=/** # Path pattern used for static resources. # SPRING WEB SERVICES (WebServicesProperties) spring.webservices.path=/services # Path that serves as the base URI for the services. spring.webservices.servlet.init= # Servlet init parameters to pass to Spring Web Services. spring.webservices.servlet.load-on-startup=-1 # Load on startup priority of the Spring Web Services servlet. +spring.webservices.wsdl-locations= # Comma-separated list of locations of WSDLs and accompanying XSDs to be exposed as beans. @@ -459,141 +492,110 @@ spring.webservices.servlet.load-on-startup=-1 # Load on startup priority of the # SECURITY PROPERTIES # ---------------------------------------- # SECURITY (SecurityProperties) -security.basic.authorize-mode=role # Security authorize mode to apply. -security.basic.enabled=true # Enable basic authentication. -security.basic.path=/** # Comma-separated list of paths to secure. -security.basic.realm=Spring # HTTP basic realm name. -security.enable-csrf=false # Enable Cross Site Request Forgery support. -security.filter-order=0 # Security filter chain order. -security.filter-dispatcher-types=ASYNC, FORWARD, INCLUDE, REQUEST # Security filter chain dispatcher types. -security.headers.cache=true # Enable cache control HTTP headers. -security.headers.content-security-policy= # Value for content security policy header. -security.headers.content-security-policy-mode=default # Content security policy mode. -security.headers.content-type=true # Enable "X-Content-Type-Options" header. -security.headers.frame=true # Enable "X-Frame-Options" header. -security.headers.hsts=all # HTTP Strict Transport Security (HSTS) mode (none, domain, all). -security.headers.xss=true # Enable cross site scripting (XSS) protection. -security.ignored= # Comma-separated list of paths to exclude from the default secured paths. -security.require-ssl=false # Enable secure channel for all requests. -security.sessions=stateless # Session creation policy (always, never, if_required, stateless). -security.user.name=user # Default user name. -security.user.password= # Password for the default user name. A random password is logged on startup by default. -security.user.role=USER # Granted roles for the default user name. +spring.security.filter.order=-100 # Security filter chain order. +spring.security.filter.dispatcher-types=async,error,request # Security filter chain dispatcher types. +spring.security.user.name=user # Default user name. +spring.security.user.password= # Password for the default user name. +spring.security.user.roles= # Granted roles for the default user name. # SECURITY OAUTH2 CLIENT (OAuth2ClientProperties) -security.oauth2.client.client-id= # OAuth2 client id. -security.oauth2.client.client-secret= # OAuth2 client secret. A random secret is generated by default - -# SECURITY OAUTH2 RESOURCES (ResourceServerProperties) -security.oauth2.resource.filter-order= # The order of the filter chain used to authenticate tokens. -security.oauth2.resource.id= # Identifier of the resource. -security.oauth2.resource.jwt.key-uri= # The URI of the JWT token. Can be set if the value is not available and the key is public. -security.oauth2.resource.jwt.key-value= # The verification key of the JWT token. Can either be a symmetric secret or PEM-encoded RSA public key. -security.oauth2.resource.prefer-token-info=true # Use the token info, can be set to false to use the user info. -security.oauth2.resource.service-id=resource # -security.oauth2.resource.token-info-uri= # URI of the token decoding endpoint. -security.oauth2.resource.token-type= # The token type to send when using the userInfoUri. -security.oauth2.resource.user-info-uri= # URI of the user endpoint. - -# SECURITY OAUTH2 SSO (OAuth2SsoProperties) -security.oauth2.sso.filter-order= # Filter order to apply if not providing an explicit WebSecurityConfigurerAdapter -security.oauth2.sso.login-path=/login # Path to the login page, i.e. the one that triggers the redirect to the OAuth2 Authorization Server - +spring.security.oauth2.client.provider.*= # OAuth provider details. +spring.security.oauth2.client.registration.*= # OAuth client registrations. # ---------------------------------------- # DATA PROPERTIES # ---------------------------------------- # FLYWAY (FlywayProperties) -flyway.allow-mixed-migrations= # -flyway.baseline-description= # -flyway.baseline-on-migrate= # -flyway.baseline-version=1 # version to start migration -flyway.check-location=false # Check that migration scripts location exists. -flyway.clean-disabled= # -flyway.clean-on-validation-error= # -flyway.enabled=true # Enable flyway. -flyway.encoding= # -flyway.ignore-failed-future-migration= # -flyway.ignore-future-migrations= # -flyway.ignore-missing-migrations= # -flyway.init-sqls= # SQL statements to execute to initialize a connection immediately after obtaining it. -flyway.installed-by= # -flyway.locations=classpath:db/migration # locations of migrations scripts -flyway.out-of-order= # -flyway.password= # JDBC password if you want Flyway to create its own DataSource -flyway.placeholder-prefix= # -flyway.placeholder-replacement= # -flyway.placeholder-suffix= # -flyway.placeholders.*= # -flyway.repeatable-sql-migration-prefix= # -flyway.schemas= # schemas to update -flyway.skip-default-callbacks= # -flyway.skip-default-resolvers= # -flyway.sql-migration-prefix=V # -flyway.sql-migration-separator= # -flyway.sql-migration-suffix=.sql # -flyway.table= # -flyway.target= # -flyway.url= # JDBC url of the database to migrate. If not set, the primary configured data source is used. -flyway.user= # Login user of the database to migrate. -flyway.validate-on-migrate= # +spring.flyway.baseline-description= # +spring.flyway.baseline-on-migrate= # +spring.flyway.baseline-version=1 # Version to start migration +spring.flyway.check-location=true # Whether to check that migration scripts location exists. +spring.flyway.clean-disabled= # +spring.flyway.clean-on-validation-error= # +spring.flyway.dry-run-output= # +spring.flyway.enabled=true # Whether to enable flyway. +spring.flyway.encoding= # +spring.flyway.error-handlers= # +spring.flyway.group= # +spring.flyway.ignore-future-migrations= # +spring.flyway.ignore-missing-migrations= # +spring.flyway.init-sqls= # SQL statements to execute to initialize a connection immediately after obtaining it. +spring.flyway.installed-by= # +spring.flyway.locations=classpath:db/migration # The locations of migrations scripts. +spring.flyway.mixed= # +spring.flyway.out-of-order= # +spring.flyway.password= # JDBC password to use if you want Flyway to create its own DataSource. +spring.flyway.placeholder-prefix= # +spring.flyway.placeholder-replacement= # +spring.flyway.placeholder-suffix= # +spring.flyway.placeholders.*= # +spring.flyway.repeatable-sql-migration-prefix= # +spring.flyway.schemas= # schemas to update +spring.flyway.skip-default-callbacks= # +spring.flyway.skip-default-resolvers= # +spring.flyway.sql-migration-prefix=V # +spring.flyway.sql-migration-separator= # +spring.flyway.sql-migration-suffix=.sql # +spring.flyway.sql-migration-suffixes= # +spring.flyway.table= # +spring.flyway.target= # +spring.flyway.undo-sql-migration-prefix= # +spring.flyway.url= # JDBC url of the database to migrate. If not set, the primary configured data source is used. +spring.flyway.user= # Login user of the database to migrate. +spring.flyway.validate-on-migrate= # # LIQUIBASE (LiquibaseProperties) -liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml # Change log configuration path. -liquibase.check-change-log-location=true # Check the change log location exists. -liquibase.contexts= # Comma-separated list of runtime contexts to use. -liquibase.default-schema= # Default database schema. -liquibase.drop-first=false # Drop the database schema first. -liquibase.enabled=true # Enable liquibase support. -liquibase.labels= # Comma-separated list of runtime labels to use. -liquibase.parameters.*= # Change log parameters. -liquibase.password= # Login password of the database to migrate. -liquibase.rollback-file= # File to which rollback SQL will be written when an update is performed. -liquibase.url= # JDBC url of the database to migrate. If not set, the primary configured data source is used. -liquibase.user= # Login user of the database to migrate. +spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml # Change log configuration path. +spring.liquibase.check-change-log-location=true # Whether to check that the change log location exists. +spring.liquibase.contexts= # Comma-separated list of runtime contexts to use. +spring.liquibase.default-schema= # Default database schema. +spring.liquibase.drop-first=false # Whether to first drop the database schema. +spring.liquibase.enabled=true # Whether to enable Liquibase support. +spring.liquibase.labels= # Comma-separated list of runtime labels to use. +spring.liquibase.parameters.*= # Change log parameters. +spring.liquibase.password= # Login password of the database to migrate. +spring.liquibase.rollback-file= # File to which rollback SQL is written when an update is performed. +spring.liquibase.url= # JDBC URL of the database to migrate. If not set, the primary configured data source is used. +spring.liquibase.user= # Login user of the database to migrate. # COUCHBASE (CouchbaseProperties) spring.couchbase.bootstrap-hosts= # Couchbase nodes (host or IP address) to bootstrap from. spring.couchbase.bucket.name=default # Name of the bucket to connect to. spring.couchbase.bucket.password= # Password of the bucket. -spring.couchbase.env.endpoints.key-value=1 # Number of sockets per node against the Key/value service. -spring.couchbase.env.endpoints.query=1 # Number of sockets per node against the Query (N1QL) service. +spring.couchbase.env.endpoints.key-value=1 # Number of sockets per node against the key/value service. +spring.couchbase.env.endpoints.query=1 # Number of sockets per node against the query (N1QL) service. spring.couchbase.env.endpoints.view=1 # Number of sockets per node against the view service. -spring.couchbase.env.ssl.enabled= # Enable SSL support. Enabled automatically if a "keyStore" is provided unless specified otherwise. +spring.couchbase.env.ssl.enabled= # Whether to enable SSL support. Enabled automatically if a "keyStore" is provided unless specified otherwise. spring.couchbase.env.ssl.key-store= # Path to the JVM key store that holds the certificates. spring.couchbase.env.ssl.key-store-password= # Password used to access the key store. -spring.couchbase.env.timeouts.connect=5000 # Bucket connections timeout in milliseconds. -spring.couchbase.env.timeouts.key-value=2500 # Blocking operations performed on a specific key timeout in milliseconds. -spring.couchbase.env.timeouts.query=7500 # N1QL query operations timeout in milliseconds. -spring.couchbase.env.timeouts.socket-connect=1000 # Socket connect connections timeout in milliseconds. -spring.couchbase.env.timeouts.view=7500 # Regular and geospatial view operations timeout in milliseconds. +spring.couchbase.env.timeouts.connect=5000ms # Bucket connections timeouts. +spring.couchbase.env.timeouts.key-value=2500ms # Blocking operations performed on a specific key timeout. +spring.couchbase.env.timeouts.query=7500ms # N1QL query operations timeout. +spring.couchbase.env.timeouts.socket-connect=1000ms # Socket connect connections timeout. +spring.couchbase.env.timeouts.view=7500ms # Regular and geospatial view operations timeout. # DAO (PersistenceExceptionTranslationAutoConfiguration) -spring.dao.exceptiontranslation.enabled=true # Enable the PersistenceExceptionTranslationPostProcessor. +spring.dao.exceptiontranslation.enabled=true # Whether to enable the PersistenceExceptionTranslationPostProcessor. # CASSANDRA (CassandraProperties) spring.data.cassandra.cluster-name= # Name of the Cassandra cluster. spring.data.cassandra.compression=none # Compression supported by the Cassandra binary protocol. -spring.data.cassandra.connect-timeout-millis= # Socket option: connection time out. +spring.data.cassandra.connect-timeout= # Socket option: connection time out. spring.data.cassandra.consistency-level= # Queries consistency level. -spring.data.cassandra.contact-points=localhost # Comma-separated list of cluster node addresses. +spring.data.cassandra.contact-points=localhost # Cluster node addresses. spring.data.cassandra.fetch-size= # Queries default fetch size. -spring.data.cassandra.heartbeat-interval-seconds= # Pooling option: heartbeat interval. spring.data.cassandra.keyspace-name= # Keyspace name to use. spring.data.cassandra.load-balancing-policy= # Class name of the load balancing policy. -spring.data.cassandra.max-requests-per-connection.*= # Pooling option: max requests per connection. -spring.data.cassandra.max-queue-size= # Pooling option: max queue size. spring.data.cassandra.port= # Port of the Cassandra server. spring.data.cassandra.password= # Login password of the server. -spring.data.cassandra.pool.heartbeat-interval=30 # Heartbeat interval (in seconds) after which a message is sent on an idle connection to make sure it's still alive. -spring.data.cassandra.pool.idle-timeout=120 # Idle timeout (in seconds) before an idle connection is removed. -spring.data.cassandra.pool.max-queue-size=256 # Maximum number of requests that get enqueued if no connection is available. -spring.data.cassandra.pool.pool-timeout=5000 # Pool timeout (in milliseconds) when trying to acquire a connection from a host's pool. -spring.data.cassandra.reactive-repositories.enabled=true # Enable Cassandra reactive repositories. -spring.data.cassandra.read-timeout-millis= # Socket option: read time out. +spring.data.cassandra.pool.heartbeat-interval=30s # Heartbeat interval after which a message is sent on an idle connection to make sure it's still alive. If a duration suffix is not specified, seconds will be used. +spring.data.cassandra.pool.idle-timeout=120s # Idle timeout before an idle connection is removed. If a duration suffix is not specified, seconds will be used. +spring.data.cassandra.pool.max-queue-size=256 # Maximum number of requests that get queued if no connection is available. +spring.data.cassandra.pool.pool-timeout=5000ms # Pool timeout when trying to acquire a connection from a host's pool. +spring.data.cassandra.read-timeout= # Socket option: read time out. spring.data.cassandra.reconnection-policy= # Reconnection policy class. -spring.data.cassandra.repositories.enabled= # Enable Cassandra repositories. +spring.data.cassandra.repositories.type=auto # Type of Cassandra repositories to enable. spring.data.cassandra.retry-policy= # Class name of the retry policy. spring.data.cassandra.serial-consistency-level= # Queries serial consistency level. spring.data.cassandra.schema-action=none # Schema action to take at startup. @@ -603,143 +605,148 @@ spring.data.cassandra.username= # Login user of the server. # DATA COUCHBASE (CouchbaseDataProperties) spring.data.couchbase.auto-index=false # Automatically create views and indexes. spring.data.couchbase.consistency=read-your-own-writes # Consistency to apply by default on generated queries. -spring.data.couchbase.repositories.enabled=true # Enable Couchbase repositories. +spring.data.couchbase.repositories.type=auto # Type of Couchbase repositories to enable. # ELASTICSEARCH (ElasticsearchProperties) spring.data.elasticsearch.cluster-name=elasticsearch # Elasticsearch cluster name. spring.data.elasticsearch.cluster-nodes= # Comma-separated list of cluster node addresses. spring.data.elasticsearch.properties.*= # Additional properties used to configure the client. -spring.data.elasticsearch.repositories.enabled=true # Enable Elasticsearch repositories. +spring.data.elasticsearch.repositories.enabled=true # Whether to enable Elasticsearch repositories. # DATA LDAP -spring.data.ldap.repositories.enabled=true # Enable LDAP repositories. +spring.data.ldap.repositories.enabled=true # Whether to enable LDAP repositories. # MONGODB (MongoProperties) spring.data.mongodb.authentication-database= # Authentication database name. -spring.data.mongodb.database=test # Database name. +spring.data.mongodb.database= # Database name. spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use. spring.data.mongodb.grid-fs-database= # GridFS database name. -spring.data.mongodb.host=localhost # Mongo server host. Cannot be set with uri. -spring.data.mongodb.password= # Login password of the mongo server. Cannot be set with uri. -spring.data.mongodb.port=27017 # Mongo server port. Cannot be set with uri. -spring.data.mongodb.reactive-repositories.enabled=true # Enable Mongo reactive repositories. -spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories. +spring.data.mongodb.host= # Mongo server host. Cannot be set with URI. +spring.data.mongodb.password= # Login password of the mongo server. Cannot be set with URI. +spring.data.mongodb.port= # Mongo server port. Cannot be set with URI. +spring.data.mongodb.repositories.type=auto # Type of Mongo repositories to enable. spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. Cannot be set with host, port and credentials. -spring.data.mongodb.username= # Login user of the mongo server. Cannot be set with uri. +spring.data.mongodb.username= # Login user of the mongo server. Cannot be set with URI. # DATA REDIS -spring.data.redis.repositories.enabled=true # Enable Redis repositories. +spring.data.redis.repositories.enabled=true # Whether to enable Redis repositories. # NEO4J (Neo4jProperties) spring.data.neo4j.auto-index=none # Auto index mode. -spring.data.neo4j.embedded.enabled=true # Enable embedded mode if the embedded driver is available. -spring.data.neo4j.open-in-view=false # Register OpenSessionInViewInterceptor. Binds a Neo4j Session to the thread for the entire processing of the request. +spring.data.neo4j.embedded.enabled=true # Whether to enable embedded mode if the embedded driver is available. +spring.data.neo4j.open-in-view=true # Register OpenSessionInViewInterceptor. Binds a Neo4j Session to the thread for the entire processing of the request. spring.data.neo4j.password= # Login password of the server. -spring.data.neo4j.repositories.enabled=true # Enable Neo4j repositories. +spring.data.neo4j.repositories.enabled=true # Whether to enable Neo4j repositories. spring.data.neo4j.uri= # URI used by the driver. Auto-detected by default. spring.data.neo4j.username= # Login user of the server. # DATA REST (RepositoryRestProperties) spring.data.rest.base-path= # Base path to be used by Spring Data REST to expose repository resources. +spring.data.rest.default-media-type= # Content type to use as a default when none is specified. spring.data.rest.default-page-size= # Default size of pages. spring.data.rest.detection-strategy=default # Strategy to use to determine which repositories get exposed. -spring.data.rest.enable-enum-translation= # Enable enum value translation via the Spring Data REST default resource bundle. +spring.data.rest.enable-enum-translation= # Whether to enable enum value translation through the Spring Data REST default resource bundle. spring.data.rest.limit-param-name= # Name of the URL query string parameter that indicates how many results to return at once. spring.data.rest.max-page-size= # Maximum size of pages. spring.data.rest.page-param-name= # Name of the URL query string parameter that indicates what page to return. -spring.data.rest.return-body-on-create= # Return a response body after creating an entity. -spring.data.rest.return-body-on-update= # Return a response body after updating an entity. +spring.data.rest.return-body-on-create= # Whether to return a response body after creating an entity. +spring.data.rest.return-body-on-update= # Whether to return a response body after updating an entity. spring.data.rest.sort-param-name= # Name of the URL query string parameter that indicates what direction to sort results. # SOLR (SolrProperties) spring.data.solr.host=http://127.0.0.1:8983/solr # Solr host. Ignored if "zk-host" is set. -spring.data.solr.repositories.enabled=true # Enable Solr repositories. +spring.data.solr.repositories.enabled=true # Whether to enable Solr repositories. spring.data.solr.zk-host= # ZooKeeper host address in the form HOST:PORT. # DATA WEB (SpringDataWebProperties) spring.data.web.pageable.default-page-size=20 # Default page size. +spring.data.web.pageable.max-page-size=2000 # Maximum page size to be accepted. +spring.data.web.pageable.one-indexed-parameters=false # Whether to expose and assume 1-based page number indexes. spring.data.web.pageable.page-parameter=page # Page index parameter name. +spring.data.web.pageable.prefix= # General prefix to be prepended to the page number and page size parameters. +spring.data.web.pageable.qualifier-delimiter=_ # Delimiter to be used between the qualifier and the actual page number and size properties. spring.data.web.pageable.size-parameter=size # Page size parameter name. spring.data.web.sort.sort-parameter=sort # Sort parameter name. # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) -spring.datasource.continue-on-error=false # Do not stop if an error occurs while initializing the database. +spring.datasource.continue-on-error=false # Whether to stop if an error occurs while initializing the database. spring.datasource.data= # Data (DML) script resource references. -spring.datasource.data-username= # User of the database to execute DML scripts (if different). +spring.datasource.data-username= # Username of the database to execute DML scripts (if different). spring.datasource.data-password= # Password of the database to execute DML scripts (if different). spring.datasource.dbcp2.*= # Commons DBCP2 specific settings spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. -spring.datasource.generate-unique-name=false # Generate a random datasource name. +spring.datasource.generate-unique-name=false # Whether to generate a random datasource name. spring.datasource.hikari.*= # Hikari specific settings -spring.datasource.initialize=true # Populate the database using 'data.sql'. -spring.datasource.jmx-enabled=false # Enable JMX support (if provided by the underlying pool). +spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts. +spring.datasource.jmx-enabled=false # Whether to enable JMX support (if provided by the underlying pool). spring.datasource.jndi-name= # JNDI location of the datasource. Class, url, username & password are ignored when set. -spring.datasource.name=testdb # Name of the datasource. +spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database. spring.datasource.password= # Login password of the database. -spring.datasource.platform=all # Platform to use in the schema resource (schema-${platform}.sql). +spring.datasource.platform=all # Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or data-${platform}.sql). spring.datasource.schema= # Schema (DDL) script resource references. -spring.datasource.schema-username= # User of the database to execute DDL scripts (if different). +spring.datasource.schema-username= # Username of the database to execute DDL scripts (if different). spring.datasource.schema-password= # Password of the database to execute DDL scripts (if different). spring.datasource.separator=; # Statement separator in SQL initialization scripts. spring.datasource.sql-script-encoding= # SQL scripts encoding. spring.datasource.tomcat.*= # Tomcat datasource specific settings spring.datasource.type= # Fully qualified name of the connection pool implementation to use. By default, it is auto-detected from the classpath. -spring.datasource.url= # JDBC url of the database. -spring.datasource.username= # Login user of the database. +spring.datasource.url= # JDBC URL of the database. +spring.datasource.username= # Login username of the database. spring.datasource.xa.data-source-class-name= # XA datasource fully qualified name. spring.datasource.xa.properties= # Properties to pass to the XA data source. # JEST (Elasticsearch HTTP client) (JestProperties) -spring.elasticsearch.jest.connection-timeout=3000 # Connection timeout in milliseconds. -spring.elasticsearch.jest.multi-threaded=true # Enable connection requests from multiple execution threads. +spring.elasticsearch.jest.connection-timeout=3s # Connection timeout. +spring.elasticsearch.jest.multi-threaded=true # Whether to enable connection requests from multiple execution threads. spring.elasticsearch.jest.password= # Login password. spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use. spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use. -spring.elasticsearch.jest.read-timeout=3000 # Read timeout in milliseconds. +spring.elasticsearch.jest.read-timeout=3s # Read timeout. spring.elasticsearch.jest.uris=http://localhost:9200 # Comma-separated list of the Elasticsearch instances to use. -spring.elasticsearch.jest.username= # Login user. +spring.elasticsearch.jest.username= # Login username. # H2 Web Console (H2ConsoleProperties) -spring.h2.console.enabled=false # Enable the console. -spring.h2.console.path=/h2-console # Path at which the console will be available. -spring.h2.console.settings.trace=false # Enable trace output. -spring.h2.console.settings.web-allow-others=false # Enable remote access. +spring.h2.console.enabled=false # Whether to enable the console. +spring.h2.console.path=/h2-console # Path at which the console is available. +spring.h2.console.settings.trace=false # Whether to enable trace output. +spring.h2.console.settings.web-allow-others=false # Whether to enable remote access. # InfluxDB (InfluxDbProperties) spring.influx.password= # Login password. -spring.influx.url= # Url of the InfluxDB instance to connect to. +spring.influx.url= # URL of the InfluxDB instance to which to connect. spring.influx.user= # Login user. -# JOOQ (JooqAutoConfiguration) -spring.jooq.sql-dialect= # Sql dialect to use, auto-detected by default. +# JOOQ (JooqProperties) +spring.jooq.sql-dialect= # SQL dialect to use. Auto-detected by default. # JDBC (JdbcProperties) spring.jdbc.template.fetch-size=-1 # Number of rows that should be fetched from the database when more rows are needed. spring.jdbc.template.max-rows=-1 # Maximum number of rows. -spring.jdbc.template.query-timeout=-1 # Query timeout in seconds. +spring.jdbc.template.query-timeout= # Query timeout. Default is to use the JDBC driver's default configuration. If a duration suffix is not specified, seconds will be used. # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) -spring.data.jpa.repositories.enabled=true # Enable JPA repositories. +spring.data.jpa.repositories.enabled=true # Whether to enable JPA repositories. spring.jpa.database= # Target database to operate on, auto-detected by default. Can be alternatively set using the "databasePlatform" property. spring.jpa.database-platform= # Name of the target database to operate on, auto-detected by default. Can be alternatively set using the "Database" enum. -spring.jpa.generate-ddl=false # Initialize the schema on startup. -spring.jpa.hibernate.ddl-auto= # DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Default to "create-drop" when using an embedded database, "none" otherwise. -spring.jpa.hibernate.naming.implicit-strategy= # Hibernate 5 implicit naming strategy fully qualified name. -spring.jpa.hibernate.naming.physical-strategy= # Hibernate 5 physical naming strategy fully qualified name. -spring.jpa.hibernate.use-new-id-generator-mappings= # Use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE. +spring.jpa.generate-ddl=false # Whether to initialize the schema on startup. +spring.jpa.hibernate.ddl-auto= # DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none". +spring.jpa.hibernate.naming.implicit-strategy= # Fully qualified name of the implicit naming strategy. +spring.jpa.hibernate.naming.physical-strategy= # Fully qualified name of the physical naming strategy. +spring.jpa.hibernate.use-new-id-generator-mappings= # Whether to use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE. +spring.jpa.mapping-resources= # Mapping resources (equivalent to "mapping-file" entries in persistence.xml). spring.jpa.open-in-view=true # Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for the entire processing of the request. spring.jpa.properties.*= # Additional native properties to set on the JPA provider. -spring.jpa.show-sql=false # Enable logging of SQL statements. +spring.jpa.show-sql=false # Whether to enable logging of SQL statements. # JTA (JtaAutoConfiguration) -spring.jta.enabled=true # Enable JTA support. +spring.jta.enabled=true # Whether to enable JTA support. spring.jta.log-dir= # Transaction logs directory. spring.jta.transaction-manager-id= # Transaction manager unique identifier. # ATOMIKOS (AtomikosProperties) spring.jta.atomikos.connectionfactory.borrow-connection-timeout=30 # Timeout, in seconds, for borrowing connections from the pool. -spring.jta.atomikos.connectionfactory.ignore-session-transacted-flag=true # Whether or not to ignore the transacted flag when creating session. -spring.jta.atomikos.connectionfactory.local-transaction-mode=false # Whether or not local transactions are desired. +spring.jta.atomikos.connectionfactory.ignore-session-transacted-flag=true # Whether to ignore the transacted flag when creating session. +spring.jta.atomikos.connectionfactory.local-transaction-mode=false # Whether local transactions are desired. spring.jta.atomikos.connectionfactory.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread. spring.jta.atomikos.connectionfactory.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. spring.jta.atomikos.connectionfactory.max-lifetime=0 # The time, in seconds, that a connection can be pooled for before being destroyed. 0 denotes no limit. @@ -747,7 +754,10 @@ spring.jta.atomikos.connectionfactory.max-pool-size=1 # The maximum size of the spring.jta.atomikos.connectionfactory.min-pool-size=1 # The minimum size of the pool. spring.jta.atomikos.connectionfactory.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. spring.jta.atomikos.connectionfactory.unique-resource-name=jmsConnectionFactory # The unique name used to identify the resource during recovery. +spring.jta.atomikos.connectionfactory.xa-connection-factory-class-name= # Vendor-specific implementation of XAConnectionFactory. +spring.jta.atomikos.connectionfactory.xa-properties= # Vendor-specific XA properties. spring.jta.atomikos.datasource.borrow-connection-timeout=30 # Timeout, in seconds, for borrowing connections from the pool. +spring.jta.atomikos.datasource.concurrent-connection-validation= # Whether to use concurrent connection validation. spring.jta.atomikos.datasource.default-isolation-level= # Default isolation level of connections provided by the pool. spring.jta.atomikos.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection. spring.jta.atomikos.datasource.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread. @@ -758,54 +768,65 @@ spring.jta.atomikos.datasource.min-pool-size=1 # The minimum size of the pool. spring.jta.atomikos.datasource.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. spring.jta.atomikos.datasource.test-query= # SQL query or statement used to validate a connection before returning it. spring.jta.atomikos.datasource.unique-resource-name=dataSource # The unique name used to identify the resource during recovery. -spring.jta.atomikos.properties.allow-sub-transactions=true # Specify if sub-transactions are allowed. -spring.jta.atomikos.properties.checkpoint-interval=500 # Interval between checkpoints. -spring.jta.atomikos.properties.default-jta-timeout=10000 # Default timeout for JTA transactions. -spring.jta.atomikos.properties.enable-logging=true # Enable disk logging. -spring.jta.atomikos.properties.force-shutdown-on-vm-exit=false # Specify if a VM shutdown should trigger forced shutdown of the transaction core. +spring.jta.atomikos.datasource.xa-data-source-class-name= # Vendor-specific implementation of XAConnectionFactory. +spring.jta.atomikos.datasource.xa-properties= # Vendor-specific XA properties. +spring.jta.atomikos.properties.allow-sub-transactions=true # Specify whether sub-transactions are allowed. +spring.jta.atomikos.properties.checkpoint-interval=500 # Interval between checkpoints, expressed as the number of log writes between two checkpoint. +spring.jta.atomikos.properties.default-jta-timeout=10000ms # Default timeout for JTA transactions. +spring.jta.atomikos.properties.default-max-wait-time-on-shutdown=9223372036854775807 # How long should normal shutdown (no-force) wait for transactions to complete. +spring.jta.atomikos.properties.enable-logging=true # Whether to enable disk logging. +spring.jta.atomikos.properties.force-shutdown-on-vm-exit=false # Whether a VM shutdown should trigger forced shutdown of the transaction core. spring.jta.atomikos.properties.log-base-dir= # Directory in which the log files should be stored. spring.jta.atomikos.properties.log-base-name=tmlog # Transactions log file base name. spring.jta.atomikos.properties.max-actives=50 # Maximum number of active transactions. -spring.jta.atomikos.properties.max-timeout=300000 # Maximum timeout (in milliseconds) that can be allowed for transactions. -spring.jta.atomikos.properties.recovery.delay=10000 # Delay between two recovery scans. -spring.jta.atomikos.properties.recovery.forget-orphaned-log-entries-delay=86400000 # Delay after which recovery can cleanup pending ('orphaned') log entries. -spring.jta.atomikos.properties.recovery.max-retries=5 # Number of retries attempts to commit the transaction before throwing an exception. -spring.jta.atomikos.properties.recovery.retry-interval=10000 # Delay between retry attempts. -spring.jta.atomikos.properties.serial-jta-transactions=true # Specify if sub-transactions should be joined when possible. +spring.jta.atomikos.properties.max-timeout=300000ms # Maximum timeout that can be allowed for transactions. +spring.jta.atomikos.properties.recovery.delay=10000ms # Delay between two recovery scans. +spring.jta.atomikos.properties.recovery.forget-orphaned-log-entries-delay=86400000ms # Delay after which recovery can cleanup pending ('orphaned') log entries. +spring.jta.atomikos.properties.recovery.max-retries=5 # Number of retry attempts to commit the transaction before throwing an exception. +spring.jta.atomikos.properties.recovery.retry-interval=10000ms # Delay between retry attempts. +spring.jta.atomikos.properties.serial-jta-transactions=true # Whether sub-transactions should be joined when possible. spring.jta.atomikos.properties.service= # Transaction manager implementation that should be started. -spring.jta.atomikos.properties.threaded-two-phase-commit=false # Use different (and concurrent) threads for two-phase commit on the participating resources. -spring.jta.atomikos.properties.transaction-manager-unique-name= # Transaction manager's unique name. +spring.jta.atomikos.properties.threaded-two-phase-commit=false # Whether to use different (and concurrent) threads for two-phase commit on the participating resources. +spring.jta.atomikos.properties.transaction-manager-unique-name= # The transaction manager's unique name. # BITRONIX spring.jta.bitronix.connectionfactory.acquire-increment=1 # Number of connections to create when growing the pool. spring.jta.bitronix.connectionfactory.acquisition-interval=1 # Time, in seconds, to wait before trying to acquire a connection again after an invalid connection was acquired. spring.jta.bitronix.connectionfactory.acquisition-timeout=30 # Timeout, in seconds, for acquiring connections from the pool. -spring.jta.bitronix.connectionfactory.allow-local-transactions=true # Whether or not the transaction manager should allow mixing XA and non-XA transactions. -spring.jta.bitronix.connectionfactory.apply-transaction-timeout=false # Whether or not the transaction timeout should be set on the XAResource when it is enlisted. -spring.jta.bitronix.connectionfactory.automatic-enlisting-enabled=true # Whether or not resources should be enlisted and delisted automatically. -spring.jta.bitronix.connectionfactory.cache-producers-consumers=true # Whether or not produces and consumers should be cached. -spring.jta.bitronix.connectionfactory.defer-connection-release=true # Whether or not the provider can run many transactions on the same connection and supports transaction interleaving. -spring.jta.bitronix.connectionfactory.ignore-recovery-failures=false # Whether or not recovery failures should be ignored. +spring.jta.bitronix.connectionfactory.allow-local-transactions=true # Whether the transaction manager should allow mixing XA and non-XA transactions. +spring.jta.bitronix.connectionfactory.apply-transaction-timeout=false # Whether the transaction timeout should be set on the XAResource when it is enlisted. +spring.jta.bitronix.connectionfactory.automatic-enlisting-enabled=true # Whether resources should be enlisted and delisted automatically. +spring.jta.bitronix.connectionfactory.cache-producers-consumers=true # Whether producers and consumers should be cached. +spring.jta.bitronix.connectionfactory.class-name= # Underlying implementation class name of the XA resource. +spring.jta.bitronix.connectionfactory.defer-connection-release=true # Whether the provider can run many transactions on the same connection and supports transaction interleaving. +spring.jta.bitronix.connectionfactory.disabled= # Whether this resource is disabled, meaning it's temporarily forbidden to acquire a connection from its pool. +spring.jta.bitronix.connectionfactory.driver-properties= # Properties that should be set on the underlying implementation. +spring.jta.bitronix.connectionfactory.failed= # Mark this resource producer as failed. +spring.jta.bitronix.connectionfactory.ignore-recovery-failures=false # Whether recovery failures should be ignored. spring.jta.bitronix.connectionfactory.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. spring.jta.bitronix.connectionfactory.max-pool-size=10 # The maximum size of the pool. 0 denotes no limit. spring.jta.bitronix.connectionfactory.min-pool-size=0 # The minimum size of the pool. spring.jta.bitronix.connectionfactory.password= # The password to use to connect to the JMS provider. -spring.jta.bitronix.connectionfactory.share-transaction-connections=false # Whether or not connections in the ACCESSIBLE state can be shared within the context of a transaction. -spring.jta.bitronix.connectionfactory.test-connections=true # Whether or not connections should be tested when acquired from the pool. +spring.jta.bitronix.connectionfactory.share-transaction-connections=false # Whether connections in the ACCESSIBLE state can be shared within the context of a transaction. +spring.jta.bitronix.connectionfactory.test-connections=true # Whether connections should be tested when acquired from the pool. spring.jta.bitronix.connectionfactory.two-pc-ordering-position=1 # The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE). spring.jta.bitronix.connectionfactory.unique-name=jmsConnectionFactory # The unique name used to identify the resource during recovery. -spring.jta.bitronix.connectionfactory.use-tm-join=true Whether or not TMJOIN should be used when starting XAResources. +spring.jta.bitronix.connectionfactory.use-tm-join=true # Whether TMJOIN should be used when starting XAResources. spring.jta.bitronix.connectionfactory.user= # The user to use to connect to the JMS provider. spring.jta.bitronix.datasource.acquire-increment=1 # Number of connections to create when growing the pool. spring.jta.bitronix.datasource.acquisition-interval=1 # Time, in seconds, to wait before trying to acquire a connection again after an invalid connection was acquired. spring.jta.bitronix.datasource.acquisition-timeout=30 # Timeout, in seconds, for acquiring connections from the pool. -spring.jta.bitronix.datasource.allow-local-transactions=true # Whether or not the transaction manager should allow mixing XA and non-XA transactions. -spring.jta.bitronix.datasource.apply-transaction-timeout=false # Whether or not the transaction timeout should be set on the XAResource when it is enlisted. -spring.jta.bitronix.datasource.automatic-enlisting-enabled=true # Whether or not resources should be enlisted and delisted automatically. +spring.jta.bitronix.datasource.allow-local-transactions=true # Whether the transaction manager should allow mixing XA and non-XA transactions. +spring.jta.bitronix.datasource.apply-transaction-timeout=false # Whether the transaction timeout should be set on the XAResource when it is enlisted. +spring.jta.bitronix.datasource.automatic-enlisting-enabled=true # Whether resources should be enlisted and delisted automatically. +spring.jta.bitronix.datasource.class-name= # Underlying implementation class name of the XA resource. spring.jta.bitronix.datasource.cursor-holdability= # The default cursor holdability for connections. -spring.jta.bitronix.datasource.defer-connection-release=true # Whether or not the database can run many transactions on the same connection and supports transaction interleaving. -spring.jta.bitronix.datasource.enable-jdbc4-connection-test= # Whether or not Connection.isValid() is called when acquiring a connection from the pool. -spring.jta.bitronix.datasource.ignore-recovery-failures=false # Whether or not recovery failures should be ignored. +spring.jta.bitronix.datasource.defer-connection-release=true # Whether the database can run many transactions on the same connection and supports transaction interleaving. +spring.jta.bitronix.datasource.disabled= # Whether this resource is disabled, meaning it's temporarily forbidden to acquire a connection from its pool. +spring.jta.bitronix.datasource.driver-properties= # Properties that should be set on the underlying implementation. +spring.jta.bitronix.datasource.enable-jdbc4-connection-test= # Whether Connection.isValid() is called when acquiring a connection from the pool. +spring.jta.bitronix.datasource.failed= # Mark this resource producer as failed. +spring.jta.bitronix.datasource.ignore-recovery-failures=false # Whether recovery failures should be ignored. spring.jta.bitronix.datasource.isolation-level= # The default isolation level for connections. spring.jta.bitronix.datasource.local-auto-commit= # The default auto-commit mode for local transactions. spring.jta.bitronix.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection. @@ -813,81 +834,81 @@ spring.jta.bitronix.datasource.max-idle-time=60 # The time, in seconds, after wh spring.jta.bitronix.datasource.max-pool-size=10 # The maximum size of the pool. 0 denotes no limit. spring.jta.bitronix.datasource.min-pool-size=0 # The minimum size of the pool. spring.jta.bitronix.datasource.prepared-statement-cache-size=0 # The target size of the prepared statement cache. 0 disables the cache. -spring.jta.bitronix.datasource.share-transaction-connections=false # Whether or not connections in the ACCESSIBLE state can be shared within the context of a transaction. +spring.jta.bitronix.datasource.share-transaction-connections=false # Whether connections in the ACCESSIBLE state can be shared within the context of a transaction. spring.jta.bitronix.datasource.test-query= # SQL query or statement used to validate a connection before returning it. -spring.jta.bitronix.datasource.two-pc-ordering-position=1 # The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE). +spring.jta.bitronix.datasource.two-pc-ordering-position=1 # The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, and always last is Integer.MAX_VALUE). spring.jta.bitronix.datasource.unique-name=dataSource # The unique name used to identify the resource during recovery. -spring.jta.bitronix.datasource.use-tm-join=true Whether or not TMJOIN should be used when starting XAResources. -spring.jta.bitronix.properties.allow-multiple-lrc=false # Allow multiple LRC resources to be enlisted into the same transaction. -spring.jta.bitronix.properties.asynchronous2-pc=false # Enable asynchronously execution of two phase commit. +spring.jta.bitronix.datasource.use-tm-join=true # Whether TMJOIN should be used when starting XAResources. +spring.jta.bitronix.properties.allow-multiple-lrc=false # Whether to allow multiple LRC resources to be enlisted into the same transaction. +spring.jta.bitronix.properties.asynchronous2-pc=false # Whether to enable asynchronously execution of two phase commit. spring.jta.bitronix.properties.background-recovery-interval-seconds=60 # Interval in seconds at which to run the recovery process in the background. -spring.jta.bitronix.properties.current-node-only-recovery=true # Recover only the current node. -spring.jta.bitronix.properties.debug-zero-resource-transaction=false # Log the creation and commit call stacks of transactions executed without a single enlisted resource. -spring.jta.bitronix.properties.default-transaction-timeout=60 # Default transaction timeout in seconds. -spring.jta.bitronix.properties.disable-jmx=false # Enable JMX support. +spring.jta.bitronix.properties.current-node-only-recovery=true # Whether to recover only the current node. +spring.jta.bitronix.properties.debug-zero-resource-transaction=false # Whether to log the creation and commit call stacks of transactions executed without a single enlisted resource. +spring.jta.bitronix.properties.default-transaction-timeout=60 # Default transaction timeout, in seconds. +spring.jta.bitronix.properties.disable-jmx=false # Whether to enable JMX support. spring.jta.bitronix.properties.exception-analyzer= # Set the fully qualified name of the exception analyzer implementation to use. -spring.jta.bitronix.properties.filter-log-status=false # Enable filtering of logs so that only mandatory logs are written. -spring.jta.bitronix.properties.force-batching-enabled=true # Set if disk forces are batched. -spring.jta.bitronix.properties.forced-write-enabled=true # Set if logs are forced to disk. -spring.jta.bitronix.properties.graceful-shutdown-interval=60 # Maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown time. +spring.jta.bitronix.properties.filter-log-status=false # Whether to enable filtering of logs so that only mandatory logs are written. +spring.jta.bitronix.properties.force-batching-enabled=true # Whether disk forces are batched. +spring.jta.bitronix.properties.forced-write-enabled=true # Whether logs are forced to disk. +spring.jta.bitronix.properties.graceful-shutdown-interval=60 # Maximum amount of seconds the TM waits for transactions to get done before aborting them at shutdown time. spring.jta.bitronix.properties.jndi-transaction-synchronization-registry-name= # JNDI name of the TransactionSynchronizationRegistry. spring.jta.bitronix.properties.jndi-user-transaction-name= # JNDI name of the UserTransaction. -spring.jta.bitronix.properties.journal=disk # Name of the journal. Can be 'disk', 'null' or a class name. +spring.jta.bitronix.properties.journal=disk # Name of the journal. Can be 'disk', 'null', or a class name. spring.jta.bitronix.properties.log-part1-filename=btm1.tlog # Name of the first fragment of the journal. spring.jta.bitronix.properties.log-part2-filename=btm2.tlog # Name of the second fragment of the journal. spring.jta.bitronix.properties.max-log-size-in-mb=2 # Maximum size in megabytes of the journal fragments. spring.jta.bitronix.properties.resource-configuration-filename= # ResourceLoader configuration file name. -spring.jta.bitronix.properties.server-id= # ASCII ID that must uniquely identify this TM instance. Default to the machine's IP address. +spring.jta.bitronix.properties.server-id= # ASCII ID that must uniquely identify this TM instance. Defaults to the machine's IP address. spring.jta.bitronix.properties.skip-corrupted-logs=false # Skip corrupted transactions log entries. -spring.jta.bitronix.properties.warn-about-zero-resource-transaction=true # Log a warning for transactions executed without a single enlisted resource. +spring.jta.bitronix.properties.warn-about-zero-resource-transaction=true # Whether to log a warning for transactions executed without a single enlisted resource. # NARAYANA (NarayanaProperties) -spring.jta.narayana.default-timeout=60 # Transaction timeout in seconds. +spring.jta.narayana.default-timeout=60s # Transaction timeout. If a duration suffix is not specified, seconds will be used. spring.jta.narayana.expiry-scanners=com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner # Comma-separated list of expiry scanners. spring.jta.narayana.log-dir= # Transaction object store directory. -spring.jta.narayana.one-phase-commit=true # Enable one phase commit optimisation. -spring.jta.narayana.periodic-recovery-period=120 # Interval in which periodic recovery scans are performed in seconds. -spring.jta.narayana.recovery-backoff-period=10 # Back off period between first and second phases of the recovery scan in seconds. -spring.jta.narayana.recovery-db-pass= # Database password to be used by recovery manager. -spring.jta.narayana.recovery-db-user= # Database username to be used by recovery manager. -spring.jta.narayana.recovery-jms-pass= # JMS password to be used by recovery manager. -spring.jta.narayana.recovery-jms-user= # JMS username to be used by recovery manager. +spring.jta.narayana.one-phase-commit=true # Whether to enable one phase commit optimization. +spring.jta.narayana.periodic-recovery-period=120s # Interval in which periodic recovery scans are performed. If a duration suffix is not specified, seconds will be used. +spring.jta.narayana.recovery-backoff-period=10s # Back off period between first and second phases of the recovery scan. If a duration suffix is not specified, seconds will be used. +spring.jta.narayana.recovery-db-pass= # Database password to be used by the recovery manager. +spring.jta.narayana.recovery-db-user= # Database username to be used by the recovery manager. +spring.jta.narayana.recovery-jms-pass= # JMS password to be used by the recovery manager. +spring.jta.narayana.recovery-jms-user= # JMS username to be used by the recovery manager. spring.jta.narayana.recovery-modules= # Comma-separated list of recovery modules. spring.jta.narayana.transaction-manager-id=1 # Unique transaction manager id. spring.jta.narayana.xa-resource-orphan-filters= # Comma-separated list of orphan filters. # EMBEDDED MONGODB (EmbeddedMongoProperties) -spring.mongodb.embedded.features=SYNC_DELAY # Comma-separated list of features to enable. +spring.mongodb.embedded.features=sync_delay # Comma-separated list of features to enable. spring.mongodb.embedded.storage.database-dir= # Directory used for data storage. -spring.mongodb.embedded.storage.oplog-size= # Maximum size of the oplog in megabytes. +spring.mongodb.embedded.storage.oplog-size= # Maximum size of the oplog, in megabytes. spring.mongodb.embedded.storage.repl-set-name= # Name of the replica set. -spring.mongodb.embedded.version=2.6.10 # Version of Mongo to use. +spring.mongodb.embedded.version=3.2.2 # Version of Mongo to use. # REDIS (RedisProperties) spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster. spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from. spring.redis.database=0 # Database index used by the connection factory. -spring.redis.url= # Connection URL, will override host, port and password (user will be ignored), e.g. redis://user:password@example.com:6379 +spring.redis.url= # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379 spring.redis.host=localhost # Redis server host. -spring.redis.jedis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. -spring.redis.jedis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. -spring.redis.jedis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. +spring.redis.jedis.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. +spring.redis.jedis.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. +spring.redis.jedis.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. spring.redis.jedis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive. -spring.redis.lettuce.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. -spring.redis.lettuce.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. -spring.redis.lettuce.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. +spring.redis.lettuce.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. +spring.redis.lettuce.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. +spring.redis.lettuce.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. spring.redis.lettuce.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive. -spring.redis.lettuce.shutdown-timeout=100 # Shutdown timeout in milliseconds. +spring.redis.lettuce.shutdown-timeout=100ms # Shutdown timeout. spring.redis.password= # Login password of the redis server. spring.redis.port=6379 # Redis server port. -spring.redis.sentinel.master= # Name of Redis server. -spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs. -spring.redis.ssl=false # Enable SSL support. -spring.redis.timeout=0 # Connection timeout in milliseconds. +spring.redis.sentinel.master= # Name of the Redis server. +spring.redis.sentinel.nodes= # Comma-separated list of "host:port" pairs. +spring.redis.ssl=false # Whether to enable SSL support. +spring.redis.timeout= # Connection timeout. # TRANSACTION (TransactionProperties) -spring.transaction.default-timeout= # Default transaction timeout in seconds. -spring.transaction.rollback-on-commit-failure= # Perform the rollback on commit failures. +spring.transaction.default-timeout= # Default transaction timeout. If a duration suffix is not specified, seconds will be used. +spring.transaction.rollback-on-commit-failure= # Whether to roll back on commit failures. @@ -896,25 +917,34 @@ spring.transaction.rollback-on-commit-failure= # Perform the rollback on commit # ---------------------------------------- # ACTIVEMQ (ActiveMQProperties) -spring.activemq.broker-url= # URL of the ActiveMQ broker. Auto-generated by default. For instance `tcp://localhost:61616` -spring.activemq.in-memory=true # Specify if the default broker URL should be in memory. Ignored if an explicit broker has been specified. +spring.activemq.broker-url= # URL of the ActiveMQ broker. Auto-generated by default. +spring.activemq.close-timeout=15s # Time to wait before considering a close complete. +spring.activemq.in-memory=true # Whether the default broker URL should be in memory. Ignored if an explicit broker has been specified. +spring.activemq.non-blocking-redelivery=false # Whether to stop message delivery before re-delivering messages from a rolled back transaction. This implies that message order is not preserved when this is enabled. spring.activemq.password= # Login password of the broker. +spring.activemq.send-timeout=0ms # Time to wait on message sends for a response. Set it to 0 to wait forever. spring.activemq.user= # Login user of the broker. -spring.activemq.packages.trust-all=false # Trust all packages. +spring.activemq.packages.trust-all= # Whether to trust all packages. spring.activemq.packages.trusted= # Comma-separated list of specific packages to trust (when not trusting all packages). -spring.activemq.pool.configuration.*= # See PooledConnectionFactory. -spring.activemq.pool.enabled=false # Whether a PooledConnectionFactory should be created instead of a regular ConnectionFactory. -spring.activemq.pool.expiry-timeout=0 # Connection expiration timeout in milliseconds. -spring.activemq.pool.idle-timeout=30000 # Connection idle timeout in milliseconds. +spring.activemq.pool.block-if-full=true # Whether to block when a connection is requested and the pool is full. Set it to false to throw a "JMSException" instead. +spring.activemq.pool.block-if-full-timeout=-1ms # Blocking period before throwing an exception if the pool is still full. +spring.activemq.pool.create-connection-on-startup=true # Whether to create a connection on startup. Can be used to warm up the pool on startup. +spring.activemq.pool.enabled=false # Whether a PooledConnectionFactory should be created, instead of a regular ConnectionFactory. +spring.activemq.pool.expiry-timeout=0ms # Connection expiration timeout. +spring.activemq.pool.idle-timeout=30s # Connection idle timeout. spring.activemq.pool.max-connections=1 # Maximum number of pooled connections. +spring.activemq.pool.maximum-active-session-per-connection=500 # Maximum number of active sessions per connection. +spring.activemq.pool.reconnect-on-exception=true # Reset the connection when a "JMSException" occurs. +spring.activemq.pool.time-between-expiration-check=-1ms # Time to sleep between runs of the idle connection eviction thread. When negative, no idle connection eviction thread runs. +spring.activemq.pool.use-anonymous-producers=true # Whether to use only one anonymous "MessageProducer" instance. Set it to false to create one "MessageProducer" every time one is required. # ARTEMIS (ArtemisProperties) spring.artemis.embedded.cluster-password= # Cluster password. Randomly generated on startup by default. spring.artemis.embedded.data-directory= # Journal file directory. Not necessary if persistence is turned off. -spring.artemis.embedded.enabled=true # Enable embedded mode if the Artemis server APIs are available. -spring.artemis.embedded.persistent=false # Enable persistent store. +spring.artemis.embedded.enabled=true # Whether to enable embedded mode if the Artemis server APIs are available. +spring.artemis.embedded.persistent=false # Whether to enable persistent store. spring.artemis.embedded.queues= # Comma-separated list of queues to create on startup. -spring.artemis.embedded.server-id= # Server id. By default, an auto-incremented counter is used. +spring.artemis.embedded.server-id= # Server ID. By default, an auto-incremented counter is used. spring.artemis.embedded.topics= # Comma-separated list of topics to create on startup. spring.artemis.host=localhost # Artemis broker host. spring.artemis.mode= # Artemis deployment mode, auto-detected by default. @@ -923,14 +953,14 @@ spring.artemis.port=61616 # Artemis broker port. spring.artemis.user= # Login user of the broker. # SPRING BATCH (BatchProperties) -spring.batch.initializer.enabled= # Create the required batch tables on startup if necessary. Enabled automatically if no custom table prefix is set or if a custom schema is configured. +spring.batch.initialize-schema=embedded # Database schema initialization mode. spring.batch.job.enabled=true # Execute all Spring Batch jobs in the context on startup. -spring.batch.job.names= # Comma-separated list of job names to execute on startup (For instance `job1,job2`). By default, all Jobs found in the context are executed. +spring.batch.job.names= # Comma-separated list of job names to execute on startup (for instance, `job1,job2`). By default, all Jobs found in the context are executed. spring.batch.schema=classpath:org/springframework/batch/core/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. spring.batch.table-prefix= # Table prefix for all the batch meta-data tables. # SPRING INTEGRATION (IntegrationProperties) -spring.integration.jdbc.initializer.enabled=false # Create the required integration tables on startup. +spring.integration.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.integration.jdbc.schema=classpath:org/springframework/integration/jdbc/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. # JMS (JmsProperties) @@ -939,29 +969,38 @@ spring.jms.listener.acknowledge-mode= # Acknowledge mode of the container. By de spring.jms.listener.auto-startup=true # Start the container automatically on startup. spring.jms.listener.concurrency= # Minimum number of concurrent consumers. spring.jms.listener.max-concurrency= # Maximum number of concurrent consumers. -spring.jms.pub-sub-domain=false # Specify if the default destination type is topic. -spring.jms.template.default-destination= # Default destination to use on send/receive operations that do not have a destination parameter. -spring.jms.template.delivery-delay= # Delivery delay to use for send calls in milliseconds. -spring.jms.template.delivery-mode= # Delivery mode. Enable QoS when set. -spring.jms.template.priority= # Priority of a message when sending. Enable QoS when set. -spring.jms.template.qos-enabled= # Enable explicit QoS when sending a message. -spring.jms.template.receive-timeout= # Timeout to use for receive calls in milliseconds. -spring.jms.template.time-to-live= # Time-to-live of a message when sending in milliseconds. Enable QoS when set. +spring.jms.pub-sub-domain=false # Whether the default destination type is topic. +spring.jms.template.default-destination= # Default destination to use on send and receive operations that do not have a destination parameter. +spring.jms.template.delivery-delay= # Delivery delay to use for send calls. +spring.jms.template.delivery-mode= # Delivery mode. Enables QoS (Quality of Service) when set. +spring.jms.template.priority= # Priority of a message when sending. Enables QoS (Quality of Service) when set. +spring.jms.template.qos-enabled= # Whether to enable explicit QoS (Quality of Service) when sending a message. +spring.jms.template.receive-timeout= # Timeout to use for receive calls. +spring.jms.template.time-to-live= # Time-to-live of a message when sending. Enables QoS (Quality of Service) when set. # APACHE KAFKA (KafkaProperties) +spring.kafka.admin.client-id= # ID to pass to the server when making requests. Used for server-side logging. +spring.kafka.admin.fail-fast=false # Whether to fail fast if the broker is not available on startup. +spring.kafka.admin.properties.*= # Additional admin-specific properties used to configure the client. +spring.kafka.admin.ssl.key-password= # Password of the private key in the key store file. +spring.kafka.admin.ssl.keystore-location= # Location of the key store file. +spring.kafka.admin.ssl.keystore-password= # Store password for the key store file. +spring.kafka.admin.ssl.truststore-location= # Location of the trust store file. +spring.kafka.admin.ssl.truststore-password= # Store password for the trust store file. spring.kafka.bootstrap-servers= # Comma-delimited list of host:port pairs to use for establishing the initial connection to the Kafka cluster. -spring.kafka.client-id= # Id to pass to the server when making requests; used for server-side logging. -spring.kafka.consumer.auto-commit-interval= # Frequency in milliseconds that the consumer offsets are auto-committed to Kafka if 'enable.auto.commit' true. -spring.kafka.consumer.auto-offset-reset= # What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server. +spring.kafka.client-id= # ID to pass to the server when making requests. Used for server-side logging. +spring.kafka.consumer.auto-commit-interval= # Frequency with which the consumer offsets are auto-committed to Kafka if 'enable.auto.commit' is set to true. +spring.kafka.consumer.auto-offset-reset= # What to do when there is no initial offset in Kafka or if the current offset no longer exists on the server. spring.kafka.consumer.bootstrap-servers= # Comma-delimited list of host:port pairs to use for establishing the initial connection to the Kafka cluster. -spring.kafka.consumer.client-id= # Id to pass to the server when making requests; used for server-side logging. -spring.kafka.consumer.enable-auto-commit= # If true the consumer's offset will be periodically committed in the background. -spring.kafka.consumer.fetch-max-wait= # Maximum amount of time in milliseconds the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by "fetch.min.bytes". -spring.kafka.consumer.fetch-min-size= # Minimum amount of data the server should return for a fetch request in bytes. -spring.kafka.consumer.group-id= # Unique string that identifies the consumer group this consumer belongs to. -spring.kafka.consumer.heartbeat-interval= # Expected time in milliseconds between heartbeats to the consumer coordinator. +spring.kafka.consumer.client-id= # ID to pass to the server when making requests. Used for server-side logging. +spring.kafka.consumer.enable-auto-commit= # Whether the consumer's offset is periodically committed in the background. +spring.kafka.consumer.fetch-max-wait= # Maximum amount of time the server blocks before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by "fetch.min.bytes". +spring.kafka.consumer.fetch-min-size= # Minimum amount of data, in bytes, the server should return for a fetch request. +spring.kafka.consumer.group-id= # Unique string that identifies the consumer group to which this consumer belongs. +spring.kafka.consumer.heartbeat-interval= # Expected time between heartbeats to the consumer coordinator. spring.kafka.consumer.key-deserializer= # Deserializer class for keys. spring.kafka.consumer.max-poll-records= # Maximum number of records returned in a single call to poll(). +spring.kafka.consumer.properties.*= # Additional consumer-specific properties used to configure the client. spring.kafka.consumer.ssl.key-password= # Password of the private key in the key store file. spring.kafka.consumer.ssl.keystore-location= # Location of the key store file. spring.kafka.consumer.ssl.keystore-password= # Store password for the key store file. @@ -969,87 +1008,104 @@ spring.kafka.consumer.ssl.truststore-location= # Location of the trust store fil spring.kafka.consumer.ssl.truststore-password= # Store password for the trust store file. spring.kafka.consumer.value-deserializer= # Deserializer class for values. spring.kafka.jaas.control-flag=required # Control flag for login configuration. -spring.kafka.jaas.enabled= # Enable JAAS configuration. +spring.kafka.jaas.enabled=false # Whether to enable JAAS configuration. spring.kafka.jaas.login-module=com.sun.security.auth.module.Krb5LoginModule # Login module. spring.kafka.jaas.options= # Additional JAAS options. spring.kafka.listener.ack-count= # Number of records between offset commits when ackMode is "COUNT" or "COUNT_TIME". -spring.kafka.listener.ack-mode= # Listener AckMode; see the spring-kafka documentation. -spring.kafka.listener.ack-time= # Time in milliseconds between offset commits when ackMode is "TIME" or "COUNT_TIME". +spring.kafka.listener.ack-mode= # Listener AckMode. See the spring-kafka documentation. +spring.kafka.listener.ack-time= # Time between offset commits when ackMode is "TIME" or "COUNT_TIME". +spring.kafka.listener.client-id= # Prefix for the listener's consumer client.id property. spring.kafka.listener.concurrency= # Number of threads to run in the listener containers. -spring.kafka.listener.poll-timeout= # Timeout in milliseconds to use when polling the consumer. +spring.kafka.listener.idle-event-interval= # Time between publishing idle consumer events (no data received). +spring.kafka.listener.log-container-config= # Whether to log the container configuration during initialization (INFO level). +spring.kafka.listener.monitor-interval= # Time between checks for non-responsive consumers. If a duration suffix is not specified, seconds will be used. +spring.kafka.listener.no-poll-threshold= # Multiplier applied to "pollTimeout" to determine if a consumer is non-responsive. +spring.kafka.listener.poll-timeout= # Timeout to use when polling the consumer. spring.kafka.listener.type=single # Listener type. spring.kafka.producer.acks= # Number of acknowledgments the producer requires the leader to have received before considering a request complete. spring.kafka.producer.batch-size= # Number of records to batch before sending. spring.kafka.producer.bootstrap-servers= # Comma-delimited list of host:port pairs to use for establishing the initial connection to the Kafka cluster. spring.kafka.producer.buffer-memory= # Total bytes of memory the producer can use to buffer records waiting to be sent to the server. -spring.kafka.producer.client-id= # Id to pass to the server when making requests; used for server-side logging. +spring.kafka.producer.client-id= # ID to pass to the server when making requests. Used for server-side logging. spring.kafka.producer.compression-type= # Compression type for all data generated by the producer. spring.kafka.producer.key-serializer= # Serializer class for keys. +spring.kafka.producer.properties.*= # Additional producer-specific properties used to configure the client. spring.kafka.producer.retries= # When greater than zero, enables retrying of failed sends. spring.kafka.producer.ssl.key-password= # Password of the private key in the key store file. spring.kafka.producer.ssl.keystore-location= # Location of the key store file. spring.kafka.producer.ssl.keystore-password= # Store password for the key store file. spring.kafka.producer.ssl.truststore-location= # Location of the trust store file. spring.kafka.producer.ssl.truststore-password= # Store password for the trust store file. +spring.kafka.producer.transaction-id-prefix= # When non empty, enables transaction support for producer. spring.kafka.producer.value-serializer= # Serializer class for values. -spring.kafka.properties.*= # Additional properties used to configure the client. +spring.kafka.properties.*= # Additional properties, common to producers and consumers, used to configure the client. spring.kafka.ssl.key-password= # Password of the private key in the key store file. spring.kafka.ssl.keystore-location= # Location of the key store file. spring.kafka.ssl.keystore-password= # Store password for the key store file. spring.kafka.ssl.truststore-location= # Location of the trust store file. spring.kafka.ssl.truststore-password= # Store password for the trust store file. -spring.kafka.template.default-topic= # Default topic to which messages will be sent. +spring.kafka.template.default-topic= # Default topic to which messages are sent. # RABBIT (RabbitProperties) spring.rabbitmq.addresses= # Comma-separated list of addresses to which the client should connect. -spring.rabbitmq.cache.channel.checkout-timeout= # Number of milliseconds to wait to obtain a channel if the cache size has been reached. +spring.rabbitmq.cache.channel.checkout-timeout= # Duration to wait to obtain a channel if the cache size has been reached. spring.rabbitmq.cache.channel.size= # Number of channels to retain in the cache. spring.rabbitmq.cache.connection.mode=channel # Connection factory cache mode. spring.rabbitmq.cache.connection.size= # Number of connections to cache. -spring.rabbitmq.connection-timeout= # Connection timeout, in milliseconds; zero for infinite. -spring.rabbitmq.dynamic=true # Create an AmqpAdmin bean. +spring.rabbitmq.connection-timeout= # Connection timeout. Set it to zero to wait forever. +spring.rabbitmq.dynamic=true # Whether to create an AmqpAdmin bean. spring.rabbitmq.host=localhost # RabbitMQ host. spring.rabbitmq.listener.direct.acknowledge-mode= # Acknowledge mode of container. -spring.rabbitmq.listener.direct.auto-startup=true # Start the container automatically on startup. +spring.rabbitmq.listener.direct.auto-startup=true # Whether to start the container automatically on startup. spring.rabbitmq.listener.direct.consumers-per-queue= # Number of consumers per queue. -spring.rabbitmq.listener.direct.default-requeue-rejected= # Whether rejected deliveries are requeued by default; default true. -spring.rabbitmq.listener.direct.idle-event-interval= # How often idle container events should be published in milliseconds. +spring.rabbitmq.listener.direct.default-requeue-rejected= # Whether rejected deliveries are re-queued by default. +spring.rabbitmq.listener.direct.idle-event-interval= # How often idle container events should be published. spring.rabbitmq.listener.direct.prefetch= # Number of messages to be handled in a single request. It should be greater than or equal to the transaction size (if used). +spring.rabbitmq.listener.direct.retry.enabled=false # Whether publishing retries are enabled. +spring.rabbitmq.listener.direct.retry.initial-interval=1000ms # Duration between the first and second attempt to deliver a message. +spring.rabbitmq.listener.direct.retry.max-attempts=3 # Maximum number of attempts to deliver a message. +spring.rabbitmq.listener.direct.retry.max-interval=10000ms # Maximum duration between attempts. +spring.rabbitmq.listener.direct.retry.multiplier=1 # Multiplier to apply to the previous retry interval. +spring.rabbitmq.listener.direct.retry.stateless=true # Whether retries are stateless or stateful. spring.rabbitmq.listener.simple.acknowledge-mode= # Acknowledge mode of container. -spring.rabbitmq.listener.simple.auto-startup=true # Start the container automatically on startup. +spring.rabbitmq.listener.simple.auto-startup=true # Whether to start the container automatically on startup. spring.rabbitmq.listener.simple.concurrency= # Minimum number of listener invoker threads. -spring.rabbitmq.listener.simple.default-requeue-rejected= # Whether or not to requeue delivery failures. -spring.rabbitmq.listener.simple.idle-event-interval= # How often idle container events should be published in milliseconds. -spring.rabbitmq.listener.simple.max-concurrency= # Maximum number of listener invoker. +spring.rabbitmq.listener.simple.default-requeue-rejected= # Whether rejected deliveries are re-queued by default. +spring.rabbitmq.listener.simple.idle-event-interval= # How often idle container events should be published. +spring.rabbitmq.listener.simple.max-concurrency= # Maximum number of listener invoker threads. spring.rabbitmq.listener.simple.prefetch= # Number of messages to be handled in a single request. It should be greater than or equal to the transaction size (if used). -spring.rabbitmq.listener.simple.retry.enabled=false # Whether or not publishing retries are enabled. -spring.rabbitmq.listener.simple.retry.initial-interval=1000 # Interval between the first and second attempt to deliver a message. +spring.rabbitmq.listener.simple.retry.enabled=false # Whether publishing retries are enabled. +spring.rabbitmq.listener.simple.retry.initial-interval=1000ms # Duration between the first and second attempt to deliver a message. spring.rabbitmq.listener.simple.retry.max-attempts=3 # Maximum number of attempts to deliver a message. -spring.rabbitmq.listener.simple.retry.max-interval=10000 # Maximum interval between attempts. -spring.rabbitmq.listener.simple.retry.multiplier=1.0 # A multiplier to apply to the previous delivery retry interval. -spring.rabbitmq.listener.simple.retry.stateless=true # Whether or not retry is stateless or stateful. -spring.rabbitmq.listener.simple.transaction-size= # Number of messages to be processed in a transaction; number of messages between acks. For best results it should be less than or equal to the prefetch count. +spring.rabbitmq.listener.simple.retry.max-interval=10000ms # Maximum duration between attempts. +spring.rabbitmq.listener.simple.retry.multiplier=1 # Multiplier to apply to the previous retry interval. +spring.rabbitmq.listener.simple.retry.stateless=true # Whether retries are stateless or stateful. +spring.rabbitmq.listener.simple.transaction-size= # Number of messages to be processed in a transaction. That is, the number of messages between acks. For best results, it should be less than or equal to the prefetch count. spring.rabbitmq.listener.type=simple # Listener container type. -spring.rabbitmq.password= # Login to authenticate against the broker. +spring.rabbitmq.password=guest # Login to authenticate against the broker. spring.rabbitmq.port=5672 # RabbitMQ port. -spring.rabbitmq.publisher-confirms=false # Enable publisher confirms. -spring.rabbitmq.publisher-returns=false # Enable publisher returns. -spring.rabbitmq.requested-heartbeat= # Requested heartbeat timeout, in seconds; zero for none. -spring.rabbitmq.ssl.enabled=false # Enable SSL support. +spring.rabbitmq.publisher-confirms=false # Whether to enable publisher confirms. +spring.rabbitmq.publisher-returns=false # Whether to enable publisher returns. +spring.rabbitmq.requested-heartbeat= # Requested heartbeat timeout; zero for none. If a duration suffix is not specified, seconds will be used. +spring.rabbitmq.ssl.enabled=false # Whether to enable SSL support. spring.rabbitmq.ssl.key-store= # Path to the key store that holds the SSL certificate. spring.rabbitmq.ssl.key-store-password= # Password used to access the key store. +spring.rabbitmq.ssl.key-store-type=PKCS12 # Key store type. spring.rabbitmq.ssl.trust-store= # Trust store that holds SSL certificates. spring.rabbitmq.ssl.trust-store-password= # Password used to access the trust store. -spring.rabbitmq.ssl.algorithm= # SSL algorithm to use. By default configure by the rabbit client library. -spring.rabbitmq.template.mandatory=false # Enable mandatory messages. -spring.rabbitmq.template.receive-timeout=0 # Timeout for `receive()` methods. -spring.rabbitmq.template.reply-timeout=5000 # Timeout for `sendAndReceive()` methods. -spring.rabbitmq.template.retry.enabled=false # Set to true to enable retries in the `RabbitTemplate`. -spring.rabbitmq.template.retry.initial-interval=1000 # Interval between the first and second attempt to publish a message. -spring.rabbitmq.template.retry.max-attempts=3 # Maximum number of attempts to publish a message. -spring.rabbitmq.template.retry.max-interval=10000 # Maximum number of attempts to publish a message. -spring.rabbitmq.template.retry.multiplier=1.0 # A multiplier to apply to the previous publishing retry interval. -spring.rabbitmq.username= # Login user to authenticate to the broker. +spring.rabbitmq.ssl.trust-store-type=JKS # Trust store type. +spring.rabbitmq.ssl.algorithm= # SSL algorithm to use. By default, configured by the Rabbit client library. +spring.rabbitmq.template.exchange= # Name of the default exchange to use for send operations. +spring.rabbitmq.template.mandatory= # Whether to enable mandatory messages. +spring.rabbitmq.template.receive-timeout= # Timeout for `receive()` operations. +spring.rabbitmq.template.reply-timeout= # Timeout for `sendAndReceive()` operations. +spring.rabbitmq.template.retry.enabled=false # Whether publishing retries are enabled. +spring.rabbitmq.template.retry.initial-interval=1000ms # Duration between the first and second attempt to deliver a message. +spring.rabbitmq.template.retry.max-attempts=3 # Maximum number of attempts to deliver a message. +spring.rabbitmq.template.retry.max-interval=10000ms # Maximum duration between attempts. +spring.rabbitmq.template.retry.multiplier=1 # Multiplier to apply to the previous retry interval. +spring.rabbitmq.template.routing-key= # Value of a default routing key to use for send operations. +spring.rabbitmq.username=guest # Login user to authenticate to the broker. spring.rabbitmq.virtual-host= # Virtual host to use when connecting to the broker. @@ -1057,180 +1113,292 @@ spring.rabbitmq.virtual-host= # Virtual host to use when connecting to the broke # ACTUATOR PROPERTIES # ---------------------------------------- -# ENDPOINTS (AbstractEndpoint subclasses) -endpoints.enabled=true # Enable endpoints. -endpoints.sensitive= # Default endpoint sensitive setting. -endpoints.actuator.enabled=true # Enable the endpoint. -endpoints.actuator.path= # Endpoint URL path. -endpoints.actuator.sensitive=false # Enable security on the endpoint. -endpoints.auditevents.enabled= # Enable the endpoint. -endpoints.auditevents.path= # Endpoint path. -endpoints.auditevents.sensitive=false # Enable security on the endpoint. -endpoints.autoconfig.enabled= # Enable the endpoint. -endpoints.autoconfig.id= # Endpoint identifier. -endpoints.autoconfig.path= # Endpoint path. -endpoints.autoconfig.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.beans.enabled= # Enable the endpoint. -endpoints.beans.id= # Endpoint identifier. -endpoints.beans.path= # Endpoint path. -endpoints.beans.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.configprops.enabled= # Enable the endpoint. -endpoints.configprops.id= # Endpoint identifier. -endpoints.configprops.keys-to-sanitize=password,secret,key,token,.*credentials.*,vcap_services # Keys that should be sanitized. Keys can be simple strings that the property ends with or regex expressions. -endpoints.configprops.path= # Endpoint path. -endpoints.configprops.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.docs.curies.enabled=false # Enable the curie generation. -endpoints.docs.enabled=true # Enable actuator docs endpoint. -endpoints.docs.path=/docs # -endpoints.docs.sensitive=false # -endpoints.dump.enabled= # Enable the endpoint. -endpoints.dump.id= # Endpoint identifier. -endpoints.dump.path= # Endpoint path. -endpoints.dump.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.env.enabled= # Enable the endpoint. -endpoints.env.id= # Endpoint identifier. -endpoints.env.keys-to-sanitize=password,secret,key,token,.*credentials.*,vcap_services # Keys that should be sanitized. Keys can be simple strings that the property ends with or regex expressions. -endpoints.env.path= # Endpoint path. -endpoints.env.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.flyway.enabled= # Enable the endpoint. -endpoints.flyway.id= # Endpoint identifier. -endpoints.flyway.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.health.enabled= # Enable the endpoint. -endpoints.health.id= # Endpoint identifier. -endpoints.health.mapping.*= # Mapping of health statuses to HttpStatus codes. By default, registered health statuses map to sensible defaults (i.e. UP maps to 200). -endpoints.health.path= # Endpoint path. -endpoints.health.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.health.time-to-live=1000 # Time to live for cached result, in milliseconds. -endpoints.heapdump.enabled= # Enable the endpoint. -endpoints.heapdump.path= # Endpoint path. -endpoints.heapdump.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.hypermedia.enabled=false # Enable hypermedia support for endpoints. -endpoints.info.enabled= # Enable the endpoint. -endpoints.info.id= # Endpoint identifier. -endpoints.info.path= # Endpoint path. -endpoints.info.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.jolokia.enabled=true # Enable Jolokia endpoint. -endpoints.jolokia.path=/jolokia # Endpoint URL path. -endpoints.jolokia.sensitive=true # Enable security on the endpoint. -endpoints.liquibase.enabled= # Enable the endpoint. -endpoints.liquibase.id= # Endpoint identifier. -endpoints.liquibase.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.logfile.enabled=true # Enable the endpoint. -endpoints.logfile.external-file= # External Logfile to be accessed. -endpoints.logfile.path=/logfile # Endpoint URL path. -endpoints.logfile.sensitive=true # Enable security on the endpoint. -endpoints.loggers.enabled=true # Enable the endpoint. -endpoints.loggers.id= # Endpoint identifier. -endpoints.loggers.path=/logfile # Endpoint path. -endpoints.loggers.sensitive=true # Mark if the endpoint exposes sensitive information. -endpoints.mappings.enabled= # Enable the endpoint. -endpoints.mappings.id= # Endpoint identifier. -endpoints.mappings.path= # Endpoint path. -endpoints.mappings.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.metrics.enabled= # Enable the endpoint. -endpoints.metrics.filter.enabled=true # Enable the metrics servlet filter. -endpoints.metrics.filter.gauge-submissions=merged # Http filter gauge submissions (merged, per-http-method) -endpoints.metrics.filter.counter-submissions=merged # Http filter counter submissions (merged, per-http-method) -endpoints.metrics.id= # Endpoint identifier. -endpoints.metrics.path= # Endpoint path. -endpoints.metrics.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.shutdown.enabled= # Enable the endpoint. -endpoints.shutdown.id= # Endpoint identifier. -endpoints.shutdown.path= # Endpoint path. -endpoints.shutdown.sensitive= # Mark if the endpoint exposes sensitive information. -endpoints.trace.enabled= # Enable the endpoint. -endpoints.trace.filter.enabled=true # Enable the trace servlet filter. -endpoints.trace.id= # Endpoint identifier. -endpoints.trace.path= # Endpoint path. -endpoints.trace.sensitive= # Mark if the endpoint exposes sensitive information. - -# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties) -endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported. -endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers. -endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods. -endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled. -endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response. -endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients. - -# JMX ENDPOINT (EndpointMBeanExportProperties) -endpoints.jmx.domain= # JMX domain name. Initialized with the value of 'spring.jmx.default-domain' if set. -endpoints.jmx.enabled=true # Enable JMX export of all endpoints. -endpoints.jmx.static-names= # Additional static properties to append to all ObjectNames of MBeans representing Endpoints. -endpoints.jmx.unique-names=false # Ensure that ObjectNames are modified in case of conflict. - -# JOLOKIA (JolokiaProperties) -jolokia.config.*= # See Jolokia manual - # MANAGEMENT HTTP SERVER (ManagementServerProperties) -management.add-application-context-header=false # Add the "X-Application-Context" HTTP header in each response. -management.address= # Network address that the management endpoints should bind to. -management.context-path= # Management endpoint context-path. For instance `/actuator` -management.cloudfoundry.enabled= # Enable extended Cloud Foundry actuator endpoints -management.cloudfoundry.skip-ssl-validation= # Skip SSL verification for Cloud Foundry actuator endpoint security calls -management.port= # Management endpoint HTTP port. Uses the same port as the application by default. Configure a different port to use management-specific SSL. -management.security.enabled=true # Enable security. -management.security.roles=ACTUATOR # Comma-separated list of roles that can access the management endpoint. -management.security.sessions=stateless # Session creating policy to use (always, never, if_required, stateless). -management.ssl.ciphers= # Supported SSL ciphers. Requires a custom management.port. -management.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. Requires a custom management.port. -management.ssl.enabled= # Enable SSL support. Requires a custom management.port. -management.ssl.enabled-protocols= # Enabled SSL protocols. Requires a custom management.port. -management.ssl.key-alias= # Alias that identifies the key in the key store. Requires a custom management.port. -management.ssl.key-password= # Password used to access the key in the key store. Requires a custom management.port. -management.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file). Requires a custom management.port. -management.ssl.key-store-password= # Password used to access the key store. Requires a custom management.port. -management.ssl.key-store-provider= # Provider for the key store. Requires a custom management.port. -management.ssl.key-store-type= # Type of the key store. Requires a custom management.port. -management.ssl.protocol=TLS # SSL protocol to use. Requires a custom management.port. -management.ssl.trust-store= # Trust store that holds SSL certificates. Requires a custom management.port. -management.ssl.trust-store-password= # Password used to access the trust store. Requires a custom management.port. -management.ssl.trust-store-provider= # Provider for the trust store. Requires a custom management.port. -management.ssl.trust-store-type= # Type of the trust store. Requires a custom management.port. +management.server.add-application-context-header=false # Add the "X-Application-Context" HTTP header in each response. +management.server.address= # Network address to which the management endpoints should bind. Requires a custom management.server.port. +management.server.port= # Management endpoint HTTP port (uses the same port as the application by default). Configure a different port to use management-specific SSL. +management.server.servlet.context-path= # Management endpoint context-path (for instance, `/management`). Requires a custom management.server.port. +management.server.ssl.ciphers= # Supported SSL ciphers. Requires a custom management.port. +management.server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. Requires a custom management.server.port. +management.server.ssl.enabled= # Whether to enable SSL support. Requires a custom management.server.port. +management.server.ssl.enabled-protocols= # Enabled SSL protocols. Requires a custom management.server.port. +management.server.ssl.key-alias= # Alias that identifies the key in the key store. Requires a custom management.server.port. +management.server.ssl.key-password= # Password used to access the key in the key store. Requires a custom management.server.port. +management.server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file). Requires a custom management.server.port. +management.server.ssl.key-store-password= # Password used to access the key store. Requires a custom management.server.port. +management.server.ssl.key-store-provider= # Provider for the key store. Requires a custom management.server.port. +management.server.ssl.key-store-type= # Type of the key store. Requires a custom management.server.port. +management.server.ssl.protocol=TLS # SSL protocol to use. Requires a custom management.server.port. +management.server.ssl.trust-store= # Trust store that holds SSL certificates. Requires a custom management.server.port. +management.server.ssl.trust-store-password= # Password used to access the trust store. Requires a custom management.server.port. +management.server.ssl.trust-store-provider= # Provider for the trust store. Requires a custom management.server.port. +management.server.ssl.trust-store-type= # Type of the trust store. Requires a custom management.server.port. + +# CLOUDFOUNDRY +management.cloudfoundry.enabled=true # Whether to enable extended Cloud Foundry actuator endpoints. +management.cloudfoundry.skip-ssl-validation=false # Whether to skip SSL verification for Cloud Foundry actuator endpoint security calls. + +# ENDPOINTS GENERAL CONFIGURATION +management.endpoints.enabled-by-default= # Whether to enable or disable all endpoints by default. + +# ENDPOINTS JMX CONFIGURATION (JmxEndpointProperties) +management.endpoints.jmx.domain=org.springframework.boot # Endpoints JMX domain name. Fallback to 'spring.jmx.default-domain' if set. +management.endpoints.jmx.exposure.include=* # Endpoint IDs that should be included or '*' for all. +management.endpoints.jmx.exposure.exclude= # Endpoint IDs that should be excluded. +management.endpoints.jmx.static-names= # Additional static properties to append to all ObjectNames of MBeans representing Endpoints. +management.endpoints.jmx.unique-names=false # Whether to ensure that ObjectNames are modified in case of conflict. + +# ENDPOINTS WEB CONFIGURATION (WebEndpointProperties) +management.endpoints.web.exposure.include=health,info # Endpoint IDs that should be included or '*' for all. +management.endpoints.web.exposure.exclude= # Endpoint IDs that should be excluded. +management.endpoints.web.base-path=/actuator # Base path for Web endpoints. Relative to server.servlet.context-path or management.server.servlet.context-path if management.server.port is configured. +management.endpoints.web.path-mapping= # Mapping between endpoint IDs and the path that should expose them. + +# ENDPOINTS CORS CONFIGURATION (CorsEndpointProperties) +management.endpoints.web.cors.allow-credentials= # Whether credentials are supported. When not set, credentials are not supported. +management.endpoints.web.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers. +management.endpoints.web.cors.allowed-methods= # Comma-separated list of methods to allow. '*' allows all methods. When not set, defaults to GET. +management.endpoints.web.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled. +management.endpoints.web.cors.exposed-headers= # Comma-separated list of headers to include in a response. +management.endpoints.web.cors.max-age=1800s # How long the response from a pre-flight request can be cached by clients. If a duration suffix is not specified, seconds will be used. + +# AUDIT EVENTS ENDPOINT (AuditEventsEndpoint) +management.endpoint.auditevents.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.auditevents.enabled=true # Whether to enable the auditevents endpoint. + +# BEANS ENDPOINT (BeansEndpoint) +management.endpoint.beans.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.beans.enabled=true # Whether to enable the beans endpoint. + +# CONDITIONS REPORT ENDPOINT (ConditionsReportEndpoint) +management.endpoint.conditions.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.conditions.enabled=true # Whether to enable the conditions endpoint. + +# CONFIGURATION PROPERTIES REPORT ENDPOINT (ConfigurationPropertiesReportEndpoint, ConfigurationPropertiesReportEndpointProperties) +management.endpoint.configprops.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.configprops.enabled=true # Whether to enable the configprops endpoint. +management.endpoint.configprops.keys-to-sanitize=password,secret,key,token,.*credentials.*,vcap_services # Keys that should be sanitized. Keys can be simple strings that the property ends with or regular expressions. + +# ENVIRONMENT ENDPOINT (EnvironmentEndpoint, EnvironmentEndpointProperties) +management.endpoint.env.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.env.enabled=true # Whether to enable the env endpoint. +management.endpoint.env.keys-to-sanitize=password,secret,key,token,.*credentials.*,vcap_services # Keys that should be sanitized. Keys can be simple strings that the property ends with or regular expressions. + +# FLYWAY ENDPOINT (FlywayEndpoint) +management.endpoint.flyway.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.flyway.enabled=true # Whether to enable the flyway endpoint. + +# HEALTH ENDPOINT (HealthEndpoint, HealthEndpointProperties) +management.endpoint.health.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.health.enabled=true # Whether to enable the health endpoint. +management.endpoint.health.roles= # Roles used to determine whether or not a user is authorized to be shown details. When empty, all authenticated users are authorized. +management.endpoint.health.show-details=never # When to show full health details. + +# HEAP DUMP ENDPOINT (HeapDumpWebEndpoint) +management.endpoint.heapdump.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.heapdump.enabled=true # Whether to enable the heapdump endpoint. + +# HTTP TRACE ENDPOINT (HttpTraceEndpoint) +management.endpoint.httptrace.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.httptrace.enabled=true # Whether to enable the httptrace endpoint. + +# INFO ENDPOINT (InfoEndpoint) +info= # Arbitrary properties to add to the info endpoint. +management.endpoint.info.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.info.enabled=true # Whether to enable the info endpoint. + +# JOLOKIA ENDPOINT (JolokiaProperties) +management.endpoint.jolokia.config.*= # Jolokia settings. Refer to the documentation of Jolokia for more details. +management.endpoint.jolokia.enabled=true # Whether to enable the jolokia endpoint. + +# LIQUIBASE ENDPOINT (LiquibaseEndpoint) +management.endpoint.liquibase.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.liquibase.enabled=true # Whether to enable the liquibase endpoint. + +# LOG FILE ENDPOINT (LogFileWebEndpoint, LogFileWebEndpointProperties) +management.endpoint.logfile.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.logfile.enabled=true # Whether to enable the logfile endpoint. +management.endpoint.logfile.external-file= # External Logfile to be accessed. Can be used if the logfile is written by output redirect and not by the logging system itself. + +# LOGGERS ENDPOINT (LoggersEndpoint) +management.endpoint.loggers.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.loggers.enabled=true # Whether to enable the loggers endpoint. + +# REQUEST MAPPING ENDPOINT (MappingsEndpoint) +management.endpoint.mappings.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.mappings.enabled=true # Whether to enable the mappings endpoint. + +# METRICS ENDPOINT (MetricsEndpoint) +management.endpoint.metrics.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.metrics.enabled=true # Whether to enable the metrics endpoint. + +# PROMETHEUS ENDPOINT (PrometheusScrapeEndpoint) +management.endpoint.prometheus.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.prometheus.enabled=true # Whether to enable the prometheus endpoint. + +# SCHEDULED TASKS ENDPOINT (ScheduledTasksEndpoint) +management.endpoint.scheduledtasks.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.scheduledtasks.enabled=true # Whether to enable the scheduledtasks endpoint. + +# SESSIONS ENDPOINT (SessionsEndpoint) +management.endpoint.sessions.enabled=true # Whether to enable the sessions endpoint. + +# SHUTDOWN ENDPOINT (ShutdownEndpoint) +management.endpoint.shutdown.enabled=false # Whether to enable the shutdown endpoint. + +# THREAD DUMP ENDPOINT (ThreadDumpEndpoint) +management.endpoint.threaddump.cache.time-to-live=0ms # Maximum time that a response can be cached. +management.endpoint.threaddump.enabled=true # Whether to enable the threaddump endpoint. # HEALTH INDICATORS -management.health.db.enabled=true # Enable database health check. -management.health.cassandra.enabled=true # Enable cassandra health check. -management.health.couchbase.enabled=true # Enable couchbase health check. -management.health.defaults.enabled=true # Enable default health indicators. -management.health.diskspace.enabled=true # Enable disk space health check. +management.health.db.enabled=true # Whether to enable database health check. +management.health.cassandra.enabled=true # Whether to enable Cassandra health check. +management.health.couchbase.enabled=true # Whether to enable Couchbase health check. +management.health.defaults.enabled=true # Whether to enable default health indicators. +management.health.diskspace.enabled=true # Whether to enable disk space health check. management.health.diskspace.path= # Path used to compute the available disk space. -management.health.diskspace.threshold=0 # Minimum disk space that should be available, in bytes. -management.health.elasticsearch.enabled=true # Enable elasticsearch health check. +management.health.diskspace.threshold=0 # Minimum disk space, in bytes, that should be available. +management.health.elasticsearch.enabled=true # Whether to enable Elasticsearch health check. management.health.elasticsearch.indices= # Comma-separated index names. -management.health.elasticsearch.response-timeout=100 # The time, in milliseconds, to wait for a response from the cluster. -management.health.jms.enabled=true # Enable JMS health check. -management.health.ldap.enabled=true # Enable LDAP health check. -management.health.mail.enabled=true # Enable Mail health check. -management.health.mongo.enabled=true # Enable MongoDB health check. -management.health.rabbit.enabled=true # Enable RabbitMQ health check. -management.health.redis.enabled=true # Enable Redis health check. -management.health.solr.enabled=true # Enable Solr health check. -management.health.status.order=DOWN, OUT_OF_SERVICE, UP, UNKNOWN # Comma-separated list of health statuses in order of severity. +management.health.elasticsearch.response-timeout=100ms # Time to wait for a response from the cluster. +management.health.influxdb.enabled=true # Whether to enable InfluxDB health check. +management.health.jms.enabled=true # Whether to enable JMS health check. +management.health.ldap.enabled=true # Whether to enable LDAP health check. +management.health.mail.enabled=true # Whether to enable Mail health check. +management.health.mongo.enabled=true # Whether to enable MongoDB health check. +management.health.neo4j.enabled=true # Whether to enable Neo4j health check. +management.health.rabbit.enabled=true # Whether to enable RabbitMQ health check. +management.health.redis.enabled=true # Whether to enable Redis health check. +management.health.solr.enabled=true # Whether to enable Solr health check. +management.health.status.http-mapping= # Mapping of health statuses to HTTP status codes. By default, registered health statuses map to sensible defaults (for example, UP maps to 200). +management.health.status.order=DOWN,OUT_OF_SERVICE,UP,UNKNOWN # Comma-separated list of health statuses in order of severity. + +# HTTP TRACING (HttpTraceProperties) +management.trace.http.enabled=true # Whether to enable HTTP request-response tracing. +management.trace.http.include=request-headers,response-headers,cookies,errors # Items to be included in the trace. # INFO CONTRIBUTORS (InfoContributorProperties) -management.info.build.enabled=true # Enable build info. -management.info.defaults.enabled=true # Enable default info contributors. -management.info.env.enabled=true # Enable environment info. -management.info.git.enabled=true # Enable git info. +management.info.build.enabled=true # Whether to enable build info. +management.info.defaults.enabled=true # Whether to enable default info contributors. +management.info.env.enabled=true # Whether to enable environment info. +management.info.git.enabled=true # Whether to enable git info. management.info.git.mode=simple # Mode to use to expose git information. -# TRACING (TraceProperties) -management.trace.include=request-headers,response-headers,cookies,errors # Items to be included in the trace. - -# METRICS EXPORT (MetricExportProperties) -spring.metrics.export.aggregate.key-pattern= # Pattern that tells the aggregator what to do with the keys from the source repository. -spring.metrics.export.aggregate.prefix= # Prefix for global repository if active. -spring.metrics.export.delay-millis=5000 # Delay in milliseconds between export ticks. Metrics are exported to external sources on a schedule with this delay. -spring.metrics.export.enabled=true # Flag to enable metric export (assuming a MetricWriter is available). -spring.metrics.export.excludes= # List of patterns for metric names to exclude. Applied after the includes. -spring.metrics.export.includes= # List of patterns for metric names to include. -spring.metrics.export.redis.key=keys.spring.metrics # Key for redis repository export (if active). -spring.metrics.export.redis.prefix=spring.metrics # Prefix for redis repository if active. -spring.metrics.export.send-latest= # Flag to switch off any available optimizations based on not exporting unchanged metric values. -spring.metrics.export.statsd.host= # Host of a statsd server to receive exported metrics. -spring.metrics.export.statsd.port=8125 # Port of a statsd server to receive exported metrics. -spring.metrics.export.statsd.prefix= # Prefix for statsd exported metrics. -spring.metrics.export.triggers.*= # Specific trigger properties per MetricWriter bean name. +# METRICS +management.metrics.binders.files.enabled=true # Whether to enable files metrics. +management.metrics.binders.integration.enabled=true # Whether to enable Spring Integration metrics. +management.metrics.binders.jvm.enabled=true # Whether to enable JVM metrics. +management.metrics.binders.logback.enabled=true # Whether to enable Logback metrics. +management.metrics.binders.processor.enabled=true # Whether to enable processor metrics. +management.metrics.binders.uptime.enabled=true # Whether to enable uptime metrics. +management.metrics.distribution.percentiles-histogram.*= # Whether meter IDs starting-with the specified name should be publish percentile histograms. +management.metrics.distribution.percentiles.*= # Specific computed non-aggregable percentiles to ship to the backend for meter IDs starting-with the specified name. +management.metrics.distribution.sla.*= # Specific SLA boundaries for meter IDs starting-with the specified name. The longest match wins, the key `all` can also be used to configure all meters. +management.metrics.enable.*= # Whether meter IDs starting-with the specified name should be enabled. The longest match wins, the key `all` can also be used to configure all meters. +management.metrics.export.atlas.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. +management.metrics.export.atlas.config-refresh-frequency=10s # Frequency for refreshing config settings from the LWC service. +management.metrics.export.atlas.config-time-to-live=150s # Time to live for subscriptions from the LWC service. +management.metrics.export.atlas.config-uri=http://localhost:7101/lwc/api/v1/expressions/local-dev # URI for the Atlas LWC endpoint to retrieve current subscriptions. +management.metrics.export.atlas.connect-timeout=1s # Connection timeout for requests to this backend. +management.metrics.export.atlas.enabled=true # Whether exporting of metrics to this backend is enabled. +management.metrics.export.atlas.eval-uri=http://localhost:7101/lwc/api/v1/evaluate # URI for the Atlas LWC endpoint to evaluate the data for a subscription. +management.metrics.export.atlas.lwc-enabled=false # Whether to enable streaming to Atlas LWC. +management.metrics.export.atlas.meter-time-to-live=15m # Time to live for meters that do not have any activity. After this period the meter will be considered expired and will not get reported. +management.metrics.export.atlas.num-threads=2 # Number of threads to use with the metrics publishing scheduler. +management.metrics.export.atlas.read-timeout=10s # Read timeout for requests to this backend. +management.metrics.export.atlas.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.atlas.uri=http://localhost:7101/api/v1/publish # URI of the Atlas server. +management.metrics.export.datadog.api-key= # Datadog API key. +management.metrics.export.datadog.application-key= # Datadog application key. Not strictly required, but improves the Datadog experience by sending meter descriptions, types, and base units to Datadog. +management.metrics.export.datadog.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. +management.metrics.export.datadog.connect-timeout=1s # Connection timeout for requests to this backend. +management.metrics.export.datadog.descriptions=true # Whether to publish descriptions metadata to Datadog. Turn this off to minimize the amount of metadata sent. +management.metrics.export.datadog.enabled=true # Whether exporting of metrics to this backend is enabled. +management.metrics.export.datadog.host-tag=instance # Tag that will be mapped to "host" when shipping metrics to Datadog. +management.metrics.export.datadog.num-threads=2 # Number of threads to use with the metrics publishing scheduler. +management.metrics.export.datadog.read-timeout=10s # Read timeout for requests to this backend. +management.metrics.export.datadog.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.datadog.uri=https://app.datadoghq.com # URI to ship metrics to. If you need to publish metrics to an internal proxy en-route to Datadog, you can define the location of the proxy with this. +management.metrics.export.ganglia.addressing-mode=multicast # UDP addressing mode, either unicast or multicast. +management.metrics.export.ganglia.duration-units=milliseconds # Base time unit used to report durations. +management.metrics.export.ganglia.enabled=true # Whether exporting of metrics to Ganglia is enabled. +management.metrics.export.ganglia.host=localhost # Host of the Ganglia server to receive exported metrics. +management.metrics.export.ganglia.port=8649 # Port of the Ganglia server to receive exported metrics. +management.metrics.export.ganglia.protocol-version=3.1 # Ganglia protocol version. Must be either 3.1 or 3.0. +management.metrics.export.ganglia.rate-units=seconds # Base time unit used to report rates. +management.metrics.export.ganglia.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.ganglia.time-to-live=1 # Time to live for metrics on Ganglia. Set the multi-cast Time-To-Live to be one greater than the number of hops (routers) between the hosts. +management.metrics.export.graphite.duration-units=milliseconds # Base time unit used to report durations. +management.metrics.export.graphite.enabled=true # Whether exporting of metrics to Graphite is enabled. +management.metrics.export.graphite.host=localhost # Host of the Graphite server to receive exported metrics. +management.metrics.export.graphite.port=2004 # Port of the Graphite server to receive exported metrics. +management.metrics.export.graphite.protocol=pickled # Protocol to use while shipping data to Graphite. +management.metrics.export.graphite.rate-units=seconds # Base time unit used to report rates. +management.metrics.export.graphite.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.graphite.tags-as-prefix= # For the default naming convention, turn the specified tag keys into part of the metric prefix. +management.metrics.export.influx.auto-create-db=true # Whether to create the Influx database if it does not exist before attempting to publish metrics to it. +management.metrics.export.influx.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. +management.metrics.export.influx.compressed=true # Whether to enable GZIP compression of metrics batches published to Influx. +management.metrics.export.influx.connect-timeout=1s # Connection timeout for requests to this backend. +management.metrics.export.influx.consistency=one # Write consistency for each point. +management.metrics.export.influx.db=mydb # Tag that will be mapped to "host" when shipping metrics to Influx. +management.metrics.export.influx.enabled=true # Whether exporting of metrics to this backend is enabled. +management.metrics.export.influx.num-threads=2 # Number of threads to use with the metrics publishing scheduler. +management.metrics.export.influx.password= # Login password of the Influx server. +management.metrics.export.influx.read-timeout=10s # Read timeout for requests to this backend. +management.metrics.export.influx.retention-policy= # Retention policy to use (Influx writes to the DEFAULT retention policy if one is not specified). +management.metrics.export.influx.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.influx.uri=http://localhost:8086 # URI of the Influx server. +management.metrics.export.influx.user-name= # Login user of the Influx server. +management.metrics.export.jmx.enabled=true # Whether exporting of metrics to JMX is enabled. +management.metrics.export.jmx.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.newrelic.account-id= # New Relic account ID. +management.metrics.export.newrelic.api-key= # New Relic API key. +management.metrics.export.newrelic.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. +management.metrics.export.newrelic.connect-timeout=1s # Connection timeout for requests to this backend. +management.metrics.export.newrelic.enabled=true # Whether exporting of metrics to this backend is enabled. +management.metrics.export.newrelic.num-threads=2 # Number of threads to use with the metrics publishing scheduler. +management.metrics.export.newrelic.read-timeout=10s # Read timeout for requests to this backend. +management.metrics.export.newrelic.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.newrelic.uri=https://insights-collector.newrelic.com # URI to ship metrics to. +management.metrics.export.prometheus.descriptions=true # Whether to enable publishing descriptions as part of the scrape payload to Prometheus. Turn this off to minimize the amount of data sent on each scrape. +management.metrics.export.prometheus.enabled=true # Whether exporting of metrics to Prometheus is enabled. +management.metrics.export.prometheus.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.signalfx.access-token= # SignalFX access token. +management.metrics.export.signalfx.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. +management.metrics.export.signalfx.connect-timeout=1s # Connection timeout for requests to this backend. +management.metrics.export.signalfx.enabled=true # Whether exporting of metrics to this backend is enabled. +management.metrics.export.signalfx.num-threads=2 # Number of threads to use with the metrics publishing scheduler. +management.metrics.export.signalfx.read-timeout=10s # Read timeout for requests to this backend. +management.metrics.export.signalfx.source= # Uniquely identifies the app instance that is publishing metrics to SignalFx. Defaults to the local host name. +management.metrics.export.signalfx.step=10s # Step size (i.e. reporting frequency) to use. +management.metrics.export.signalfx.uri=https://ingest.signalfx.com # URI to ship metrics to. +management.metrics.export.simple.enabled=true # Whether, in the absence of any other exporter, exporting of metrics to an in-memory backend is enabled. +management.metrics.export.simple.mode=cumulative # Counting mode. +management.metrics.export.simple.step=1m # Step size (i.e. reporting frequency) to use. +management.metrics.export.statsd.enabled=true # Whether exporting of metrics to StatsD is enabled. +management.metrics.export.statsd.flavor=datadog # StatsD line protocol to use. +management.metrics.export.statsd.host=localhost # Host of the StatsD server to receive exported metrics. +management.metrics.export.statsd.max-packet-length=1400 # Total length of a single payload should be kept within your network's MTU. +management.metrics.export.statsd.polling-frequency=10s # How often gauges will be polled. When a gauge is polled, its value is recalculated and if the value has changed (or publishUnchangedMeters is true), it is sent to the StatsD server. +management.metrics.export.statsd.port=8125 # Port of the StatsD server to receive exported metrics. +management.metrics.export.statsd.publish-unchanged-meters=true # Whether to send unchanged meters to the StatsD server. +management.metrics.export.statsd.queue-size=2147483647 # Maximum size of the queue of items waiting to be sent to the StatsD server. +management.metrics.export.wavefront.api-token= # API token used when publishing metrics directly to the Wavefront API host. +management.metrics.export.wavefront.batch-size=10000 # Number of measurements per request to use for this backend. If more measurements are found, then multiple requests will be made. +management.metrics.export.wavefront.connect-timeout=1s # Connection timeout for requests to this backend. +management.metrics.export.wavefront.enabled=true # Whether exporting of metrics to this backend is enabled. +management.metrics.export.wavefront.global-prefix= # Global prefix to separate metrics originating from this app's white box instrumentation from those originating from other Wavefront integrations when viewed in the Wavefront UI. +management.metrics.export.wavefront.num-threads=2 # Number of threads to use with the metrics publishing scheduler. +management.metrics.export.wavefront.read-timeout=10s # Read timeout for requests to this backend. +management.metrics.export.wavefront.source= # Unique identifier for the app instance that is the source of metrics being published to Wavefront. Defaults to the local host name. +management.metrics.export.wavefront.step=10s # Step size (i.e. reporting frequency) to use. +management.metrics.export.wavefront.uri=https://longboard.wavefront.com # URI to ship metrics to. +management.metrics.use-global-registry=true # Whether auto-configured MeterRegistry implementations should be bound to the global static registry on Metrics. +management.metrics.web.client.max-uri-tags=100 # Maximum number of unique URI tag values allowed. After the max number of tag values is reached, metrics with additional tag values are denied by filter. +management.metrics.web.client.requests-metric-name=http.client.requests # Name of the metric for sent requests. +management.metrics.web.server.auto-time-requests=true # Whether requests handled by Spring MVC or WebFlux should be automatically timed. +management.metrics.web.server.requests-metric-name=http.server.requests # Name of the metric for received requests. # ---------------------------------------- @@ -1238,23 +1406,22 @@ spring.metrics.export.triggers.*= # Specific trigger properties per MetricWriter # ---------------------------------------- # DEVTOOLS (DevToolsProperties) -spring.devtools.livereload.enabled=true # Enable a livereload.com compatible server. +spring.devtools.livereload.enabled=true # Whether to enable a livereload.com-compatible server. spring.devtools.livereload.port=35729 # Server port. spring.devtools.restart.additional-exclude= # Additional patterns that should be excluded from triggering a full restart. spring.devtools.restart.additional-paths= # Additional paths to watch for changes. -spring.devtools.restart.enabled=true # Enable automatic restart. -spring.devtools.restart.exclude=META-INF/maven/**,META-INF/resources/**,resources/**,static/**,public/**,templates/**,**/*Test.class,**/*Tests.class,git.properties # Patterns that should be excluded from triggering a full restart. -spring.devtools.restart.poll-interval=1000 # Amount of time (in milliseconds) to wait between polling for classpath changes. -spring.devtools.restart.quiet-period=400 # Amount of quiet time (in milliseconds) required without any classpath changes before a restart is triggered. -spring.devtools.restart.trigger-file= # Name of a specific file that when changed will trigger the restart check. If not specified any classpath file change will trigger the restart. +spring.devtools.restart.enabled=true # Whether to enable automatic restart. +spring.devtools.restart.exclude=META-INF/maven/**,META-INF/resources/**,resources/**,static/**,public/**,templates/**,**/*Test.class,**/*Tests.class,git.properties,META-INF/build-info.properties # Patterns that should be excluded from triggering a full restart. +spring.devtools.restart.log-condition-evaluation-delta=true # Whether to log the condition evaluation delta upon restart. +spring.devtools.restart.poll-interval=1s # Amount of time to wait between polling for classpath changes. +spring.devtools.restart.quiet-period=400ms # Amount of quiet time required without any classpath changes before a restart is triggered. +spring.devtools.restart.trigger-file= # Name of a specific file that, when changed, triggers the restart check. If not specified, any classpath file change triggers the restart. # REMOTE DEVTOOLS (RemoteDevToolsProperties) spring.devtools.remote.context-path=/.~~spring-boot!~ # Context path used to handle the remote connection. -spring.devtools.remote.debug.enabled=true # Enable remote debug support. -spring.devtools.remote.debug.local-port=8000 # Local remote debug server port. spring.devtools.remote.proxy.host= # The host of the proxy to use to connect to the remote application. spring.devtools.remote.proxy.port= # The port of the proxy to use to connect to the remote application. -spring.devtools.remote.restart.enabled=true # Enable remote restart. +spring.devtools.remote.restart.enabled=true # Whether to enable remote restart. spring.devtools.remote.secret= # A shared secret required to establish a connection (required to enable remote support). spring.devtools.remote.secret-header-name=X-AUTH-TOKEN # HTTP header used to transfer the shared secret. @@ -1265,4 +1432,4 @@ spring.devtools.remote.secret-header-name=X-AUTH-TOKEN # HTTP header used to tra spring.test.database.replace=any # Type of existing DataSource to replace. spring.test.mockmvc.print=default # MVC Print option. -``` \ No newline at end of file +``` diff --git a/X. Appendices/B. Configuration Metadata.md b/X. Appendices/B. Configuration Metadata.md new file mode 100644 index 00000000..ce7eee09 --- /dev/null +++ b/X. Appendices/B. Configuration Metadata.md @@ -0,0 +1,5 @@ +### 附录B. 配置元数据 + +Spring Boot jars包含元数据文件,它们提供了所有支持的配置属性详情。这些文件设计用于让IDE开发者能够为使用`application.properties`或`application.yml`文件的用户提供上下文帮助及代码完成功能。 + +主要的元数据文件是在编译器通过处理所有被`@ConfigurationProperties`注解的节点来自动生成的。尽管如此,在实现个别案例或者更加高级的使用案例时,还是可以[手写部分元数据](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#configuration-metadata-additional-metadata)。 diff --git a/X. Appendices/B. Configuration meta-data.md b/X. Appendices/B. Configuration meta-data.md deleted file mode 100644 index c5b60ced..00000000 --- a/X. Appendices/B. Configuration meta-data.md +++ /dev/null @@ -1,5 +0,0 @@ -### 附录B. 配置元数据 - -Spring Boot jars包含元数据文件,它们提供了所有支持的配置属性详情。这些文件设计用于让IDE开发者能够为使用`application.properties`或`application.yml`文件的用户提供上下文帮助及代码完成功能。 - -主要的元数据文件是在编译器通过处理所有被`@ConfigurationProperties`注解的节点来自动生成的。尽管如此,在实现个别案例或者更加高级的使用案例时,还是可以[手写部分元数据](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#configuration-metadata-additional-metadata)。 diff --git a/X. Appendices/B.1. Meta-data format.md b/X. Appendices/B.1. Meta-data format.md deleted file mode 100644 index 76273e26..00000000 --- a/X. Appendices/B.1. Meta-data format.md +++ /dev/null @@ -1,79 +0,0 @@ -### 附录B.1. 元数据格式 - -配置元数据位于jars文件中的`META-INF/spring-configuration-metadata.json`,它们使用一个具有"groups"或"properties"分类节点的简单JSON格式: -```json -{"groups": [ - { - "name": "server", - "type": "org.springframework.boot.autoconfigure.web.ServerProperties", - "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" - }, - { - "name": "spring.jpa.hibernate", - "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate", - "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties", - "sourceMethod": "getHibernate()" - } - ... -],"properties": [ - { - "name": "server.port", - "type": "java.lang.Integer", - "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" - }, - { - "name": "server.servlet.path", - "type": "java.lang.String", - "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties", - "defaultValue": "/" - }, - { - "name": "spring.jpa.hibernate.ddl-auto", - "type": "java.lang.String", - "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.", - "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate" - } - ... -],"hints": [ - { - "name": "spring.jpa.hibernate.ddl-auto", - "values": [ - { - "value": "none", - "description": "Disable DDL handling." - }, - { - "value": "validate", - "description": "Validate the schema, make no changes to the database." - }, - { - "value": "update", - "description": "Update the schema if necessary." - }, - { - "value": "create", - "description": "Create the schema and destroy previous data." - }, - { - "value": "create-drop", - "description": "Create and then destroy the schema at the end of the session." - } - ] - } -]} -``` -每个"property"是一个配置节点,用户可以使用特定的值指定它。例如,`server.port`和`server.servlet.path`可能在`application.properties`中如以下定义: -```properties -server.port=9090 -server.servlet.path=/home -``` -"groups"是高级别的节点,它们本身不指定一个值,但为properties提供一个有上下文关联的分组。例如,`server.port`和`server.servlet.path`属性是`server`组的一部分。 - -**注** 不需要每个"property"都有一个"group",一些属性可以以自己的形式存在。 - - - - - - - diff --git a/X. Appendices/B.1. Metadata Format.md b/X. Appendices/B.1. Metadata Format.md new file mode 100644 index 00000000..5b0ef804 --- /dev/null +++ b/X. Appendices/B.1. Metadata Format.md @@ -0,0 +1,79 @@ +### 附录B.1. 元数据格式 + +配置元数据位于jars文件中的`META-INF/spring-configuration-metadata.json`,它们使用一个具有"groups"或"properties"分类节点的简单JSON格式: +```json +{"groups": [ + { + "name": "server", + "type": "org.springframework.boot.autoconfigure.web.ServerProperties", + "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" + }, + { + "name": "spring.jpa.hibernate", + "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate", + "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties", + "sourceMethod": "getHibernate()" + } + ... +],"properties": [ + { + "name": "server.port", + "type": "java.lang.Integer", + "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" + }, + { + "name": "server.servlet.path", + "type": "java.lang.String", + "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties", + "defaultValue": "/" + }, + { + "name": "spring.jpa.hibernate.ddl-auto", + "type": "java.lang.String", + "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.", + "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate" + } + ... +],"hints": [ + { + "name": "spring.jpa.hibernate.ddl-auto", + "values": [ + { + "value": "none", + "description": "Disable DDL handling." + }, + { + "value": "validate", + "description": "Validate the schema, make no changes to the database." + }, + { + "value": "update", + "description": "Update the schema if necessary." + }, + { + "value": "create", + "description": "Create the schema and destroy previous data." + }, + { + "value": "create-drop", + "description": "Create and then destroy the schema at the end of the session." + } + ] + } +]} +``` +每个"property"是一个配置节点,用户可以使用特定的值指定它。例如,`server.port`和`server.servlet.path`可能在`application.properties`中如以下定义: +```properties +server.port=9090 +server.servlet.path=/home +``` +"groups"是高级别的节点,它们本身不指定一个值,但为properties提供一个有上下文关联的分组。例如,`server.port`和`server.servlet.path`属性是`server`组的一部分。 + +**注** 不需要每个"property"都有一个"group",一些属性可以以自己的形式存在。 + + + + + + + diff --git a/X. Appendices/B.1.2. Property Attributes.md b/X. Appendices/B.1.2. Property Attributes.md index 6ee08b14..81cdb135 100644 --- a/X. Appendices/B.1.2. Property Attributes.md +++ b/X. Appendices/B.1.2. Property Attributes.md @@ -1,49 +1,49 @@ -### 附录B.1.2. Property属性 - -`properties`数组中包含的JSON对象可以包含以下属性: - -|名称|类型|目的| -|----|:----|:----| -|`name`|String|property的全名,格式为小写虚线分割的形式(比如`server.servlet.path`)。该属性是强制性的| -|`type`|String|property数据类型的完整的签名。例如`java.lang.String`,但也可以是一个完整的泛型类,比如`java.util.Map`。该属性可以用来指导用户他们可以输入值的类型。为了保持一致,原生类型使用它们的包装类代替,比如`boolean`变成了`java.lang.Boolean`。注意,这个类可能是个从一个字符串转换而来的复杂类型。如果类型未知则该属性会被忽略| -|`description`|String|一个简短的组的描述,用于展示给用户。如果没有描述可用则该属性会被省略。推荐使用一个简短的段落描述,开头提供一个简要的总结,最后一行以句号(`.`)结束| -|`sourceType`|String|贡献property的来源类名。例如,如果property来自一个被`@ConfigurationProperties`注解的类,该属性将包括该类的全限定名。如果来源类型未知则该属性会被忽略| -|`defaultValue`|Object|当property没有定义时使用的默认值。如果property类型是个数组则该属性也可以是个数组。如果默认值未知则该属性会被忽略| -|`deprecated`|Deprecation|指定该property是否弃用。如果该字段没有弃用或该信息未知则该属性会被忽略。更多细节请查看下面| - -每一个`properties`元素的`deprecation`属性包含的JSON对象可以包含如下的属性: - -|名称|类型|目的| -|----|:----|:----| -|`level`|String|弃用的级别,可以是`warning`(默认)或者`error`。当一个属性有`warning`弃用级别,它应当还是会被绑定在环境里。但是,当它有一个`error`启用级别,这个属性就不再被管理,也不再被绑定。 -|`reason`|String|对这个属性被弃用的原因的简短描述。没有原因则可能会被省略。推荐使用一个简短的段落描述,开头提供一个简要的总结,最后一行以句号(`.`)结束| -|`replacement`|String|属性的全名,代替弃用的属性。如果没有代替的属性则会被省略| - -**注** 在Spring Boot 1.3之前,单个的`deprecated`布尔属性可以用来代替`deprecation`元素。在弃用的方式里,这仍旧被支持,但是不应当再被使用。如果没有可用的reason和replacement,一个空的`deprecation`对象应当被设置。 - -Deprecation也可以通过在暴露deprecated属性的getter方法上,添加`@DeprecatedConfigurationProperty`标注的方式,在代码中声明式地指定。比如,让我们假设`app.foo.target`属性令人困惑,被重命名成了`app.foo.name`: -```java -@ConfigurationProperties("app.foo") -public class FooProperties { - - private String name; - - public String getName() { ... } - - public void setName(String name) { ... } - - @DeprecatedConfigurationProperty(replacement = "app.foo.name") - @Deprecated - public String getTarget() { - return getName(); - } - - @Deprecated - public void setTarget(String target) { - setName(target); - } -} -``` -**注** 没有办法设置`level`,因为代码还在处理这个属性,所以一直是`warning`。 - +### 附录B.1.2. Property属性 + +`properties`数组中包含的JSON对象可以包含以下属性: + +|名称|类型|目的| +|----|:----|:----| +|`name`|String|property的全名,格式为小写句点分割的形式(比如`server.servlet.path`)。该属性是强制性的| +|`type`|String|property数据类型的完整的签名。例如`java.lang.String`,但也可以是一个完整的泛型类,比如`java.util.Map`。该属性可以用来指导用户他们可以输入值的类型。为了保持一致,原生类型使用它们的包装类代替,比如`boolean`变成了`java.lang.Boolean`。注意,这个类可能是个从一个字符串转换而来的复杂类型。如果类型未知则该属性会被忽略| +|`description`|String|一个简短的组的描述,用于展示给用户。如果没有描述可用则该属性会被省略。推荐使用一个简短的段落描述,开头提供一个简要的总结,最后一行以句号(`.`)结束| +|`sourceType`|String|贡献property的来源类名。例如,如果property来自一个被`@ConfigurationProperties`注解的类,该属性将包括该类的全限定名。如果来源类型未知则该属性会被忽略| +|`defaultValue`|Object|当property没有定义时使用的默认值。如果property类型是个数组则该属性也可以是个数组。如果默认值未知则该属性会被忽略| +|`deprecated`|Deprecation|指定该property是否弃用。如果该字段没有弃用或该信息未知则该属性会被忽略。下表提供了关于`deprecation`属性的更多详细信息| + +每一个`properties`元素的`deprecation`属性包含的JSON对象可以包含如下的属性: + +|名称|类型|目的| +|----|:----|:----| +|`level`|String|弃用的级别,可以是`warning`(默认)或者`error`。当一个属性有`warning`弃用级别,它应当还是会被绑定在环境里。但是,当它有一个`error`启用级别,这个属性就不再被管理,也不再被绑定。 +|`reason`|String|对这个属性被弃用的原因的简短描述。没有原因则可能会被省略。推荐使用一个简短的段落描述,开头提供一个简要的总结,最后一行以句号(`.`)结束| +|`replacement`|String|属性的全名,代替弃用的属性。如果没有代替的属性则会被省略| + +**注** 在Spring Boot 1.3之前,单个的`deprecated`布尔属性可以用来代替`deprecation`元素。在弃用的方式里,这仍旧被支持,但是不应当再被使用。如果没有可用的reason和replacement,一个空的`deprecation`对象应当被设置。 + +Deprecation也可以通过在暴露deprecated属性的getter方法上,添加`@DeprecatedConfigurationProperty`标注的方式,在代码中声明式地指定。比如,让我们假设`app.acme.target`属性令人困惑,被重命名成了`app.acme.name`。下面的例子展示了如何处理这种情况: +```java +@ConfigurationProperties("app.acme") +public class AcmeProperties { + + private String name; + + public String getName() { ... } + + public void setName(String name) { ... } + + @DeprecatedConfigurationProperty(replacement = "app.acme.name") + @Deprecated + public String getTarget() { + return getName(); + } + + @Deprecated + public void setTarget(String target) { + setName(target); + } +} +``` +**注** 没有办法设置`level`,因为代码还在处理这个属性,所以一直是`warning`。 + 上面的代码确保了弃用的属性依旧工作(在幕后委托给`name`属性)。一旦`getTarget`和`setTarget`方法可以从你的公共API移除,元数据里的自动的弃用提示也会一同消失。如果你想要保持提示,用`error`弃用级别添加手工的元数据,保证用户仍旧会收到关于那个属性的通知。当提供了`replacement`的时候,这会特别有用。 \ No newline at end of file diff --git a/X. Appendices/B.1.3 Hint Attributes.md b/X. Appendices/B.1.3 Hint Attributes.md index 710b7e79..ab3e7446 100644 --- a/X. Appendices/B.1.3 Hint Attributes.md +++ b/X. Appendices/B.1.3 Hint Attributes.md @@ -1,23 +1,23 @@ -### 附录B.1.3. Hint属性 - -`hints`数组中包含的JSON对象能够包含以下属性: - -|名称|类型|目的| -|----|:----|:----| -|`name`|String|该hint参考的property的全名。格式为小写虚线分割的形式(比如`server.servlet.path`)。如果这个属性参考一个map(比如`system.contexts`),hint要么应用到map的key(`system.context.keys`)上,要么应用到value上(`system.context.values`)。该属性是强制性的| -|`values`|ValueHint[]|由`ValueHint`对象定义的有效值的列表(看下面)。每一个入口都定义了值,并可能有一段描述| -|`providers`|ValueProvider[]|由`ValueProvider`对象定义的提供者的列表(看下面)。每一个入口都定义了提供者的名字和它的参数,如果有的话| - -每一个`hint`元素的`values`属性包含的JSON对象可以包含如下的属性: - -|名称|类型|目的| -|----|:----|:----| -|`value`|Object|该hint参考的元素的有效值。如果属性的类型是数组,那么也可以是有效值的数组。该属性是强制性的| -|`description`|String|一个简短的对有效值的描述,用于展示给用户。如果没有描述可用则该属性会被省略。推荐使用一个简短的段落描述,开头提供一个简要的总结,最后一行以句号(`.`)结束| - -每一个`hint`元素的`providers`属性包含的JSON对象可以包含如下的属性: - -|名称|类型|目的| -|----|:----|:----| -|`name`|String|提供者的名字,为该hint参考的元素提供额外的内容。| -|`parameters`|JSON object|提供者支持的任何额外的内容(更多细节,请查看提供者的文档)| +### 附录B.1.3. Hint属性 + +`hints`数组中包含的JSON对象能够包含以下属性: + +|名称|类型|目的| +|----|:----|:----| +|`name`|String|该hint参考的property的全名。格式为小写句点分割的形式(比如`server.servlet.path`)。如果这个属性参考一个map(比如`system.contexts`),hint要么应用到map的key(`system.context.keys`)上,要么应用到value上(`system.context.values`)。该属性是强制性的| +|`values`|ValueHint[]|由`ValueHint`对象定义的有效值的列表(在下表中说明)。每一个入口都定义了值,并可能有一段描述| +|`providers`|ValueProvider[]|由`ValueProvider`对象定义的提供者的列表(本文档稍后将对此进行描述)。每一个入口都定义了提供者的名字和它的参数,如果有的话| + +每一个`hint`元素的`values`属性包含的JSON对象可以包含如下的属性: + +|名称|类型|目的| +|----|:----|:----| +|`value`|Object|该hint参考的元素的有效值。如果属性的类型是数组,那么也可以是有效值的数组。该属性是强制性的| +|`description`|String|一个简短的对有效值的描述,用于展示给用户。如果没有描述可用则该属性会被省略。推荐使用一个简短的段落描述,开头提供一个简要的总结,最后一行以句号(`.`)结束| + +每一个`hint`元素的`providers`属性包含的JSON对象可以包含如下的属性: + +|名称|类型|目的| +|----|:----|:----| +|`name`|String|提供者的名字,为该hint参考的元素提供额外的内容。| +|`parameters`|JSON object|提供者支持的任何额外的内容(更多细节,请查看提供者的文档)| diff --git a/X. Appendices/B.1.4. Repeated Metadata Items.md b/X. Appendices/B.1.4. Repeated Metadata Items.md new file mode 100644 index 00000000..01ec12fa --- /dev/null +++ b/X. Appendices/B.1.4. Repeated Metadata Items.md @@ -0,0 +1,3 @@ +### 附录B.1.4. 可重复的元数据节点 + +在同一个元数据文件中可以有多个"property"和"group"名称都相同的对象。例如,Spring Boot将`spring.datasource`属性绑定到Hikari,Tomcat和DBCP类,并且每个都潜在的提供了重复的属性名。虽然多次出现在元数据中的相同名称不应该是常见的,但是元数据的使用者应该注意确保他们支持它。 diff --git a/X. Appendices/B.1.4. Repeated meta-data items.md b/X. Appendices/B.1.4. Repeated meta-data items.md deleted file mode 100644 index 00dce5ad..00000000 --- a/X. Appendices/B.1.4. Repeated meta-data items.md +++ /dev/null @@ -1,3 +0,0 @@ -### 附录B.1.4. 可重复的元数据节点 - -在同一个元数据文件中出现多次相同名称的"property"和"group"对象是可以接受的。例如,Spring Boot将`spring.datasource`属性绑定到Hikari,Tomcat和DBCP类,并且每个都潜在的提供了重复的属性名。这些元数据的消费者需要确保他们支持这样的场景。 diff --git a/X. Appendices/B.2 Providing Manual Hints.md b/X. Appendices/B.2 Providing Manual Hints.md new file mode 100644 index 00000000..3d2db71c --- /dev/null +++ b/X. Appendices/B.2 Providing Manual Hints.md @@ -0,0 +1,7 @@ +### 附录B.2 提供人工提示 + +为了优化用户体验,协助用户配置一个给定的属性,你可以提供额外的元数据: + +- 描述一个属性的可能值的列表。 +- 联系提供者,将良好定义的语义添加到属性上。这样,工具就可以基于工程的上下文,发现可能值的列表。 + diff --git a/X. Appendices/B.2 Providing manual hints.md b/X. Appendices/B.2 Providing manual hints.md deleted file mode 100644 index a024b4f9..00000000 --- a/X. Appendices/B.2 Providing manual hints.md +++ /dev/null @@ -1,6 +0,0 @@ -### 附录B.2 提供人工提示 - -为了优化用户体验,协助用户配置一个给定的属性,你可以提供额外的元数据: - -1. 描述一个属性的可能值的列表。 -2. 联系提供者,将良好定义的语义添加到属性上。这样,工具就可以基于工程的上下文,发现可能值的列表。 \ No newline at end of file diff --git a/X. Appendices/B.2.1 Value Hint.md b/X. Appendices/B.2.1 Value Hint.md new file mode 100644 index 00000000..6f408a95 --- /dev/null +++ b/X. Appendices/B.2.1 Value Hint.md @@ -0,0 +1,32 @@ +### 附录B.2.1 值提示 + +每一个hint的`name`属性参考了property的`name`。在[上面最初的例子](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#configuration-metadata-format)里,我们为`spring.jpa.hibernate.ddl-auto`属性提供了5个值:`none`、`validate`、`update`、`create`和`create-drop`。每个值也可以有一个描述。 + +如果你的属性不是`Map`类型,你可以为key和value一起提供hint(但不是为map它自己)。特殊的`.keys`和`.values`后缀必须被分别地用于参考keys和values。 + +让我们假设一个`sample.contexts`,它把神奇的String值映射到一个Integer: +```java +@ConfigurationProperties("sample") +public class SampleProperties { + + private Map contexts; + // getters and setters +} +``` +例如,神奇的值是`sample1`和`sample2`。为了给key提供额外的内容帮助,你可以将以下内容添加到[模块的手工元数据](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#configuration-metadata-additional-metadata): +```json +{"hints": [ + { + "name": "sample.contexts.keys", + "values": [ + { + "value": "sample1" + }, + { + "value": "sample2" + } + ] + } +]} +``` +**注** 我们建议你对这两个值使用`Enum`。如果你的IDE支持,这是目前为止实现自动补全的最有效的方式。 \ No newline at end of file diff --git a/X. Appendices/B.2.1 Value hint.md b/X. Appendices/B.2.1 Value hint.md deleted file mode 100644 index a8b9d785..00000000 --- a/X. Appendices/B.2.1 Value hint.md +++ /dev/null @@ -1,32 +0,0 @@ -### 附录B.2.1 值提示 - -每一个hint的`name`属性参考了property的`name`。在上面最初的例子里,我们为`spring.jpa.hibernate.ddl-auto`属性提供了5个值:`none`,`validate`,`update`,`create`和`create-drop`。每个值也可以有一个描述。 - -如果你的属性不是`Map`类型,你可以为key和value一起提供hint(但不是为map它自己)。特殊的`.keys`和`.values`后缀必须被分别地用于参考keys和values。 - -让我们假设一个`foo.contexts`,它把神奇的String值映射到一个Integer: -```java -@ConfigurationProperties("foo") -public class FooProperties { - - private Map contexts; - // getters and setters -} -``` -例如,神奇的值是foo和bar。为了给key提供额外的内容帮助,你可以将以下内容添加到[模块的手工元数据](https://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#configuration-metadata-additional-metadata): -```json -{"hints": [ - { - "name": "foo.contexts.keys", - "values": [ - { - "value": "foo" - }, - { - "value": "bar" - } - ] - } -]} -``` -**注** 当然,对那些有两个值的,你应当有一个替代的`Enum`。如果你的IDE支持,这是目前为止实现自动补全的最有效的方式。 \ No newline at end of file diff --git a/X. Appendices/B.2.2 Value Provider.md b/X. Appendices/B.2.2 Value Provider.md new file mode 100644 index 00000000..312346b0 --- /dev/null +++ b/X. Appendices/B.2.2 Value Provider.md @@ -0,0 +1,210 @@ +### 附录B.2.2 值提供者 + +提供者是将语义附加到属性上的一种强大的方式。我们在下面的章节里定义了官方的提供者,你可以为你自己的提示使用它们。但是,必须记住:你最喜欢的IDE可能实现了其中的一部分,或者什么也没有实现。它也可以最后提供它自己。 + +**注** 由于这是一个新特性,IDE供应商必须跟上它的工作方式。采用时间自然会有所不同。 + +下面👇的表格总结了支持的提供者的列表: + +|名称|描述| +|----|:----| +|`any`|允许提供额外的值| +|`class-reference`|自动补全项目里可用的类。通常被一个由`目标`参数指定的基础的类约束| +|`handle-as`|操作属性,就好像它是由强制的`目标`参数定义的类型一样| +|`logger-name`|自动补全有效的记录器名。典型地,目前项目里可用的包名和类名会被自动补全| +|`spring-bean-reference`|自动补全当前项目里可用的bean的名字。通常被一个由`目标`参数指定的基础的类约束| +|`spring-profile-name`|自动补全当前项目里可用的Spring profile的名字| + +**注** 对于一个给定的属性,只能有一个有效的提供者。但是,如果可以以某种方式共同管理属性,你也可以指定多个提供者。确保把最强大的提供者放在第一位,因为IDE必须使用它能够处理的JSON部分里的第一个。如果对于一个给定的属性,没有提供者提供支持,也不会有特殊的内容帮助被提供。 + +**Any** + +特殊的**any**提供程序值允许提供任何附加值。如果支持,应该应用基于属性类型的常规值验证。 + +如果你有一个值列表,并且任何额外的值仍然被认为是有效的,则通常使用此提供程序。 + +下面的例子提供了`on`和`off`作为`system.state`的自动完成值: +```json +{"hints": [ + { + "name": "system.state", + "values": [ + { + "value": "on" + }, + { + "value": "off" + } + ], + "providers": [ + { + "name": "any" + } + ] + } +]} +``` +注意,在前面的示例中,还允许任何其他值。 + +**Class Reference** + +**class-reference**提供程序自动完成项目中可用的类。该提供程序支持以下参数: +|参数|类型|默认值|描述| +|----|:----|:----|:----| +|`target`|`String`(`Class`)|none|应该分配给所选值的类的完全限定名。通常用于过滤非候选类。请注意,此信息可以由类型本身提供,方法是公开具有适当上限的类。| +|`concrete`|`boolean`|true|指定是否只将具体类视为有效的候选类。| + +下面的元数据片段对应于标准的`server.servlet.jsp.class-name`属性定义了要使用的`JspServlet`类名: +```json +{"hints": [ + { + "name": "server.servlet.jsp.class-name", + "providers": [ + { + "name": "class-reference", + "parameters": { + "target": "javax.servlet.http.HttpServlet" + } + } + ] + } +]} +``` + +**Handle As** + +**handle-as**提供程序允许您将属性的类型替换为更高级的类型。当属性具有`java.lang.String`类型时,通常会发生这种情况。因为你不希望配置类依赖于可能不在类路径上的类。该提供程序支持以下参数: + +|参数|类型|默认值|描述| +|----|:----|:----|:----| +|`target`|`String`(`Class`)|none|要考虑用于属性的类型的完全限定名。这个参数是强制性的。| + +可以使用以下类型: + +- 任何`java.lang.Enum`:列出属性的可能值。(我们建议使用`Enum`类型定义属性,因为IDE不需要进一步的提示就可以自动完成这些值。) +- `java.nio.charset.Charset`:支持自动完成字符集/编码值(如`UTF-8`) +- `java.util.Locale`:自动完成区域设置(如`en_US`) +- `org.springframework.util.MimeType`:支持自动完成内容类型值(例如`text/plain`) +- `org.springframework.core.io.Resource`:支持自动完成Spring的资源抽象,以引用文件系统或类路径上的文件。(如`classpath:/sample.properties`) + +**注** 如果可以提供多个值,则使用`集合`或数组类型来教导IDE。 + +下面的元数据片段对应于标准的`spring.liquibase.change-log`属性,定义要使用的更改日志的路径。它实际上是作为一个`org.springframework.core.io.Resource`在内部使用的。但是不能这样公开,因为我们需要保留原始的字符串值,以便将它传递给Liquibase API。 +```json +{"hints": [ + { + "name": "spring.liquibase.change-log", + "providers": [ + { + "name": "handle-as", + "parameters": { + "target": "org.springframework.core.io.Resource" + } + } + ] + } +]} +``` + +**Logger Name** + +**logger-name**提供程序自动完成有效的日志程序名称。通常,当前项目中可用的包名和类名可以自动完成。特定的框架可能有额外的、也可以支持的神奇日志程序名称。 + +由于记录器名称可以是任意的名称,因此该提供程序应该允许任何值,但是可以突出显示项目的类路径中不可用的有效包和类名称。 + +下面的元数据片段对应于标准`logging.level`属性。键是记录器名称,值对应于标准日志级别或任何自定义级别。 +```json +{"hints": [ + { + "name": "logging.level.keys", + "values": [ + { + "value": "root", + "description": "Root logger used to assign the default logging level." + } + ], + "providers": [ + { + "name": "logger-name" + } + ] + }, + { + "name": "logging.level.values", + "values": [ + { + "value": "trace" + }, + { + "value": "debug" + }, + { + "value": "info" + }, + { + "value": "warn" + }, + { + "value": "error" + }, + { + "value": "fatal" + }, + { + "value": "off" + } + + ], + "providers": [ + { + "name": "any" + } + ] + } +]} +``` + +Spring Bean Reference + +`spring-bean-reference`提供程序自动完成当前项目配置中定义的bean。该提供程序支持以下参数: + +|参数|类型|默认值|描述| +|----|:----|:----|:----| +|`target`|`String`(`Class`)|none|bean类的应可赋值给候选者的完全限定名。通常用于过滤非候选bean。| + +下面的元数据片段对应于标准的`spring.jmx.server`属性,定义要使用的`MBeanServer` bean的名称: +```json +{"hints": [ + { + "name": "spring.jmx.server", + "providers": [ + { + "name": "spring-bean-reference", + "parameters": { + "target": "javax.management.MBeanServer" + } + } + ] + } +]} +``` + +**注** 绑定器不知道元数据。如果你提供了那个提示,你仍然需要将bean名称转换为`ApplicationContext`使用的实际bean引用。 + +Spring Profile Name + +`spring-profile-name`提供程序自动完成在当前项目的配置中定义的Spring配置文件。 + +下面的元数据片段对应于标准的`spring.profiles.active`属性,定义要启用的Spring配置文件的名称: +```json +{"hints": [ + { + "name": "spring.profiles.active", + "providers": [ + { + "name": "spring-profile-name" + } + ] + } +]} +``` diff --git a/X. Appendices/B.2.2 Value provider.md b/X. Appendices/B.2.2 Value provider.md deleted file mode 100644 index 183a0a36..00000000 --- a/X. Appendices/B.2.2 Value provider.md +++ /dev/null @@ -1,222 +0,0 @@ -### 附录B.2.2 值提供者 - -提供者是将语义附加到属性上的一种强大的方式。我们在下面的章节里定义了官方的提供者,你可以为你自己的提示使用它们。但是,必须记住:你最喜欢的IDE可能实现了其中的一部分,或者什么也没有实现。它也可以最后提供它自己。 - -**注** 由于这是一个新特性,IDE供应商将不得不追上这个新特性。 - -下面👇的表格总结了支持的提供者的列表: - -|名称|描述| -|----|:----| -|`any`|允许提供额外的值| -|`class-reference`|自动补全项目里可用的类。通常被一个由`目标`参数指定的基础的类约束| -|`handle-as`|操作属性,就好像它是由强制的`目标`参数定义的类型一样| -|`logger-name`|自动补全有效的记录器名。典型地,目前项目里可用的包名和类名会被自动补全| -|`spring-bean-reference`|自动补全当前项目里可用的bean的名字。通常被一个由`目标`参数指定的基础的类约束| -|`spring-profile-name`|自动补全当前项目里可用的Spring profile的名字| - -**提示** 对于一个给定的属性,只能有一个有效的提供者。但是,如果可以以某种方式共同管理属性,你也可以指定多个提供者。确保把最强大的提供者放在第一位,因为IDE必须使用它能够处理的JSON部分里的第一个。如果对于一个给定的属性,没有提供者提供支持,也不会有特殊的内容帮助被提供。 - -**Any** - -The any provider permits any additional values to be provided. Regular value validation based on the property type should be applied if this is supported. - -This provider will be typically used if you have a list of values and any extra values are still to be considered as valid. - -The example below offers on and off as auto-completion values for system.state; any other value is also allowed: - -{"hints": [ - { - "name": "system.state", - "values": [ - { - "value": "on" - }, - { - "value": "off" - } - ], - "providers": [ - { - "name": "any" - } - ] - } -]} -Class reference - -The class-reference provider auto-completes classes available in the project. This provider supports these parameters: - -Parameter Type Default value Description -target - -String (Class) - -none - -The fully qualified name of the class that should be assignable to the chosen value. Typically used to filter out non candidate classes. Note that this information can be provided by the type itself by exposing a class with the appropriate upper bound. - -concrete - -boolean - -true - -Specify if only concrete classes are to be considered as valid candidates. - -The meta-data snippet below corresponds to the standard server.servlet.jsp.class-name property that defines the JspServlet class name to use: - -{"hints": [ - { - "name": "server.servlet.jsp.class-name", - "providers": [ - { - "name": "class-reference", - "parameters": { - "target": "javax.servlet.http.HttpServlet" - } - } - ] - } -]} -Handle As - -The handle-as provider allows you to substitute the type of the property to a more high-level type. This typically happens when the property has a java.lang.String type because you don’t want your configuration classes to rely on classes that may not be on the classpath. This provider supports these parameters: - -Parameter Type Default value Description -target - -String (Class) - -none - -The fully qualified name of the type to consider for the property. This parameter is mandatory. - -The following types can be used: - -Any java.lang.Enum that lists the possible values for the property (By all means, try to define the property with the Enum type instead as no further hint should be required for the IDE to auto-complete the values). -java.nio.charset.Charset: auto-completion of charset/encoding values (e.g. UTF-8) -java.util.Locale: auto-completion of locales (e.g. en_US) -org.springframework.util.MimeType: auto-completion of content type values (e.g. text/plain) -org.springframework.core.io.Resource: auto-completion of Spring’s Resource abstraction to refer to a file on the filesystem or on the classpath. (e.g. classpath:/foo.properties) -[Note] -If multiple values can be provided, use a Collection or Array type to teach the IDE about it. -The meta-data snippet below corresponds to the standard liquibase.change-log property that defines the path to the changelog to use. It is actually used internally as a org.springframework.core.io.Resource but cannot be exposed as such as we need to keep the original String value to pass it to the Liquibase API. - -{"hints": [ - { - "name": "liquibase.change-log", - "providers": [ - { - "name": "handle-as", - "parameters": { - "target": "org.springframework.core.io.Resource" - } - } - ] - } -]} -Logger name - -The logger-name provider auto-completes valid logger names. Typically, package and class names available in the current project can be auto-completed. Specific frameworks may have extra magic logger names that could be supported as well. - -Since a logger name can be any arbitrary name, really, this provider should allow any value but could highlight valid packages and class names that are not available in the project’s classpath. - -The meta-data snippet below corresponds to the standard logging.level property, keys are logger names and values correspond to the standard log levels or any custom level: - -{"hints": [ - { - "name": "logging.level.keys", - "values": [ - { - "value": "root", - "description": "Root logger used to assign the default logging level." - } - ], - "providers": [ - { - "name": "logger-name" - } - ] - }, - { - "name": "logging.level.values", - "values": [ - { - "value": "trace" - }, - { - "value": "debug" - }, - { - "value": "info" - }, - { - "value": "warn" - }, - { - "value": "error" - }, - { - "value": "fatal" - }, - { - "value": "off" - } - - ], - "providers": [ - { - "name": "any" - } - ] - } -]} -Spring bean reference - -The spring-bean-reference provider auto-completes the beans that are defined in the configuration of the current project. This provider supports these parameters: - -Parameter Type Default value Description -target - -String (Class) - -none - -The fully qualified name of the bean class that should be assignable to the candidate. Typically used to filter out non candidate beans. - -The meta-data snippet below corresponds to the standard spring.jmx.server property that defines the name of the MBeanServer bean to use: - -{"hints": [ - { - "name": "spring.jmx.server", - "providers": [ - { - "name": "spring-bean-reference", - "parameters": { - "target": "javax.management.MBeanServer" - } - } - ] - } -]} -[Note] -The binder is not aware of the meta-data so if you provide that hint, you will still need to transform the bean name into an actual Bean reference using the ApplicationContext. -Spring profile name - -The spring-profile-name provider auto-completes the Spring profiles that are defined in the configuration of the current project. - -The meta-data snippet below corresponds to the standard spring.profiles.active property that defines the name of the Spring profile(s) to enable: - -{"hints": [ - { - "name": "spring.profiles.active", - "providers": [ - { - "name": "spring-profile-name" - } - ] - } -]} - - diff --git a/X. Appendices/B.3. Generating Your Own Metadata by Using the Annotation Processor.md b/X. Appendices/B.3. Generating Your Own Metadata by Using the Annotation Processor.md new file mode 100644 index 00000000..c85959a2 --- /dev/null +++ b/X. Appendices/B.3. Generating Your Own Metadata by Using the Annotation Processor.md @@ -0,0 +1,26 @@ +### 附录B.3. 使用注解处理器产生自己的元数据 + +通过使用`spring-boot-configuration-processor` jar, 你可以从被`@ConfigurationProperties`注解的节点轻松的产生自己的配置元数据文件。该jar包含一个在你的项目编译时会被调用的Java注解处理器。想要使用该处理器,你只需简单添加`spring-boot-configuration-processor`依赖,例如使用Maven你需要添加: +```xml + + org.springframework.boot + spring-boot-configuration-processor + true + +``` +使用Gradle时,你可以使用[propdeps-plugin](https://github.com/spring-gradle-plugins/propdeps-plugin)并指定: +```gradle +dependencies { + optional "org.springframework.boot:spring-boot-configuration-processor" + } + + compileJava.dependsOn(processResources) +} +``` +**注** 你需要将`compileJava.dependsOn(processResources)`添加到构建中,以确保资源在代码编译之前处理。如果没有该指令,任何`additional-spring-configuration-metadata.json`文件都不会被处理。 + +该处理器会处理被`@ConfigurationProperties`注解的类和方法,description属性用于产生配置类字段值的Javadoc说明。 + +**注** 你应该使用简单的文本来设置`@ConfigurationProperties`字段的Javadoc,因为在没有被添加到JSON之前它们是不被处理的。 + +属性是通过判断是否存在标准的getters和setters来发现的,对于集合类型有特殊处理(即使只出现一个getter)。该注解处理器也支持使用lombok的`@Data`, `@Getter`和`@Setter`注解。 diff --git a/X. Appendices/B.3. Generating your own meta-data using the annotation processor.md b/X. Appendices/B.3. Generating your own meta-data using the annotation processor.md deleted file mode 100644 index ddc6830a..00000000 --- a/X. Appendices/B.3. Generating your own meta-data using the annotation processor.md +++ /dev/null @@ -1,29 +0,0 @@ -### 附录B.3. 使用注解处理器产生自己的元数据 - -通过使用`spring-boot-configuration-processor` jar, 你可以从被`@ConfigurationProperties`注解的节点轻松的产生自己的配置元数据文件。该jar包含一个在你的项目编译时会被调用的Java注解处理器。想要使用该处理器,你只需简单添加`spring-boot-configuration-processor`依赖,例如使用Maven你需要添加: -```xml - - org.springframework.boot - spring-boot-configuration-processor - true - -``` -使用Gradle时,你可以使用[propdeps-plugin](https://github.com/spring-projects/gradle-plugins/tree/master/propdeps-plugin)并指定: -```gradle -dependencies { - optional "org.springframework.boot:spring-boot-configuration-processor" - } - - compileJava.dependsOn(processResources) -} -``` -**注**:你需要将`compileJava.dependsOn(processResources)`添加到构建中,以确保资源在代码编译之前处理。如果没有该指令,任何`additional-spring-configuration-metadata.json`文件都不会被处理。 - -该处理器会处理被`@ConfigurationProperties`注解的类和方法,description属性用于产生配置类字段值的Javadoc说明。 - -**注**:你应该使用简单的文本来设置`@ConfigurationProperties`字段的Javadoc,因为在没有被添加到JSON之前它们是不被处理的。 - - -属性是通过判断是否存在标准的getters和setters来发现的,对于集合类型有特殊处理(即使只出现一个getter)。该注解处理器也支持使用lombok的`@Data`, `@Getter`和`@Setter`注解。 - - diff --git a/X. Appendices/B.3.1. Nested Properties.md b/X. Appendices/B.3.1. Nested Properties.md new file mode 100644 index 00000000..02bb4490 --- /dev/null +++ b/X. Appendices/B.3.1. Nested Properties.md @@ -0,0 +1,29 @@ +### 附录 B.3.1. 内嵌属性 + +该注解处理器自动将内部类当做内嵌属性处理。例如,下面的类: +```java +@ConfigurationProperties(prefix="server") +public class ServerProperties { + + private String name; + + private Host host; + + // ... getter and setters + + private static class Host { + + private String ip; + + private int port; + + // ... getter and setters + + } + +} +``` + +前面的示例生成`server.name`、`server.host.ip`与`server.host.port`属性的元数据信息。你可以使用字段上的`@NestedConfigurationProperty`注释来指示应该将常规(非内部)类视为嵌套类。 + +**注** 这对集合和映射没有影响,因为这些类型是自动标识的,并且为每个类型生成一个元数据属性。 diff --git a/X. Appendices/B.3.1. Nested properties.md b/X. Appendices/B.3.1. Nested properties.md deleted file mode 100644 index cd86f5ab..00000000 --- a/X. Appendices/B.3.1. Nested properties.md +++ /dev/null @@ -1,25 +0,0 @@ -### 附录 B.3.1. 内嵌属性 - -该注解处理器自动将内部类当做内嵌属性处理。例如,下面的类: -```java -@ConfigurationProperties(prefix="server") -public class ServerProperties { - - private String name; - - private Host host; - - // ... getter and setters - - private static class Host { - - private String ip; - - private int port; - - // ... getter and setters - - } - -} -``` diff --git a/X. Appendices/B.3.2. Adding Additional Metadata.md b/X. Appendices/B.3.2. Adding Additional Metadata.md new file mode 100644 index 00000000..37c8a61f --- /dev/null +++ b/X. Appendices/B.3.2. Adding Additional Metadata.md @@ -0,0 +1,7 @@ +### 附录 B.3.2. 添加其他的元数据 + +Spring Boot的配置文件处理非常灵活,通常存在不绑定到`@ConfigurationProperties` bean的属性。你可能还需要调优现有键的一些属性。为了支持这种情况并允许你提供自定义“提示”,注释处理器将自动合并来自`META-INF/additional-spring-configuration-metadata.json`的项,放入主元数据文件。 + +如果你引用的属性是自动检测到的,则会覆盖描述、默认值和弃用信息(如果指定的话)。如果当前模块中没有标识手动属性声明,则将其作为新属性添加。 + +`additional-spring-configuration-metadata.json`文件的格式与常规的`spring-configuration-metadata.json`完全相同。附加属性文件是可选的。如果没有任何其他属性,则不要添加该文件。 diff --git a/X. Appendices/B.3.2. Adding additional meta-data.md b/X. Appendices/B.3.2. Adding additional meta-data.md deleted file mode 100644 index 938822a2..00000000 --- a/X. Appendices/B.3.2. Adding additional meta-data.md +++ /dev/null @@ -1 +0,0 @@ -### 附录 B.3.2. 添加其他的元数据 diff --git a/X. Appendices/C. Auto-configuration classes.md b/X. Appendices/C. Auto-configuration classes.md index b6da2ef2..07dafb54 100644 --- a/X. Appendices/C. Auto-configuration classes.md +++ b/X. Appendices/C. Auto-configuration classes.md @@ -1,12 +1,3 @@ ### 附录 C. 自动配置类 -这里有一个Spring Boot提供的所有自动配置类的文档链接和源码列表。也要记着看一下你的应用都开启了哪些自动配置(使用`--debug`或`-Debug`启动应用,或在一个Actuator应用中使用`autoconfig`端点)。 - - - - - - - - - +下面是Spring Boot提供的所有自动配置类的列表,其中有文档和源代码的链接。还请记住查看应用程序中的状况报告,以了解关于打开哪些功能的更多细节。(为此,使用`--debug`或`-Ddebug`启动应用程序,或者在执行器应用程序中使用`conditions`端点)。 diff --git "a/X. Appendices/C.1. From the \342\200\234spring-boot-autoconfigure\342\200\235 module.md" "b/X. Appendices/C.1. From the \342\200\234spring-boot-autoconfigure\342\200\235 module.md" index aeebd714..ccb4d2ec 100644 --- "a/X. Appendices/C.1. From the \342\200\234spring-boot-autoconfigure\342\200\235 module.md" +++ "b/X. Appendices/C.1. From the \342\200\234spring-boot-autoconfigure\342\200\235 module.md" @@ -4,35 +4,112 @@ |配置类|链接| |------|:------| -|[`ActiveMQAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.html)| -|[`AopAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.html)| -|[`ArtemisAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.html)| -|[`BatchAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.html)| -|[`CacheAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.html)| -|[`CassandraAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.html)| -|[`CassandraDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.html)| -|[`CassandraReactiveDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.html)| -|[`CassandraReactiveRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfiguration.html)| -|[`CassandraRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.htmlCassandraReactiveRepositoriesAutoConfiguration.html)| -|[`CloudAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.html)| -|[`ConfigurationPropertiesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfiguration.html)| -|[`CouchbaseAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.html)| -|[`CouchbaseDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.html)| -|[`CouchbaseRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.html)| -|[`DataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.html)| -|[`DataSourceTransactionManagerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.html)| -|[`DeviceDelegatingViewResolverAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfiguration.html)| -|[`DeviceResolverAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfiguration.html)| -|[`DispatcherServletAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.html)| -|[`ElasticsearchAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.html)| -|[`ElasticsearchDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.html)| -|[`ElasticsearchRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.html)| -|[`EmbeddedLdapAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.html)| -|[`EmbeddedMongoAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.html)| -|[`ErrorMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.html)| -|[`FacebookAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/social/FacebookAutoConfiguration.html)| -|[`FallbackWebSecurityAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/FallbackWebSecurityAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/security/FallbackWebSecurityAutoConfiguration.html)| -|[`FlywayAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.html)| -|[`FreeMarkerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.html)| -|[`GroovyTemplateAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.html)| -|[`GsonAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.html)| +|[`ActiveMQAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfiguration.html)| +|[`AopAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.html)| +|[`ArtemisAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfiguration.html)| +|[`BatchAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.html)| +|[`CacheAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/cache/CacheAutoConfiguration.html)| +|[`CassandraAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.html)| +|[`CassandraDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.html)| +|[`CassandraReactiveDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveDataAutoConfiguration.html)| +|[`CassandraReactiveRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfiguration.html)| +|[`CassandraRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.html)| +|[`CloudAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.html)| +|[`CodecsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.html)| +|[`ConfigurationPropertiesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfiguration.html)| +|[`CouchbaseAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.html)| +|[`CouchbaseDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfiguration.html)| +|[`CouchbaseReactiveDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfiguration.html)| +|[`CouchbaseReactiveRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfiguration.html)| +|[`CouchbaseRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfiguration.html)| +|[`DataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.html)| +|[`DataSourceTransactionManagerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfiguration.html)| +|[`DispatcherServletAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.html)| +|[`ElasticsearchAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.html)| +|[`ElasticsearchDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.html)| +|[`ElasticsearchRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfiguration.html)| +|[`EmbeddedLdapAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.html)| +|[`EmbeddedMongoAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.html)| +|[`EmbeddedWebServerFactoryCustomizerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/EmbeddedWebServerFactoryCustomizerAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/embedded/EmbeddedWebServerFactoryCustomizerAutoConfiguration.html)| +|[`ErrorMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.html)| +|[`ErrorWebFluxAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/ErrorWebFluxAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/reactive/error/ErrorWebFluxAutoConfiguration.html)| +|[`FlywayAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.html)| +|[`FreeMarkerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.html)| +|[`GroovyTemplateAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.html)| +|[`GsonAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.html)| +|[`H2ConsoleAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.html)| +|[`HazelcastAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfiguration.html)| +|[`HazelcastJpaDependencyAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfiguration.html)| +|[`HibernateJpaAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.html)| +|[`HttpEncodingAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfiguration.html)| +|[`HttpHandlerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfiguration.html)| +|[`HttpMessageConvertersAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfiguration.html)| +|[`HypermediaAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.html)| +|[`InfluxDbAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfiguration.html)| +|[`IntegrationAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.html)| +|[`JacksonAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.html)| +|[`JdbcTemplateAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfiguration.html)| +|[`JerseyAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.html)| +|[`JestAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfiguration.html)| +|[`JmsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.html)| +|[`JmxAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.html)| +|[`JndiConnectionFactoryAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfiguration.html)| +|[`JndiDataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.html)| +|[`JooqAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.html)| +|[`JpaRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfiguration.html)| +|[`JsonbAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfiguration.html)| +|[`JtaAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfiguration.html)| +|[`KafkaAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.html)| +|[`LdapAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.html)| +|[`LdapDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfiguration.html)| +|[`LdapRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/ldap/LdapRepositoriesAutoConfiguration.html)| +|[`LiquibaseAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.html)| +|[`MailSenderAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfiguration.html)| +|[`MailSenderValidatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailSenderValidatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/mail/MailSenderValidatorAutoConfiguration.html)| +|[`MessageSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.html)| +|[`MongoAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.html)| +|[`MongoDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.html)| +|[`MongoReactiveAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.html)| +|[`MongoReactiveDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.html)| +|[`MongoReactiveRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfiguration.html)| +|[`MongoRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfiguration.html)| +|[`MultipartAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.html)| +|[`MustacheAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.html)| +|[`Neo4jDataAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.html)| +|[`Neo4jRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfiguration.html)| +|[`OAuth2ClientAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientAutoConfiguration.html)| +|[`PersistenceExceptionTranslationAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.html)| +|[`ProjectInfoAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfiguration.html)| +|[`PropertyPlaceholderAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfiguration.html)| +|[`QuartzAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration.html)| +|[`RabbitAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.html)| +|[`ReactiveSecurityAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfiguration.html)| +|[`ReactiveUserDetailsServiceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfiguration.html)| +|[`ReactiveWebServerFactoryAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.html)| +|[`ReactorCoreAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/reactor/core/ReactorCoreAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/reactor/core/ReactorCoreAutoConfiguration.html)| +|[`RedisAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.html)| +|[`RedisReactiveAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.html)| +|[`RedisRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfiguration.html)| +|[`RepositoryRestMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfiguration.html)| +|[`RestTemplateAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfiguration.html)| +|[`SecurityAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.html)| +|[`SecurityFilterAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.html)| +|[`SendGridAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfiguration.html)| +|[`ServletWebServerFactoryAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.html)| +|[`SessionAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.html)| +|[`SolrAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/solr/SolrAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/solr/SolrAutoConfiguration.html)| +|[`SolrRepositoriesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfiguration.html)| +|[`SpringApplicationAdminJmxAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.html)| +|[`SpringDataWebAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfiguration.html)| +|[`ThymeleafAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.html)| +|[`TransactionAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfiguration.html)| +|[`UserDetailsServiceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.html)| +|[`ValidationAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.html)| +|[`WebClientAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfiguration.html)| +|[`WebFluxAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.html)| +|[`WebMvcAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.html)| +|[`WebServicesAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.html)| +|[`WebSocketMessagingAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfiguration.html)| +|[`WebSocketReactiveAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/WebSocketReactiveAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/websocket/reactive/WebSocketReactiveAutoConfiguration.html)| +|[`WebSocketServletAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfiguration.html)| +|[`XADataSourceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.html)| diff --git "a/X. Appendices/C.2. From the \342\200\234spring-boot-actuator-autoconfigure\342\200\235 module.md" "b/X. Appendices/C.2. From the \342\200\234spring-boot-actuator-autoconfigure\342\200\235 module.md" new file mode 100644 index 00000000..051bbc81 --- /dev/null +++ "b/X. Appendices/C.2. From the \342\200\234spring-boot-actuator-autoconfigure\342\200\235 module.md" @@ -0,0 +1,73 @@ +### 附录 C.2 来自`spring-boot-actuator-autoconfigure`模块 + +下列的自动配置类来自于`spring-boot-actuator-autoconfigure`模块: + +|配置类|链接| +|------|:------| +|[`AtlasMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfiguration.html)| +|[`AuditAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfiguration.html)| +|[`AuditEventsEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfiguration.html)| +|[`BeansEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfiguration.html)| +|[`CacheMetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfiguration.html)| +|[`CassandraHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfiguration.html)| +|[`CloudFoundryActuatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.html)| +|[`CompositeMeterRegistryAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfiguration.html)| +|[`ConditionsReportEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfiguration.html)| +|[`ConfigurationPropertiesReportEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfiguration.html)| +|[`CouchbaseHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthIndicatorAutoConfiguration.html)| +|[`DataSourceHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthIndicatorAutoConfiguration.html)| +|[`DataSourcePoolMetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.html)| +|[`DatadogMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.html)| +|[`DiskSpaceHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthIndicatorAutoConfiguration.html)| +|[`ElasticsearchHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfiguration.html)| +|[`EndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.html)| +|[`EnvironmentEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfiguration.html)| +|[`FlywayEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfiguration.html)| +|[`GangliaMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfiguration.html)| +|[`GraphiteMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfiguration.html)| +|[`HealthEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfiguration.html)| +|[`HealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.html)| +|[`HeapDumpWebEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfiguration.html)| +|[`HttpTraceAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceAutoConfiguration.html)| +|[`HttpTraceEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/trace/http/HttpTraceEndpointAutoConfiguration.html)| +|[`InfluxDbHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthIndicatorAutoConfiguration.html)| +|[`InfluxMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.html)| +|[`InfoContributorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfiguration.html)| +|[`InfoEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfiguration.html)| +|[`JmsHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthIndicatorAutoConfiguration.html)| +|[`JmxEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.html)| +|[`JmxMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfiguration.html)| +|[`JolokiaEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/jolokia/JolokiaEndpointAutoConfiguration.html)| +|[`LdapHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthIndicatorAutoConfiguration.html)| +|[`LiquibaseEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.html)| +|[`LogFileWebEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfiguration.html)| +|[`LoggersEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.html)| +|[`MailHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/mail/MailHealthIndicatorAutoConfiguration.html)| +|[`ManagementContextAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.html)| +|[`MappingsEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfiguration.html)| +|[`MetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.html)| +|[`MetricsEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/MetricsEndpointAutoConfiguration.html)| +|[`MongoHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorAutoConfiguration.html)| +|[`Neo4jHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthIndicatorAutoConfiguration.html)| +|[`NewRelicMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.html)| +|[`PrometheusMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfiguration.html)| +|[`RabbitHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthIndicatorAutoConfiguration.html)| +|[`RabbitMetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfiguration.html)| +|[`ReactiveCloudFoundryActuatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.html)| +|[`ReactiveManagementContextAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementContextAutoConfiguration.html)| +|[`RedisHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfiguration.html)| +|[`RestTemplateMetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfiguration.html)| +|[`ScheduledTasksEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfiguration.html)| +|[`ServletManagementContextAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementContextAutoConfiguration.html)| +|[`SessionsEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfiguration.html)| +|[`ShutdownEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfiguration.html)| +|[`SignalFxMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfiguration.html)| +|[`SimpleMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfiguration.html)| +|[`SolrHealthIndicatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/solr/SolrHealthIndicatorAutoConfiguration.html)| +|[`StatsdMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfiguration.html)| +|[`ThreadDumpEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfiguration.html)| +|[`TomcatMetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfiguration.html)| +|[`WavefrontMetricsExportAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfiguration.html)| +|[`WebEndpointAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfiguration.html)| +|[`WebFluxMetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/web/reactive/WebFluxMetricsAutoConfiguration.html)| +|[`WebMvcMetricsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.html)| diff --git "a/X. Appendices/C.2. From the \342\200\234spring-boot-actuator\342\200\235 module.md" "b/X. Appendices/C.2. From the \342\200\234spring-boot-actuator\342\200\235 module.md" deleted file mode 100644 index a88a917a..00000000 --- "a/X. Appendices/C.2. From the \342\200\234spring-boot-actuator\342\200\235 module.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 附录 C.2 来自`spring-boot-actuator`模块 - -下列的自动配置类来自于`spring-boot-actuator`模块: - -|配置类|链接| -|------|:------| -|[`AuditAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/actuate/autoconfigure/AuditAutoConfiguration.html)| -|[`CacheStatisticsAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.html)| -|[`CloudFoundryActuatorAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.M5/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfiguration.java)|[javadoc](https://docs.spring.io/spring-boot/docs/2.0.0.M5/api/org/springframework/boot/actuate/cloudfoundry/CloudFoundryActuatorAutoConfiguration.html)| diff --git a/X. Appendices/D. Test auto-configuration annotations.md b/X. Appendices/D. Test auto-configuration annotations.md index 5e219f8b..670f2ef1 100644 --- a/X. Appendices/D. Test auto-configuration annotations.md +++ b/X. Appendices/D. Test auto-configuration annotations.md @@ -1,3 +1,17 @@ -### 附录 D. 测试自动配置的标注 +### 附录 D. 测试的自动配置的标注 -Here is a table of the various @…Test annotations that can be used to test slices of your application and the auto-configuration that they import by default: +下表列出了各种`@…Test`注释,这些注释可以用来测试你的应用程序的片段,以及默认情况下导入的自动配置。 + +|测试片段|导入的自动配置| +|------|:------| +|`@DataJpaTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration` `org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration` `org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration` `org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration` `org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration` `org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration` `org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration`| +|`@DataLdapTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration` `org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration` `org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration` `org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration`| +|`@DataMongoTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration` `org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration` `org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration` `org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration` `org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration` `org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration` `org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration`| +|`@DataNeo4jTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration` `org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration` `org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration`| +|`@DataRedisTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration` `org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration`| +|`@JdbcTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration` `org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration` `org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration` `org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration`| +|`@JooqTest`|`org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration` `org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration` `org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration` `org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration` `org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration`| +|`@JsonTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration` `org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration` `org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration` `org.springframework.boot.test.autoconfigure.json.JsonTestersAutoConfiguration`| +|`@RestClientTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration` `org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration` `org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration` `org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration` `org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration` `org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration` `org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration` `org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerAutoConfiguration` `org.springframework.boot.test.autoconfigure.web.client.WebClientRestTemplateAutoConfiguration`| +|`@WebFluxTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration` `org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration` `org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration` `org.springframework.boot.test.autoconfigure.web.reactive.WebTestClientAutoConfiguration`| +|`@WebMvcTest`|`org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration` `org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration` `org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration` `org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration` `org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration` `org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration` `org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration` `org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration` `org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration` `org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration` `org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration` `org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration` `org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration` `org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration` `org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration` `org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityAutoConfiguration` `org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration` `org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration`| diff --git a/X. Appendices/E. The Executable Jar Format.md b/X. Appendices/E. The Executable Jar Format.md new file mode 100644 index 00000000..3eeb94c1 --- /dev/null +++ b/X. Appendices/E. The Executable Jar Format.md @@ -0,0 +1,5 @@ +### 附录 E. 可执行Jar格式 + +`spring-boot-loader`模块允许Spring Boot对可执行jar和war文件的支持。如果你正在使用Maven或Gradle插件,可执行jar会被自动产生,通常你不需要了解它是如何工作的。 + +如果你需要从一个不同的构建系统创建可执行jars,或你只是对底层技术好奇,本章节将提供一些背景资料。 diff --git a/X. Appendices/E. The executable jar format.md b/X. Appendices/E. The executable jar format.md deleted file mode 100644 index 0168ff11..00000000 --- a/X. Appendices/E. The executable jar format.md +++ /dev/null @@ -1,5 +0,0 @@ -### 附录 E. 可执行jar格式 - -`spring-boot-loader`模块允许Spring Boot对可执行jar和war文件的支持。如果你正在使用Maven或Gradle插件,可执行jar会被自动产生,通常你不需要了解它是如何工作的。 - -如果你需要从一个不同的构建系统创建可执行jars,或你只是对底层技术好奇,本章节将提供一些背景资料。 diff --git a/X. Appendices/E.1. Nested JARs.md b/X. Appendices/E.1. Nested JARs.md index 174181c7..378ba4d2 100644 --- a/X. Appendices/E.1. Nested JARs.md +++ b/X. Appendices/E.1. Nested JARs.md @@ -1,5 +1,5 @@ ### 附录 E.1. 内嵌JARs -Java没有提供任何标准的方式来加载内嵌的jar文件(也就是jar文件自身包含到一个jar中)。如果你正分发一个在不解压缩的情况下可以从命令行运行的自包含应用,那这将是个问题。 +Java没有提供任何标准的方式来加载内嵌的jar文件(也就是jar文件自身包含到一个jar中)。如果你需要分发一个在不解压缩的情况下可以从命令行运行的自包含应用,那这将是个问题。 -为了解决这个问题,很多开发者使用"影子" jars。一个影子jar只是简单的将所有jars的类打包进一个单独的"超级jar"。使用影子jars的问题是它很难分辨在你的应用中实际可以使用的库。在多个jars中存在相同的文件名(内容不同)也是一个问题。Spring Boot另辟蹊径,让你能够直接嵌套jars。 +为了解决这个问题,很多开发者使用"影子" jars。一个影子jar将所有jars的类打包进一个单独的"超级jar"。使用影子jars的问题是它很难分辨在你的应用中实际可以使用的库。在多个jars中存在相同的文件名(内容不同)也是一个问题。Spring Boot另辟蹊径,让你能够直接嵌套jars。 diff --git a/X. Appendices/E.1.1. The Executable Jar File Structure.md b/X. Appendices/E.1.1. The Executable Jar File Structure.md new file mode 100644 index 00000000..db19898c --- /dev/null +++ b/X. Appendices/E.1.1. The Executable Jar File Structure.md @@ -0,0 +1,24 @@ +### 附录 E.1.1 可执行Jar文件结构 + +Spring Boot Loader兼容的jar文件应该遵循以下结构: + +```java +example.jar + | + +-META-INF + | +-MANIFEST.MF + +-org + | +-springframework + | +-boot + | +-loader + | +- + +-BOOT-INF + +-classes + | +-mycompany + | +-project + | +-YourClasses.class + +-lib + +-dependency1.jar + +-dependency2.jar +``` +应用类需要放在内嵌的`BOOT-INF/classes`目录下。依赖需要放在内嵌的`BOOT-INF/lib`目录下。 diff --git a/X. Appendices/E.1.1. The executable jar file structure.md b/X. Appendices/E.1.1. The executable jar file structure.md deleted file mode 100644 index adbd56ea..00000000 --- a/X. Appendices/E.1.1. The executable jar file structure.md +++ /dev/null @@ -1,24 +0,0 @@ -### 附录 E.1.1 可执行jar文件结构 - -Spring Boot Loader兼容的jar文件应该遵循以下结构: - -```java -example.jar - | - +-META-INF - | +-MANIFEST.MF - +-org - | +-springframework - | +-boot - | +-loader - | +- - +-BOOT-INF - +-classes - | +-mycompany - | +-project - | +-YourClasses.class - +-lib - +-dependency1.jar - +-dependency2.jar -``` -应用类需要放在内嵌的`BOOT-INF/classes`目录下。依赖需要放在内嵌的`BOOT-INF/lib`目录下。 diff --git a/X. Appendices/E.1.2. The Executable War File Structure.md b/X. Appendices/E.1.2. The Executable War File Structure.md new file mode 100644 index 00000000..3fa4f422 --- /dev/null +++ b/X. Appendices/E.1.2. The Executable War File Structure.md @@ -0,0 +1,27 @@ +### 附录 E.1.2. 可执行War文件结构 + +Spring Boot Loader兼容的war文件应该遵循以下结构: +```java +example.war + | + +-META-INF + | +-MANIFEST.MF + +-org + | +-springframework + | +-boot + | +-loader + | +- + +-WEB-INF + +-classes + | +-com + | +-mycompany + | +-project + | +-YourClasses.class + +-lib + | +-dependency1.jar + | +-dependency2.jar + +-lib-provided + +-servlet-api.jar + +-dependency3.jar +``` +依赖需要放到内嵌的`WEB-INF/lib`目录下。任何运行时需要但部署到普通web容器不需要的依赖应该放到`WEB-INF/lib-provided`目录下。 diff --git a/X. Appendices/E.1.2. The executable war file structure.md b/X. Appendices/E.1.2. The executable war file structure.md deleted file mode 100644 index 1f87fa0d..00000000 --- a/X. Appendices/E.1.2. The executable war file structure.md +++ /dev/null @@ -1,27 +0,0 @@ -### 附录 E.1.2. 可执行war文件结构 - -Spring Boot Loader兼容的war文件应该遵循以下结构: -```java -example.war - | - +-META-INF - | +-MANIFEST.MF - +-org - | +-springframework - | +-boot - | +-loader - | +- - +-WEB-INF - +-classes - | +-com - | +-mycompany - | +-project - | +-YourClasses.class - +-lib - | +-dependency1.jar - | +-dependency2.jar - +-lib-provided - +-servlet-api.jar - +-dependency3.jar -``` -依赖需要放到内嵌的`WEB-INF/lib`目录下。任何运行时需要但部署到普通web容器不需要的依赖应该放到`WEB-INF/lib-provided`目录下。 diff --git "a/X. Appendices/E.2. Spring Boot\342\200\231s \342\200\234JarFile\342\200\235 class.md" "b/X. Appendices/E.2. Spring Boot\342\200\231s \342\200\234JarFile\342\200\235 Class.md" similarity index 100% rename from "X. Appendices/E.2. Spring Boot\342\200\231s \342\200\234JarFile\342\200\235 class.md" rename to "X. Appendices/E.2. Spring Boot\342\200\231s \342\200\234JarFile\342\200\235 Class.md" diff --git "a/X. Appendices/E.2.1. Compatibility with the Standard Java \342\200\234JarFile\342\200\235.md" "b/X. Appendices/E.2.1. Compatibility with the Standard Java \342\200\234JarFile\342\200\235.md" new file mode 100644 index 00000000..70bf9284 --- /dev/null +++ "b/X. Appendices/E.2.1. Compatibility with the Standard Java \342\200\234JarFile\342\200\235.md" @@ -0,0 +1,3 @@ +### 附录 E.2.1 对标准Java "JarFile"的兼容性 + +Spring Boot Loader努力保持对已有代码和库的兼容。`org.springframework.boot.loader.jar.JarFile`继承自`java.util.jar.JarFile`,可以作为降级替换。`getURL()`方法返回一个与`java.net.JarURLConnection`兼容的`URL`,并可与Java的`URLClassLoader`一起使用。 diff --git "a/X. Appendices/E.2.1. Compatibility with the standard Java \342\200\234JarFile\342\200\235.md" "b/X. Appendices/E.2.1. Compatibility with the standard Java \342\200\234JarFile\342\200\235.md" deleted file mode 100644 index b2ae99d7..00000000 --- "a/X. Appendices/E.2.1. Compatibility with the standard Java \342\200\234JarFile\342\200\235.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 附录 E.2.1 对标准Java "JarFile"的兼容性 - -Spring Boot Loader努力保持对已有代码和库的兼容。`org.springframework.boot.loader.jar.JarFile`继承自`java.util.jar.JarFile`,可以作为降级替换。 diff --git a/X. Appendices/E.3. Launching Executable Jars.md b/X. Appendices/E.3. Launching Executable Jars.md new file mode 100644 index 00000000..f08363dc --- /dev/null +++ b/X. Appendices/E.3. Launching Executable Jars.md @@ -0,0 +1,5 @@ +### 附录 E.3. 启动可执行jars + +`org.springframework.boot.loader.Launcher`类是个特殊的启动类,用于一个可执行jar的主要入口。它实际上就是你jar文件的`Main-Class`,并用来设置一个合适的`URLClassLoader`,最后调用你的`main()`方法。 + +这里有3个启动器子类(JarLauncher、WarLauncher和PropertiesLauncher)。它们的作用是从嵌套的jar或war文件目录中(相对于显示的从classpath)加载资源(.class文件等)。在`[Jar|War]Launcher`情况下,嵌套路径是固定的(`lib/*.jar`和war的`lib-provided/*.jar`),所以如果你需要很多其他jars只需添加到那些位置即可。PropertiesLauncher默认查找你应用存档的`lib/`目录,但你可以通过设置环境变量`LOADER_PATH`或application.properties中的`loader.path`来添加其他的位置(一个以逗号分隔的目录、存档或存档内的目录列表)。 diff --git a/X. Appendices/E.3. Launching executable jars.md b/X. Appendices/E.3. Launching executable jars.md deleted file mode 100644 index 2aa3a1ad..00000000 --- a/X. Appendices/E.3. Launching executable jars.md +++ /dev/null @@ -1,5 +0,0 @@ -### 附录 E.3. 启动可执行jars - -`org.springframework.boot.loader.Launcher`类是个特殊的启动类,用于一个可执行jars的主要入口。它实际上就是你jar文件的`Main-Class`,并用来设置一个合适的`URLClassLoader`,最后调用你的`main()`方法。 - -这里有3个启动器子类,JarLauncher,WarLauncher和PropertiesLauncher。它们的作用是从嵌套的jar或war文件目录中(相对于显示的从classpath)加载资源(.class文件等)。在`[Jar|War]Launcher`情况下,嵌套路径是固定的(`lib/*.jar`和war的`lib-provided/*.jar`),所以如果你需要很多其他jars只需添加到那些位置即可。PropertiesLauncher默认查找你应用存档的`lib/`目录,但你可以通过设置环境变量`LOADER_PATH`或application.properties中的`loader.path`来添加其他的位置(逗号分割的目录或存档列表)。 diff --git a/X. Appendices/E.3.1. Launcher Manifest.md b/X. Appendices/E.3.1. Launcher Manifest.md new file mode 100644 index 00000000..df10679b --- /dev/null +++ b/X. Appendices/E.3.1. Launcher Manifest.md @@ -0,0 +1,15 @@ +### 附录 E.3.1 Launcher Manifest + +你需要指定一个合适的Launcher作为`META-INF/MANIFEST.MF`的`Main-Class`属性。你实际想要启动的类(也就是你编写的包含main方法的类)需要在`Start-Class`属性中定义。 + +例如,这里有个典型的可执行jar文件的MANIFEST.MF: +```properties +Main-Class: org.springframework.boot.loader.JarLauncher +Start-Class: com.mycompany.project.MyApplication +``` +对于一个war文件,它可能是这样的: +```properties +Main-Class: org.springframework.boot.loader.WarLauncher +Start-Class: com.mycompany.project.MyApplication +``` +**注**:你不需要在manifest文件中指定`Class-Path`实体,classpath会从嵌套的jars中被推导出来。 diff --git a/X. Appendices/E.3.1. Launcher manifest.md b/X. Appendices/E.3.1. Launcher manifest.md deleted file mode 100644 index 6de74241..00000000 --- a/X. Appendices/E.3.1. Launcher manifest.md +++ /dev/null @@ -1,15 +0,0 @@ -### 附录 E.3.1 Launcher manifest - -你需要指定一个合适的Launcher作为`META-INF/MANIFEST.MF`的`Main-Class`属性。你实际想要启动的类(也就是你编写的包含main方法的类)需要在`Start-Class`属性中定义。 - -例如,这里有个典型的可执行jar文件的MANIFEST.MF: -```properties -Main-Class: org.springframework.boot.loader.JarLauncher -Start-Class: com.mycompany.project.MyApplication -``` -对于一个war文件,它可能是这样的: -```properties -Main-Class: org.springframework.boot.loader.WarLauncher -Start-Class: com.mycompany.project.MyApplication -``` -**注**:你不需要在manifest文件中指定`Class-Path`实体,classpath会从嵌套的jars中被推导出来。 diff --git a/X. Appendices/E.3.2. Exploded Archives.md b/X. Appendices/E.3.2. Exploded Archives.md new file mode 100644 index 00000000..43d554e7 --- /dev/null +++ b/X. Appendices/E.3.2. Exploded Archives.md @@ -0,0 +1,7 @@ +### 附录 E.3.2. 暴露的存档 + +一些PaaS实现可能选择在运行前先解压存档。例如,Cloud Foundry就是这样操作的。你可以运行一个解压的存档,只需简单的启动合适的启动器: +```shell +$ unzip -q myapp.jar +$ java org.springframework.boot.loader.JarLaunche +``` diff --git a/X. Appendices/E.3.2. Exploded archives.md b/X. Appendices/E.3.2. Exploded archives.md deleted file mode 100644 index bd7e3b21..00000000 --- a/X. Appendices/E.3.2. Exploded archives.md +++ /dev/null @@ -1,8 +0,0 @@ -### 附录 E.3.2. 暴露的存档 - -一些PaaS实现可能选择在运行前先解压存档。例如,Cloud Foundry就是这样操作的。你可以运行一个解压的存档,只需简单的启动合适的启动器: -```shell -$ unzip -q myapp.jar -$ java org.springframework.boot.loader.JarLaunche -``` - diff --git a/X. Appendices/E.4. PropertiesLauncher Features.md b/X. Appendices/E.4. PropertiesLauncher Features.md index 8652a90a..62aeb44f 100644 --- a/X. Appendices/E.4. PropertiesLauncher Features.md +++ b/X. Appendices/E.4. PropertiesLauncher Features.md @@ -1,21 +1,36 @@ ### 附录 E.4. PropertiesLauncher特性 -PropertiesLauncher有一些特殊的性质,它们可以通过外部属性来启用(系统属性,环境变量,manifest实体或application.properties)。 +PropertiesLauncher有一些特殊的性质,它们可以通过外部属性来启用(系统属性、环境变量、manifest实体或application.properties)。下面的表格描述了这些属性: -|Key|作用| +|键|作用| |----|:-----| -|loader.path|逗号分割的classpath,比如`lib:${HOME}/app/lib`| -|loader.home|其他属性文件的位置,比如[/opt/app](file:///opt/app)(默认为`${user.dir}`)| -|loader.args|main方法的默认参数(以空格分割)| -|loader.main|要启动的main类名称,比如`com.app.Application`| -|loader.config.name|属性文件名,比如loader(默认为application)| -|loader.config.location|属性文件路径,比如`classpath:loader.properties`(默认为application.properties)| -|loader.system|布尔标识,表明所有的属性都应该添加到系统属性中(默认为false)| +|`loader.path`|逗号分隔的classpath,比如`lib,${HOME}/app/lib`。前面的条目优先,就像`javac`命令行中的常规`-classpath`一样。| +|`loader.home`|用于解析`loader.path`中的相对路径。例如,给定`loader.path=lib`,那么`${loader.home}/lib`是一个类路径位置(以及该目录中的所有 jar文件)。这个属性也用于定位`loader.properties`文件,就像下面的例子`/opt/app`,它的默认值是`${user.dir}`。| +|`loader.args`|main方法的默认参数(以空格分隔)| +|`loader.main`|要启动的main类名称,比如`com.app.Application`| +|`loader.config.name`|属性文件名,比如loader(默认为application)| +|`loader.config.location`|属性文件路径,比如`classpath:loader.properties`(默认为application.properties)| +|`loader.system`|布尔标识,表明所有的属性都应该添加到系统属性中(默认为false)| -Manifest实体keys通过大写单词首字母及将分隔符从"."改为"-"(比如`Loader-Path`)来进行格式化。`loader.main`是个特例,它是通过查找manifest的`Start-Class`,这样也兼容JarLauncher。 +当指定为环境变量或清单条目时,应使用以下名称: -环境变量可以大写字母并且用下划线代替句号。 +|键|清单条目|环境变量| +|----|:-----|:-----| +|`loader.path`|`Loader-Path`|`LOADER_PATH`| +|`loader.home`|`Loader-Home`|`LOADER_HOME`| +|`loader.args`|`Loader-Args`|`LOADER_ARGS`| +|`loader.main`|`Start-Class`|`LOADER_MAIN`| +|`loader.config.location`|`Loader-Config-Location`|`LOADER_CONFIG_LOCATION`| +|`loader.system`|`Loader-System`|`LOADER_SYSTEM`| -* `loader.home`是其他属性文件(覆盖默认)的目录位置,只要没有指定`loader.config.location`。 -* `loader.path`可以包含目录(递归地扫描jar和zip文件),存档路径或通配符模式(针对默认的JVM行为)。 -* 占位符在使用前会被系统和环境变量加上属性文件本身的值替换掉。 +**注** 构建插件在胖子jar构建时,会自动将`Main-Class`属性移动到`Start-Class`。如果使用这个,请指定要启动的类的名称,使用`Main-Class`属性而省略`Start-Class`。 + +以下规则适用于使用`PropertiesLauncher`工作: + +- `loader.properties`在`loader.home`中搜索,然后在类路径的根目录中搜索,然后在`classpath:/BOOT-INF/classes`中搜索。首先使用的是存在该名称的文件的第一个位置。 +- `loader.home`是一个额外的属性文件的目录位置(覆盖了默认值),只有在没有指定`loader.config.location`时才会使用。 +- `loader.path`可以包含目录(递归地扫描jar和zip文件)、归档路径、归档中的目录(例如,`dependencies.jar!/lib`)或通配符模式(用于默认的JVM行为)。存档路径可以是相对于`loader.home`或文件系统中任何带有`jar:file:`前缀的地方。 +- `loader.path`(如果为空) 默认为`BOOT-INF/lib`(意思是本地目录,如果从归档中运行,则为嵌套目录)。因此,当没有提供额外的配置时,`PropertiesLauncher`的行为与`JarLauncher`相同。 +- `loader.path`不能用来配置`loader.properties`的位置(当启动`PropertiesLauncher`时,用于搜索后者的类路径是JVM的类路径)。 +- 在使用前,从System和环境变量加上properties文件本身的所有值上进行占位符替换。 +- 对属性的搜索顺序(在不止一个地方查找是有意义的)是环境变量、系统属性、`loader.properties`和档案清单。 diff --git a/X. Appendices/E.5. Executable Jar Restrictions.md b/X. Appendices/E.5. Executable Jar Restrictions.md new file mode 100644 index 00000000..b9902647 --- /dev/null +++ b/X. Appendices/E.5. Executable Jar Restrictions.md @@ -0,0 +1,6 @@ +### 附录 E.5. 可执行jar的限制 + +在使用Spring Boot Loader打包的应用程序时,您需要考虑以下限制: + +- Zip条目压缩:嵌套jar的`ZipEntry`必须通过使用`ZipEntry.STORED`方法保存。这是必要的,这样我们就可以直接搜索到嵌套jar中的单个内容。嵌套jar文件本身的内容仍然可以被压缩,外部jar中的任何其他条目也可以被压缩。 +- 系统类加载器:已启动的应用程序在加载类时应该使用`Thread.getContextClassLoader()`(大多数库和框架默认都是这样做的)。试图用`ClassLoader.getSystemClassLoader()`加载嵌套的jar类会失败,`java.util.Logging`总是使用系统类加载器。为此,你应该考虑使用不同的日志实现。 diff --git a/X. Appendices/E.5. Executable jar restrictions.md b/X. Appendices/E.5. Executable jar restrictions.md deleted file mode 100644 index 556a8b33..00000000 --- a/X. Appendices/E.5. Executable jar restrictions.md +++ /dev/null @@ -1,4 +0,0 @@ -### 附录 E.5. 可执行jar的限制 - -当使用Spring Boot Loader打包的应用时有一些你需要考虑的限制。 - diff --git a/X. Appendices/E.5.1. Zip entry compression.md b/X. Appendices/E.5.1. Zip entry compression.md deleted file mode 100644 index b5236529..00000000 --- a/X. Appendices/E.5.1. Zip entry compression.md +++ /dev/null @@ -1,3 +0,0 @@ -### 附录 E.5.1 Zip实体压缩 - -对于一个嵌套jar的ZipEntry必须使用`ZipEntry.STORED`方法保存。这是需要的,这样我们可以直接查找嵌套jar中的个别内容。嵌套jar的内容本身可以仍旧被压缩,正如外部jar的其他任何实体。 diff --git a/X. Appendices/E.5.2. System ClassLoader.md b/X. Appendices/E.5.2. System ClassLoader.md deleted file mode 100644 index e23fef6b..00000000 --- a/X. Appendices/E.5.2. System ClassLoader.md +++ /dev/null @@ -1,3 +0,0 @@ -### 附录 E.5.2. 系统ClassLoader - -启动的应用在加载类时应该使用`Thread.getContextClassLoader()`(多数库和框架都默认这样做)。尝试通过`ClassLoader.getSystemClassLoader()`加载嵌套的类将失败。请注意`java.util.Logging`总是使用系统类加载器,由于这个原因你需要考虑一个不同的日志实现。 diff --git a/X. Appendices/E.6. Alternative Single Jar Solutions.md b/X. Appendices/E.6. Alternative Single Jar Solutions.md new file mode 100644 index 00000000..add39309 --- /dev/null +++ b/X. Appendices/E.6. Alternative Single Jar Solutions.md @@ -0,0 +1,7 @@ +### 附录 E.6. 可替代的单一jar解决方案 + +如果之前的限制造成你不能使用Spring Boot Loader,那可以考虑以下的替代方案: + +* [Maven Shade Plugin](https://maven.apache.org/plugins/maven-shade-plugin/) +* [JarClassLoader](http://www.jdotsoft.com/JarClassLoader.php) +* [OneJar](http://one-jar.sourceforge.net/) diff --git a/X. Appendices/E.6. Alternative single jar solutions.md b/X. Appendices/E.6. Alternative single jar solutions.md deleted file mode 100644 index e13a24f8..00000000 --- a/X. Appendices/E.6. Alternative single jar solutions.md +++ /dev/null @@ -1,7 +0,0 @@ -### 附录 E.6. 可替代的单一jar解决方案 - -如果以上限制造成你不能使用Spring Boot Loader,那可以考虑以下的替代方案: - -* [Maven Shade Plugin](http://maven.apache.org/plugins/maven-shade-plugin/) -* [JarClassLoader](http://www.jdotsoft.com/JarClassLoader.php) -* [OneJar](http://one-jar.sourceforge.net/) diff --git a/X. Appendices/F. Dependency versions.md b/X. Appendices/F. Dependency versions.md index c5d44295..6c684b2c 100644 --- a/X. Appendices/F. Dependency versions.md +++ b/X. Appendices/F. Dependency versions.md @@ -1,3 +1,687 @@ ### 附录 F. 依赖版本 -下面的表格提供了详尽的依赖版本信息,这些版本由Spring Boot自身的CLI,Maven的依赖管理(dependency management)和Gradle插件提供。当你声明一个对以下artifacts的依赖而没有声明版本时,将使用下面表格中列出的版本。 +下表提供了Spring Boot在其CLI(命令行接口)、Maven依赖关系管理和Gradle插件中提供的所有依赖版本的详细信息。当你在没有声明版本的情况下声明对这些artifact中的一个依赖关系时,将使用表中列出的版本。 + +|Group ID|Artifact ID|版本| +|----|:-----|:-----| +|antlr|antlr|2.7.7| +|ch.qos.logback|logback-access|1.2.3| +|ch.qos.logback|logback-classic|1.2.3| +|ch.qos.logback|logback-core|1.2.3| +|com.atomikos|transactions-jdbc|4.0.6| +|com.atomikos|transactions-jms|4.0.6| +|com.atomikos|transactions-jta|4.0.6| +|com.couchbase.client|couchbase-spring-cache|2.1.0| +|com.couchbase.client|java-client|2.5.5| +|com.datastax.cassandra|cassandra-driver-core|3.4.0| +|com.datastax.cassandra|cassandra-driver-mapping|3.4.0| +|com.fasterxml|classmate|1.3.4| +|com.fasterxml.jackson.core|jackson-annotations|2.9.0| +|com.fasterxml.jackson.core|jackson-core|2.9.4| +|com.fasterxml.jackson.core|jackson-databind|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-avro|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-cbor|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-csv|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-ion|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-properties|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-protobuf|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-smile|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-xml|2.9.4| +|com.fasterxml.jackson.dataformat|jackson-dataformat-yaml|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-guava|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-hibernate3|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-hibernate4|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-hibernate5|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-hppc|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-jaxrs|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-jdk8|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-joda|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-json-org|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-jsr310|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-jsr353|2.9.4| +|com.fasterxml.jackson.datatype|jackson-datatype-pcollections|2.9.4| +|com.fasterxml.jackson.jaxrs|jackson-jaxrs-base|2.9.4| +|com.fasterxml.jackson.jaxrs|jackson-jaxrs-cbor-provider|2.9.4| +|com.fasterxml.jackson.jaxrs|jackson-jaxrs-json-provider|2.9.4| +|com.fasterxml.jackson.jaxrs|jackson-jaxrs-smile-provider|2.9.4| +|com.fasterxml.jackson.jaxrs|jackson-jaxrs-xml-provider|2.9.4| +|com.fasterxml.jackson.jaxrs|jackson-jaxrs-yaml-provider|2.9.4| +|com.fasterxml.jackson.jr|jackson-jr-all|2.9.4| +|com.fasterxml.jackson.jr|jackson-jr-objects|2.9.4| +|com.fasterxml.jackson.jr|jackson-jr-retrofit2|2.9.4| +|com.fasterxml.jackson.jr|jackson-jr-stree|2.9.4| +|com.fasterxml.jackson.module|jackson-module-afterburner|2.9.4| +|com.fasterxml.jackson.module|jackson-module-guice|2.9.4| +|com.fasterxml.jackson.module|jackson-module-jaxb-annotations|2.9.4| +|com.fasterxml.jackson.module|jackson-module-jsonSchema|2.9.4| +|com.fasterxml.jackson.module|jackson-module-kotlin|2.9.4| +|com.fasterxml.jackson.module|jackson-module-mrbean|2.9.4| +|com.fasterxml.jackson.module|jackson-module-osgi|2.9.4| +|com.fasterxml.jackson.module|jackson-module-parameter-names|2.9.4| +|com.fasterxml.jackson.module|jackson-module-paranamer|2.9.4| +|com.fasterxml.jackson.module|jackson-module-scala_2.10|2.9.4| +|com.fasterxml.jackson.module|jackson-module-scala_2.11|2.9.4| +|com.fasterxml.jackson.module|jackson-module-scala_2.12|2.9.4| +|com.github.ben-manes.caffeine|caffeine|2.6.2| +|com.github.mxab.thymeleaf.extras|thymeleaf-extras-data-attribute|2.0.1| +|com.google.appengine|appengine-api-1.0-sdk|1.9.62| +|com.google.code.gson|gson|2.8.2| +|com.googlecode.json-simple|json-simple|1.1.1| +|com.h2database|h2|1.4.196| +|com.hazelcast|hazelcast|3.9.3| +|com.hazelcast|hazelcast-client|3.9.3| +|com.hazelcast|hazelcast-hibernate52|1.2.3| +|com.hazelcast|hazelcast-spring|3.9.3| +|com.jayway.jsonpath|json-path|2.4.0| +|com.jayway.jsonpath|json-path-assert|2.4.0| +|com.microsoft.sqlserver|mssql-jdbc|6.2.2.jre8| +|com.querydsl|querydsl-apt|4.1.4| +|com.querydsl|querydsl-collections|4.1.4| +|com.querydsl|querydsl-core|4.1.4| +|com.querydsl|querydsl-jpa|4.1.4| +|com.querydsl|querydsl-mongodb|4.1.4| +|com.rabbitmq|amqp-client|5.1.2| +|com.samskivert|jmustache|1.14| +|com.sendgrid|sendgrid-java|4.1.2| +|com.sun.mail|javax.mail|1.6.1| +|com.timgroup|java-statsd-client|3.1.0| +|com.unboundid|unboundid-ldapsdk|4.0.4| +|com.zaxxer|HikariCP|2.7.8| +|commons-codec|commons-codec|1.11| +|commons-pool|commons-pool|1.6| +|de.flapdoodle.embed|de.flapdoodle.embed.mongo|2.0.3| +|dom4j|dom4j|1.6.1| +|io.dropwizard.metrics|metrics-annotation|3.2.6| +|io.dropwizard.metrics|metrics-core|3.2.6| +|io.dropwizard.metrics|metrics-ehcache|3.2.6| +|io.dropwizard.metrics|metrics-ganglia|3.2.6| +|io.dropwizard.metrics|metrics-graphite|3.2.6| +|io.dropwizard.metrics|metrics-healthchecks|3.2.6| +|io.dropwizard.metrics|metrics-httpasyncclient|3.2.6| +|io.dropwizard.metrics|metrics-jdbi|3.2.6| +|io.dropwizard.metrics|metrics-jersey|3.2.6| +|io.dropwizard.metrics|metrics-jersey2|3.2.6| +|io.dropwizard.metrics|metrics-jetty8|3.2.6| +|io.dropwizard.metrics|metrics-jetty9|3.2.6| +|io.dropwizard.metrics|metrics-jetty9-legacy|3.2.6| +|io.dropwizard.metrics|metrics-json|3.2.6| +|io.dropwizard.metrics|metrics-jvm|3.2.6| +|io.dropwizard.metrics|metrics-log4j|3.2.6| +|io.dropwizard.metrics|metrics-log4j2|3.2.6| +|io.dropwizard.metrics|metrics-logback|3.2.6| +|io.dropwizard.metrics|metrics-servlet|3.2.6| +|io.dropwizard.metrics|metrics-servlets|3.2.6| +|io.lettuce|lettuce-core|5.0.2.RELEASE| +|io.micrometer|micrometer-core|1.0.1| +|io.micrometer|micrometer-registry-atlas|1.0.1| +|io.micrometer|micrometer-registry-datadog|1.0.1| +|io.micrometer|micrometer-registry-ganglia|1.0.1| +|io.micrometer|micrometer-registry-graphite|1.0.1| +|io.micrometer|micrometer-registry-influx|1.0.1| +|io.micrometer|micrometer-registry-jmx|1.0.1| +|io.micrometer|micrometer-registry-new-relic|1.0.1| +|io.micrometer|micrometer-registry-prometheus|1.0.1| +|io.micrometer|micrometer-registry-signalfx|1.0.1| +|io.micrometer|micrometer-registry-statsd|1.0.1| +|io.micrometer|micrometer-registry-wavefront|1.0.1| +|io.netty|netty-all|4.1.22.Final| +|io.netty|netty-buffer|4.1.22.Final| +|io.netty|netty-codec|4.1.22.Final| +|io.netty|netty-codec-dns|4.1.22.Final| +|io.netty|netty-codec-haproxy|4.1.22.Final| +|io.netty|netty-codec-http|4.1.22.Final| +|io.netty|netty-codec-http2|4.1.22.Final| +|io.netty|netty-codec-memcache|4.1.22.Final| +|io.netty|netty-codec-mqtt|4.1.22.Final| +|io.netty|netty-codec-redis|4.1.22.Final| +|io.netty|netty-codec-smtp|4.1.22.Final| +|io.netty|netty-codec-socks|4.1.22.Final| +|io.netty|netty-codec-stomp|4.1.22.Final| +|io.netty|netty-codec-xml|4.1.22.Final| +|io.netty|netty-common|4.1.22.Final| +|io.netty|netty-dev-tools|4.1.22.Final| +|io.netty|netty-example|4.1.22.Final| +|io.netty|netty-handler|4.1.22.Final| +|io.netty|netty-handler-proxy|4.1.22.Final| +|io.netty|netty-resolver|4.1.22.Final| +|io.netty|netty-resolver-dns|4.1.22.Final| +|io.netty|netty-transport|4.1.22.Final| +|io.netty|netty-transport-native-epoll|4.1.22.Final| +|io.netty|netty-transport-native-kqueue|4.1.22.Final| +|io.netty|netty-transport-native-unix-common|4.1.22.Final| +|io.netty|netty-transport-rxtx|4.1.22.Final| +|io.netty|netty-transport-sctp|4.1.22.Final| +|io.netty|netty-transport-udt|4.1.22.Final| +|io.projectreactor|reactor-core|3.1.5.RELEASE| +|io.projectreactor|reactor-test|3.1.5.RELEASE| +|io.projectreactor.addons|reactor-adapter|3.1.6.RELEASE| +|io.projectreactor.addons|reactor-extra|3.1.6.RELEASE| +|io.projectreactor.addons|reactor-logback|3.1.6.RELEASE| +|io.projectreactor.ipc|reactor-netty|0.7.5.RELEASE| +|io.projectreactor.kafka|reactor-kafka|1.0.0.RELEASE| +|io.reactivex|rxjava|1.3.6| +|io.reactivex|rxjava-reactive-streams|1.2.1| +|io.reactivex.rxjava2|rxjava|2.1.10| +|io.rest-assured|json-path|3.0.7| +|io.rest-assured|json-schema-validator|3.0.7| +|io.rest-assured|rest-assured|3.0.7| +|io.rest-assured|scala-support|3.0.7| +|io.rest-assured|spring-mock-mvc|3.0.7| +|io.rest-assured|xml-path|3.0.7| +|io.searchbox|jest|5.3.3| +|io.undertow|undertow-core|1.4.22.Final| +|io.undertow|undertow-servlet|1.4.22.Final| +|io.undertow|undertow-websockets-jsr|1.4.22.Final| +|javax.annotation|javax.annotation-api|1.3.2| +|javax.cache|cache-api|1.1.0| +|javax.jms|javax.jms-api|2.0.1| +|javax.json|javax.json-api|1.1.2| +|javax.json.bind|javax.json.bind-api|1| +|javax.mail|javax.mail-api|1.6.1| +|javax.money|money-api|1.0.1| +|javax.servlet|javax.servlet-api|3.1.0| +|javax.servlet|jstl|1.2| +|javax.transaction|javax.transaction-api|1.2| +|javax.validation|validation-api|2.0.1.Final| +|javax.xml.bind|jaxb-api|2.3.0| +|jaxen|jaxen|1.1.6| +|joda-time|joda-time|2.9.9| +|junit|junit|4.12| +|mysql|mysql-connector-java|5.1.45| +|net.bytebuddy|byte-buddy|1.7.10| +|net.bytebuddy|byte-buddy-agent|1.7.10| +|net.java.dev.jna|jna|4.5.1| +|net.java.dev.jna|jna-platform|4.5.1| +|net.sf.ehcache|ehcache|2.10.4| +|net.sourceforge.htmlunit|htmlunit|2.29| +|net.sourceforge.jtds|jtds|1.3.1| +|net.sourceforge.nekohtml|nekohtml|1.9.22| +|nz.net.ultraq.thymeleaf|thymeleaf-layout-dialect|2.3.0| +|org.apache.activemq|activemq-amqp|5.15.3| +|org.apache.activemq|activemq-blueprint|5.15.3| +|org.apache.activemq|activemq-broker|5.15.3| +|org.apache.activemq|activemq-camel|5.15.3| +|org.apache.activemq|activemq-client|5.15.3| +|org.apache.activemq|activemq-console|5.15.3| +|org.apache.activemq|activemq-http|5.15.3| +|org.apache.activemq|activemq-jaas|5.15.3| +|org.apache.activemq|activemq-jdbc-store|5.15.3| +|org.apache.activemq|activemq-jms-pool|5.15.3| +|org.apache.activemq|activemq-kahadb-store|5.15.3| +|org.apache.activemq|activemq-karaf|5.15.3| +|org.apache.activemq|activemq-leveldb-store|5.15.3| +|org.apache.activemq|activemq-log4j-appender|5.15.3| +|org.apache.activemq|activemq-mqtt|5.15.3| +|org.apache.activemq|activemq-openwire-generator|5.15.3| +|org.apache.activemq|activemq-openwire-legacy|5.15.3| +|org.apache.activemq|activemq-osgi|5.15.3| +|org.apache.activemq|activemq-partition|5.15.3| +|org.apache.activemq|activemq-pool|5.15.3| +|org.apache.activemq|activemq-ra|5.15.3| +|org.apache.activemq|activemq-run|5.15.3| +|org.apache.activemq|activemq-runtime-config|5.15.3| +|org.apache.activemq|activemq-shiro|5.15.3| +|org.apache.activemq|activemq-spring|5.15.3| +|org.apache.activemq|activemq-stomp|5.15.3| +|org.apache.activemq|activemq-web|5.15.3| +|org.apache.activemq|artemis-amqp-protocol|2.4.0| +|org.apache.activemq|artemis-commons|2.4.0| +|org.apache.activemq|artemis-core-client|2.4.0| +|org.apache.activemq|artemis-jms-client|2.4.0| +|org.apache.activemq|artemis-jms-server|2.4.0| +|org.apache.activemq|artemis-journal|2.4.0| +|org.apache.activemq|artemis-native|2.4.0| +|org.apache.activemq|artemis-selector|2.4.0| +|org.apache.activemq|artemis-server|2.4.0| +|org.apache.activemq|artemis-service-extensions|2.4.0| +|org.apache.commons|commons-dbcp2|2.2.0| +|org.apache.commons|commons-lang3|3.7| +|org.apache.commons|commons-pool2|2.5.0| +|org.apache.derby|derby|10.14.1.0| +|org.apache.httpcomponents|fluent-hc|4.5.5| +|org.apache.httpcomponents|httpasyncclient|4.1.3| +|org.apache.httpcomponents|httpclient|4.5.5| +|org.apache.httpcomponents|httpclient-cache|4.5.5| +|org.apache.httpcomponents|httpclient-osgi|4.5.5| +|org.apache.httpcomponents|httpclient-win|4.5.5| +|org.apache.httpcomponents|httpcore|4.4.9| +|org.apache.httpcomponents|httpcore-nio|4.4.9| +|org.apache.httpcomponents|httpmime|4.5.5| +|org.apache.johnzon|johnzon-jsonb|1.1.6| +|org.apache.logging.log4j|log4j-1.2-api|2.10.0| +|org.apache.logging.log4j|log4j-api|2.10.0| +|org.apache.logging.log4j|log4j-cassandra|2.10.0| +|org.apache.logging.log4j|log4j-core|2.10.0| +|org.apache.logging.log4j|log4j-couchdb|2.10.0| +|org.apache.logging.log4j|log4j-flume-ng|2.10.0| +|org.apache.logging.log4j|log4j-iostreams|2.10.0| +|org.apache.logging.log4j|log4j-jcl|2.10.0| +|org.apache.logging.log4j|log4j-jmx-gui|2.10.0| +|org.apache.logging.log4j|log4j-jul|2.10.0| +|org.apache.logging.log4j|log4j-liquibase|2.10.0| +|org.apache.logging.log4j|log4j-mongodb|2.10.0| +|org.apache.logging.log4j|log4j-slf4j-impl|2.10.0| +|org.apache.logging.log4j|log4j-taglib|2.10.0| +|org.apache.logging.log4j|log4j-to-slf4j|2.10.0| +|org.apache.logging.log4j|log4j-web|2.10.0| +|org.apache.solr|solr-analysis-extras|6.6.2| +|org.apache.solr|solr-analytics|6.6.2| +|org.apache.solr|solr-cell|6.6.2| +|org.apache.solr|solr-clustering|6.6.2| +|org.apache.solr|solr-core|6.6.2| +|org.apache.solr|solr-dataimporthandler|6.6.2| +|org.apache.solr|solr-dataimporthandler-extras|6.6.2| +|org.apache.solr|solr-langid|6.6.2| +|org.apache.solr|solr-solrj|6.6.2| +|org.apache.solr|solr-test-framework|6.6.2| +|org.apache.solr|solr-uima|6.6.2| +|org.apache.solr|solr-velocity|6.6.2| +|org.apache.tomcat|tomcat-annotations-api|8.5.28| +|org.apache.tomcat|tomcat-catalina-jmx-remote|8.5.28| +|org.apache.tomcat|tomcat-jdbc|8.5.28| +|org.apache.tomcat|tomcat-jsp-api|8.5.28| +|org.apache.tomcat.embed|tomcat-embed-core|8.5.28| +|org.apache.tomcat.embed|tomcat-embed-el|8.5.28| +|org.apache.tomcat.embed|tomcat-embed-jasper|8.5.28| +|org.apache.tomcat.embed|tomcat-embed-websocket|8.5.28| +|org.aspectj|aspectjrt|1.8.13| +|org.aspectj|aspectjtools|1.8.13| +|org.aspectj|aspectjweaver|1.8.13| +|org.assertj|assertj-core|3.9.1| +|org.codehaus.btm|btm|2.1.4| +|org.codehaus.groovy|groovy|2.4.13| +|org.codehaus.groovy|groovy-all|2.4.13| +|org.codehaus.groovy|groovy-ant|2.4.13| +|org.codehaus.groovy|groovy-bsf|2.4.13| +|org.codehaus.groovy|groovy-console|2.4.13| +|org.codehaus.groovy|groovy-docgenerator|2.4.13| +|org.codehaus.groovy|groovy-groovydoc|2.4.13| +|org.codehaus.groovy|groovy-groovysh|2.4.13| +|org.codehaus.groovy|groovy-jmx|2.4.13| +|org.codehaus.groovy|groovy-json|2.4.13| +|org.codehaus.groovy|groovy-jsr223|2.4.13| +|org.codehaus.groovy|groovy-nio|2.4.13| +|org.codehaus.groovy|groovy-servlet|2.4.13| +|org.codehaus.groovy|groovy-sql|2.4.13| +|org.codehaus.groovy|groovy-swing|2.4.13| +|org.codehaus.groovy|groovy-templates|2.4.13| +|org.codehaus.groovy|groovy-test|2.4.13| +|org.codehaus.groovy|groovy-testng|2.4.13| +|org.codehaus.groovy|groovy-xml|2.4.13| +|org.codehaus.janino|janino|3.0.8| +|org.eclipse.jetty|apache-jsp|9.4.8.v20171121| +|org.eclipse.jetty|apache-jstl|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-client|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-conscrypt-client|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-conscrypt-server|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-java-client|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-java-server|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-openjdk8-client|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-openjdk8-server|9.4.8.v20171121| +|org.eclipse.jetty|jetty-alpn-server|9.4.8.v20171121| +|org.eclipse.jetty|jetty-annotations|9.4.8.v20171121| +|org.eclipse.jetty|jetty-ant|9.4.8.v20171121| +|org.eclipse.jetty|jetty-client|9.4.8.v20171121| +|org.eclipse.jetty|jetty-continuation|9.4.8.v20171121| +|org.eclipse.jetty|jetty-deploy|9.4.8.v20171121| +|org.eclipse.jetty|jetty-distribution|9.4.8.v20171121| +|org.eclipse.jetty|jetty-hazelcast|9.4.8.v20171121| +|org.eclipse.jetty|jetty-home|9.4.8.v20171121| +|org.eclipse.jetty|jetty-http|9.4.8.v20171121| +|org.eclipse.jetty|jetty-http-spi|9.4.8.v20171121| +|org.eclipse.jetty|jetty-infinispan|9.4.8.v20171121| +|org.eclipse.jetty|jetty-io|9.4.8.v20171121| +|org.eclipse.jetty|jetty-jaas|9.4.8.v20171121| +|org.eclipse.jetty|jetty-jaspi|9.4.8.v20171121| +|org.eclipse.jetty|jetty-jmx|9.4.8.v20171121| +|org.eclipse.jetty|jetty-jndi|9.4.8.v20171121| +|org.eclipse.jetty|jetty-nosql|9.4.8.v20171121| +|org.eclipse.jetty|jetty-plus|9.4.8.v20171121| +|org.eclipse.jetty|jetty-proxy|9.4.8.v20171121| +|org.eclipse.jetty|jetty-quickstart|9.4.8.v20171121| +|org.eclipse.jetty|jetty-rewrite|9.4.8.v20171121| +|org.eclipse.jetty|jetty-security|9.4.8.v20171121| +|org.eclipse.jetty|jetty-server|9.4.8.v20171121| +|org.eclipse.jetty|jetty-servlet|9.4.8.v20171121| +|org.eclipse.jetty|jetty-servlets|9.4.8.v20171121| +|org.eclipse.jetty|jetty-spring|9.4.8.v20171121| +|org.eclipse.jetty|jetty-unixsocket|9.4.8.v20171121| +|org.eclipse.jetty|jetty-util|9.4.8.v20171121| +|org.eclipse.jetty|jetty-util-ajax|9.4.8.v20171121| +|org.eclipse.jetty|jetty-webapp|9.4.8.v20171121| +|org.eclipse.jetty|jetty-xml|9.4.8.v20171121| +|org.eclipse.jetty.cdi|cdi-core|9.4.8.v20171121| +|org.eclipse.jetty.cdi|cdi-full-servlet|9.4.8.v20171121| +|org.eclipse.jetty.cdi|cdi-servlet|9.4.8.v20171121| +|org.eclipse.jetty.fcgi|fcgi-client|9.4.8.v20171121| +|org.eclipse.jetty.fcgi|fcgi-server|9.4.8.v20171121| +|org.eclipse.jetty.gcloud|jetty-gcloud-session-manager|9.4.8.v20171121| +|org.eclipse.jetty.http2|http2-client|9.4.8.v20171121| +|org.eclipse.jetty.http2|http2-common|9.4.8.v20171121| +|org.eclipse.jetty.http2|http2-hpack|9.4.8.v20171121| +|org.eclipse.jetty.http2|http2-http-client-transport|9.4.8.v20171121| +|org.eclipse.jetty.http2|http2-server|9.4.8.v20171121| +|org.eclipse.jetty.memcached|jetty-memcached-sessions|9.4.8.v20171121| +|org.eclipse.jetty.orbit|javax.servlet.jsp|2.2.0.v201112011158| +|org.eclipse.jetty.osgi|jetty-httpservice|9.4.8.v20171121| +|org.eclipse.jetty.osgi|jetty-osgi-boot|9.4.8.v20171121| +|org.eclipse.jetty.osgi|jetty-osgi-boot-jsp|9.4.8.v20171121| +|org.eclipse.jetty.osgi|jetty-osgi-boot-warurl|9.4.8.v20171121| +|org.eclipse.jetty.websocket|javax-websocket-client-impl|9.4.8.v20171121| +|org.eclipse.jetty.websocket|javax-websocket-server-impl|9.4.8.v20171121| +|org.eclipse.jetty.websocket|websocket-api|9.4.8.v20171121| +|org.eclipse.jetty.websocket|websocket-client|9.4.8.v20171121| +|org.eclipse.jetty.websocket|websocket-common|9.4.8.v20171121| +|org.eclipse.jetty.websocket|websocket-server|9.4.8.v20171121| +|org.eclipse.jetty.websocket|websocket-servlet|9.4.8.v20171121| +|org.ehcache|ehcache|3.5.0| +|org.ehcache|ehcache-clustered|3.5.0| +|org.ehcache|ehcache-transactions|3.5.0| +|org.elasticsearch|elasticsearch|5.6.8| +|org.elasticsearch.client|transport|5.6.8| +|org.elasticsearch.plugin|transport-netty4-client|5.6.8| +|org.firebirdsql.jdbc|jaybird-jdk17|3.0.3| +|org.firebirdsql.jdbc|jaybird-jdk18|3.0.3| +|org.flywaydb|flyway-core|5.0.7| +|org.freemarker|freemarker|2.3.27-incubating| +|org.glassfish|javax.el|3.0.0| +|org.glassfish.jersey.containers|jersey-container-servlet|2.26| +|org.glassfish.jersey.containers|jersey-container-servlet-core|2.26| +|org.glassfish.jersey.core|jersey-client|2.26| +|org.glassfish.jersey.core|jersey-common|2.26| +|org.glassfish.jersey.core|jersey-server|2.26| +|org.glassfish.jersey.ext|jersey-bean-validation|2.26| +|org.glassfish.jersey.ext|jersey-entity-filtering|2.26| +|org.glassfish.jersey.ext|jersey-spring4|2.26| +|org.glassfish.jersey.media|jersey-media-jaxb|2.26| +|org.glassfish.jersey.media|jersey-media-json-jackson|2.26| +|org.glassfish.jersey.media|jersey-media-multipart|2.26| +|org.hamcrest|hamcrest-core|1.3| +|org.hamcrest|hamcrest-library|1.3| +|org.hibernate|hibernate-c3p0|5.2.14.Final| +|org.hibernate|hibernate-core|5.2.14.Final| +|org.hibernate|hibernate-ehcache|5.2.14.Final| +|org.hibernate|hibernate-entitymanager|5.2.14.Final| +|org.hibernate|hibernate-envers|5.2.14.Final| +|org.hibernate|hibernate-hikaricp|5.2.14.Final| +|org.hibernate|hibernate-infinispan|5.2.14.Final| +|org.hibernate|hibernate-java8|5.2.14.Final| +|org.hibernate|hibernate-jcache|5.2.14.Final| +|org.hibernate|hibernate-jpamodelgen|5.2.14.Final| +|org.hibernate|hibernate-proxool|5.2.14.Final| +|org.hibernate|hibernate-spatial|5.2.14.Final| +|org.hibernate|hibernate-testing|5.2.14.Final| +|org.hibernate.validator|hibernate-validator|6.0.7.Final| +|org.hibernate.validator|hibernate-validator-annotation-processor|6.0.7.Final| +|org.hsqldb|hsqldb|2.4.0| +|org.infinispan|infinispan-jcache|9.1.6.Final| +|org.infinispan|infinispan-spring4-common|9.1.6.Final| +|org.infinispan|infinispan-spring4-embedded|9.1.6.Final| +|org.influxdb|influxdb-java|2.9| +|org.jboss|jboss-transaction-spi|7.6.0.Final| +|org.jboss.logging|jboss-logging|3.3.2.Final| +|org.jboss.narayana.jta|jdbc|5.8.0.Final| +|org.jboss.narayana.jta|jms|5.8.0.Final| +|org.jboss.narayana.jta|jta|5.8.0.Final| +|org.jboss.narayana.jts|narayana-jts-integration|5.8.0.Final| +|org.jdom|jdom2|2.0.6| +|org.jetbrains.kotlin|kotlin-reflect|1.2.21| +|org.jetbrains.kotlin|kotlin-runtime|1.2.21| +|org.jetbrains.kotlin|kotlin-stdlib|1.2.21| +|org.jetbrains.kotlin|kotlin-stdlib-jdk7|1.2.21| +|org.jetbrains.kotlin|kotlin-stdlib-jdk8|1.2.21| +|org.jetbrains.kotlin|kotlin-stdlib-jre7|1.2.21| +|org.jetbrains.kotlin|kotlin-stdlib-jre8|1.2.21| +|org.jolokia|jolokia-core|1.5.0| +|org.jooq|jooq|3.10.5| +|org.jooq|jooq-codegen|3.10.5| +|org.jooq|jooq-meta|3.10.5| +|org.junit.jupiter|junit-jupiter-api|5.1.0| +|org.junit.jupiter|junit-jupiter-engine|5.1.0| +|org.liquibase|liquibase-core|3.5.5| +|org.mariadb.jdbc|mariadb-java-client|2.2.2| +|org.mockito|mockito-core|2.15.0| +|org.mockito|mockito-inline|2.15.0| +|org.mongodb|bson|3.6.3| +|org.mongodb|mongodb-driver|3.6.3| +|org.mongodb|mongodb-driver-async|3.6.3| +|org.mongodb|mongodb-driver-core|3.6.3| +|org.mongodb|mongodb-driver-reactivestreams|1.7.1| +|org.mongodb|mongo-java-driver|3.6.3| +|org.mortbay.jasper|apache-el|8.5.24.2| +|org.neo4j|neo4j-ogm-api|3.1.0| +|org.neo4j|neo4j-ogm-bolt-driver|3.1.0| +|org.neo4j|neo4j-ogm-core|3.1.0| +|org.neo4j|neo4j-ogm-http-driver|3.1.0| +|org.postgresql|postgresql|42.2.1| +|org.projectlombok|lombok|1.16.20| +|org.quartz-scheduler|quartz|2.3.0| +|org.reactivestreams|reactive-streams|1.0.2| +|org.seleniumhq.selenium|htmlunit-driver|2.29.2| +|org.seleniumhq.selenium|selenium-api|3.9.1| +|org.seleniumhq.selenium|selenium-chrome-driver|3.9.1| +|org.seleniumhq.selenium|selenium-edge-driver|3.9.1| +|org.seleniumhq.selenium|selenium-firefox-driver|3.9.1| +|org.seleniumhq.selenium|selenium-ie-driver|3.9.1| +|org.seleniumhq.selenium|selenium-java|3.9.1| +|org.seleniumhq.selenium|selenium-opera-driver|3.9.1| +|org.seleniumhq.selenium|selenium-remote-driver|3.9.1| +|org.seleniumhq.selenium|selenium-safari-driver|3.9.1| +|org.seleniumhq.selenium|selenium-support|3.9.1| +|org.skyscreamer|jsonassert|1.5.0| +|org.slf4j|jcl-over-slf4j|1.7.25| +|org.slf4j|jul-to-slf4j|1.7.25| +|org.slf4j|log4j-over-slf4j|1.7.25| +|org.slf4j|slf4j-api|1.7.25| +|org.slf4j|slf4j-ext|1.7.25| +|org.slf4j|slf4j-jcl|1.7.25| +|org.slf4j|slf4j-jdk14|1.7.25| +|org.slf4j|slf4j-log4j12|1.7.25| +|org.slf4j|slf4j-nop|1.7.25| +|org.slf4j|slf4j-simple|1.7.25| +|org.springframework|spring-aop|5.0.4.RELEASE| +|org.springframework|spring-aspects|5.0.4.RELEASE| +|org.springframework|spring-beans|5.0.4.RELEASE| +|org.springframework|spring-context|5.0.4.RELEASE| +|org.springframework|spring-context-indexer|5.0.4.RELEASE| +|org.springframework|spring-context-support|5.0.4.RELEASE| +|org.springframework|spring-core|5.0.4.RELEASE| +|org.springframework|spring-expression|5.0.4.RELEASE| +|org.springframework|spring-instrument|5.0.4.RELEASE| +|org.springframework|spring-jcl|5.0.4.RELEASE| +|org.springframework|spring-jdbc|5.0.4.RELEASE| +|org.springframework|spring-jms|5.0.4.RELEASE| +|org.springframework|spring-messaging|5.0.4.RELEASE| +|org.springframework|spring-orm|5.0.4.RELEASE| +|org.springframework|spring-oxm|5.0.4.RELEASE| +|org.springframework|spring-test|5.0.4.RELEASE| +|org.springframework|spring-tx|5.0.4.RELEASE| +|org.springframework|spring-web|5.0.4.RELEASE| +|org.springframework|spring-webflux|5.0.4.RELEASE| +|org.springframework|spring-webmvc|5.0.4.RELEASE| +|org.springframework|spring-websocket|5.0.4.RELEASE| +|org.springframework.amqp|spring-amqp|2.0.2.RELEASE| +|org.springframework.amqp|spring-rabbit|2.0.2.RELEASE| +|org.springframework.batch|spring-batch-core|4.0.0.RELEASE| +|org.springframework.batch|spring-batch-infrastructure|4.0.0.RELEASE| +|org.springframework.batch|spring-batch-integration|4.0.0.RELEASE| +|org.springframework.batch|spring-batch-test|4.0.0.RELEASE| +|org.springframework.boot|spring-boot|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-actuator|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-actuator-autoconfigure|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-autoconfigure|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-autoconfigure-processor|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-configuration-metadata|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-configuration-processor|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-devtools|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-loader|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-loader-tools|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-properties-migrator|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-activemq|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-actuator|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-amqp|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-aop|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-artemis|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-batch|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-cache|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-cloud-connectors|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-cassandra|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-cassandra-reactive|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-couchbase|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-couchbase-reactive|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-elasticsearch|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-jpa|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-ldap|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-mongodb|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-mongodb-reactive|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-neo4j|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-redis|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-redis-reactive|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-rest|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-data-solr|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-freemarker|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-groovy-templates|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-hateoas|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-integration|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-jdbc|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-jersey|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-jetty|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-jooq|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-json|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-jta-atomikos|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-jta-bitronix|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-jta-narayana|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-log4j2|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-logging|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-mail|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-mustache|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-quartz|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-reactor-netty|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-security|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-test|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-thymeleaf|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-tomcat|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-undertow|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-validation|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-web|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-webflux|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-web-services|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-starter-websocket|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-test|2.0.0.RELEASE| +|org.springframework.boot|spring-boot-test-autoconfigure|2.0.0.RELEASE| +|org.springframework.cloud|spring-cloud-cloudfoundry-connector|2.0.1.RELEASE| +|org.springframework.cloud|spring-cloud-connectors-core|2.0.1.RELEASE| +|org.springframework.cloud|spring-cloud-heroku-connector|2.0.1.RELEASE| +|org.springframework.cloud|spring-cloud-localconfig-connector|2.0.1.RELEASE| +|org.springframework.cloud|spring-cloud-spring-service-connector|2.0.1.RELEASE| +|org.springframework.data|spring-data-cassandra|2.0.5.RELEASE| +|org.springframework.data|spring-data-commons|2.0.5.RELEASE| +|org.springframework.data|spring-data-couchbase|3.0.5.RELEASE| +|org.springframework.data|spring-data-elasticsearch|3.0.5.RELEASE| +|org.springframework.data|spring-data-envers|2.0.5.RELEASE| +|org.springframework.data|spring-data-gemfire|2.0.5.RELEASE| +|org.springframework.data|spring-data-geode|2.0.5.RELEASE| +|org.springframework.data|spring-data-jpa|2.0.5.RELEASE| +|org.springframework.data|spring-data-keyvalue|2.0.5.RELEASE| +|org.springframework.data|spring-data-ldap|2.0.5.RELEASE| +|org.springframework.data|spring-data-mongodb|2.0.5.RELEASE| +|org.springframework.data|spring-data-mongodb-cross-store|2.0.5.RELEASE| +|org.springframework.data|spring-data-neo4j|5.0.5.RELEASE| +|org.springframework.data|spring-data-redis|2.0.5.RELEASE| +|org.springframework.data|spring-data-rest-core|3.0.5.RELEASE| +|org.springframework.data|spring-data-rest-hal-browser|3.0.5.RELEASE| +|org.springframework.data|spring-data-rest-webmvc|3.0.5.RELEASE| +|org.springframework.data|spring-data-solr|3.0.5.RELEASE| +|org.springframework.hateoas|spring-hateoas|0.24.0.RELEASE| +|org.springframework.integration|spring-integration-amqp|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-core|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-event|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-feed|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-file|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-ftp|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-gemfire|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-groovy|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-http|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-ip|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-jdbc|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-jms|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-jmx|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-jpa|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-mail|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-mongodb|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-mqtt|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-redis|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-rmi|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-scripting|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-security|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-sftp|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-stomp|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-stream|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-syslog|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-test|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-test-support|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-twitter|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-webflux|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-websocket|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-ws|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-xml|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-xmpp|5.0.3.RELEASE| +|org.springframework.integration|spring-integration-zookeeper|5.0.3.RELEASE| +|org.springframework.kafka|spring-kafka|2.1.4.RELEASE| +|org.springframework.kafka|spring-kafka-test|2.1.4.RELEASE| +|org.springframework.ldap|spring-ldap-core|2.3.2.RELEASE| +|org.springframework.ldap|spring-ldap-core-tiger|2.3.2.RELEASE| +|org.springframework.ldap|spring-ldap-ldif-batch|2.3.2.RELEASE| +|org.springframework.ldap|spring-ldap-ldif-core|2.3.2.RELEASE| +|org.springframework.ldap|spring-ldap-odm|2.3.2.RELEASE| +|org.springframework.ldap|spring-ldap-test|2.3.2.RELEASE| +|org.springframework.plugin|spring-plugin-core|1.2.0.RELEASE| +|org.springframework.plugin|spring-plugin-metadata|1.2.0.RELEASE| +|org.springframework.restdocs|spring-restdocs-asciidoctor|2.0.0.RELEASE| +|org.springframework.restdocs|spring-restdocs-core|2.0.0.RELEASE| +|org.springframework.restdocs|spring-restdocs-mockmvc|2.0.0.RELEASE| +|org.springframework.restdocs|spring-restdocs-restassured|2.0.0.RELEASE| +|org.springframework.restdocs|spring-restdocs-webtestclient|2.0.0.RELEASE| +|org.springframework.retry|spring-retry|1.2.2.RELEASE| +|org.springframework.security|spring-security-acl|5.0.3.RELEASE| +|org.springframework.security|spring-security-aspects|5.0.3.RELEASE| +|org.springframework.security|spring-security-cas|5.0.3.RELEASE| +|org.springframework.security|spring-security-config|5.0.3.RELEASE| +|org.springframework.security|spring-security-core|5.0.3.RELEASE| +|org.springframework.security|spring-security-crypto|5.0.3.RELEASE| +|org.springframework.security|spring-security-data|5.0.3.RELEASE| +|org.springframework.security|spring-security-ldap|5.0.3.RELEASE| +|org.springframework.security|spring-security-messaging|5.0.3.RELEASE| +|org.springframework.security|spring-security-oauth2-client|5.0.3.RELEASE| +|org.springframework.security|spring-security-oauth2-core|5.0.3.RELEASE| +|org.springframework.security|spring-security-oauth2-jose|5.0.3.RELEASE| +|org.springframework.security|spring-security-openid|5.0.3.RELEASE| +|org.springframework.security|spring-security-remoting|5.0.3.RELEASE| +|org.springframework.security|spring-security-taglibs|5.0.3.RELEASE| +|org.springframework.security|spring-security-test|5.0.3.RELEASE| +|org.springframework.security|spring-security-web|5.0.3.RELEASE| +|org.springframework.session|spring-session-core|2.0.2.RELEASE| +|org.springframework.session|spring-session-data-mongodb|2.0.2.RELEASE| +|org.springframework.session|spring-session-data-redis|2.0.2.RELEASE| +|org.springframework.session|spring-session-hazelcast|2.0.2.RELEASE| +|org.springframework.session|spring-session-jdbc|2.0.2.RELEASE| +|org.springframework.ws|spring-ws-core|3.0.0.RELEASE| +|org.springframework.ws|spring-ws-security|3.0.0.RELEASE| +|org.springframework.ws|spring-ws-support|3.0.0.RELEASE| +|org.springframework.ws|spring-ws-test|3.0.0.RELEASE| +|org.synchronoss.cloud|nio-multipart-parser|1.1.0| +|org.thymeleaf|thymeleaf|3.0.9.RELEASE| +|org.thymeleaf|thymeleaf-spring5|3.0.9.RELEASE| +|org.thymeleaf.extras|thymeleaf-extras-java8time|3.0.1.RELEASE| +|org.thymeleaf.extras|thymeleaf-extras-springsecurity4|3.0.2.RELEASE| +|org.webjars|hal-browser|3325375| +|org.webjars|webjars-locator-core|0.35| +|org.xerial|sqlite-jdbc|3.21.0.1| +|org.xmlunit|xmlunit-core|2.5.1| +|org.xmlunit|xmlunit-legacy|2.5.1| +|org.xmlunit|xmlunit-matchers|2.5.1| +|org.yaml|snakeyaml|1.19| +|redis.clients|jedis|2.9.0| +|wsdl4j|wsdl4j|1.6.3| +|xml-apis|xml-apis|1.4.01|