diff --git a/I. Spring Boot Documentation/1. About the documentation.md b/I. Spring Boot Documentation/1. About the documentation.md index 9103377c..b56f7aa2 100644 --- a/I. Spring Boot Documentation/1. About the documentation.md +++ b/I. Spring Boot Documentation/1. About the documentation.md @@ -1,5 +1,5 @@ ### 1. 关于本文档 -Spring Boot参考指南有[html](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/reference/html),[pdf](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/reference/pdf/spring-boot-reference.pdf)和[epub](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/reference/epub/spring-boot-reference.epub)形式的文档。在[docs.spring.io/spring-boot/docs/current/reference](http://docs.spring.io/spring-boot/docs/current/reference)可获取到最新的副本。 +Spring Boot参考指南有[html](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/html),[pdf](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/pdf/spring-boot-reference.pdf)和[epub](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/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 index cc0405cd..84e69fdb 100644 --- a/I. Spring Boot Documentation/2. Getting help.md +++ b/I. Spring Boot Documentation/2. Getting help.md @@ -3,8 +3,8 @@ 使用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基础知识-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)! +**注**: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 index 60d580d1..97447527 100644 --- a/I. Spring Boot Documentation/3. First steps.md +++ b/I. Spring Boot Documentation/3. First steps.md @@ -1,6 +1,6 @@ ### 3. 第一步 -如果你想从总体上对Spring Boot或Spring入门,可以从[这里开始](../II. Getting started/README.md)! +如果你想对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) 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 135b5ccf..fb4cbc7f 100644 --- a/I. Spring Boot Documentation/4. Working with Spring Boot.md +++ b/I. Spring Boot Documentation/4. Working with Spring Boot.md @@ -1,9 +1,9 @@ ### 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.1. Maven.md)|[Gradle](../III. Using Spring Boot/13.2. Gradle.md)|[Ant](../III. Using Spring Boot/13.3. Ant.md)|[Starter POMs](../III. Using Spring Boot/13.4. Starter POMs.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) - 运行代码:[IDE](../III. Using Spring Boot/19.1. Running from an IDE.md)|[Packaged](../III. Using Spring Boot/19.2. Running as a packaged application.md)|[Maven](../III. Using Spring Boot/19.3. Using the Maven plugin.md)|[Gradle](../III. Using Spring Boot/19.4. Using the Gradle plugin.md) -- 应用打包:[生产jars](../III. Using Spring Boot/20. Packaging your application for production.md) +- 应用打包:[产品级jars](../III. Using Spring Boot/21. Packaging your application for production.md) - Spring Boot命令行:[使用CLI](../VII. Spring Boot CLI/README.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 index 02a1caa1..ed6c3005 100644 --- a/I. Spring Boot Documentation/5. Learning about Spring Boot features.md +++ b/I. Spring Boot Documentation/5. Learning about Spring Boot features.md @@ -1,10 +1,10 @@ ### 5. 了解Spring Boot特性 -需要更多Spring Boot核心特性?[这是为你准备的](../IV. Spring Boot features/README.md)! +想要了解更多Spring Boot核心特性的详情?[这就是为你准备的](../IV. Spring Boot features/README.md)! -- 核心特性:[SpringApplication](../IV. Spring Boot features/22. SpringApplication.md)|[外部配置](../IV. Spring Boot features/23. Externalized Configuration.md)|[Profiles](../IV. Spring Boot features/24. Profiles.md)|[日志](../IV. Spring Boot features/25. Logging.md) -- Web应用:[MVC](../IV. Spring Boot features/26.1. The ‘Spring Web MVC framework’.md)|[内嵌容器](../IV. Spring Boot features/26.3. Embedded servlet container support.md) -- 使用数据:[SQL](../IV. Spring Boot features/28. Working with SQL databases.md)|[NO-SQL](../IV. Spring Boot features/29. Working with NoSQL technologies.md) -- 消息:[概述](../IV. Spring Boot features/30. Messaging.md)|[JMS](../IV. Spring Boot features/30.1. JMS.md) -- 测试:[概述](../IV. Spring Boot features/35. Testing.md)|[Boot应用](../IV. Spring Boot features/35.3. Testing Spring Boot applications.md)|[工具](../IV. Spring Boot features/35.4. Test utilities.md) -- 扩展:[Auto-configuration](../IV. Spring Boot features/36. Developing auto-configuration and using conditions.md)|[@Conditions](../IV. Spring Boot features/36.3. Condition annotations.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 index b07df9eb..418a25c6 100644 --- a/I. Spring Boot Documentation/6. Moving to production.md +++ b/I. Spring Boot Documentation/6. Moving to production.md @@ -1,7 +1,7 @@ ### 6. 迁移到生产环境 -当你准备将你的Spring Boot应用部署到生产环境时,我们为你准备了一些你[可能喜欢的技巧](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready)! +当你准备将Spring Boot应用发布到生产环境时,我们提供了一些你[可能喜欢的技巧](../V. Spring Boot Actuator/README.md)! -- 管理端点:[概述](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-endpoints)|[自定义](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-customizing-endpoints) -- 连接可选项:[HTTP](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-monitoring)|[JMX](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-jmx)|[SSH](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-remote-shell) -- 监控:[指标](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-metrics)|[审计](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-auditing)|[追踪](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-tracing)|[进程](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-process-monitoring) +- 管理端点:[概述](../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 index 7c169239..1c0e08b0 100644 --- a/I. Spring Boot Documentation/7. Advanced topics.md +++ b/I. Spring Boot Documentation/7. Advanced topics.md @@ -2,6 +2,6 @@ 最后,我们为高级用户准备了一些主题。 -- 云部署:[Cloud Foundry](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#cloud-deployment-cloud-foundry)|[Heroku](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#cloud-deployment-heroku)|[CloudBees](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#) +- 部署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/README.md b/I. Spring Boot Documentation/README.md index 5ccc74a5..8ac28461 100644 --- a/I. Spring Boot Documentation/README.md +++ b/I. Spring Boot Documentation/README.md @@ -1,3 +1,3 @@ ### Spring Boot文档 -本节提供一个Spring Boot参考文档的简明概述。你可以把它作为文档其余部分的导航。你可以从头到尾依次阅读该参考指南,或跳过你不感兴趣的章节。 +本节对Spring Boot参考文档做了一个简单概述。你可以参考本节,从头到尾依次阅读该文档,也可以跳过不感兴趣的章节。 diff --git a/II. Getting started/10. Installing Spring Boot.md b/II. Getting started/10. Installing Spring Boot.md index 16c0b4e1..96125d2e 100644 --- a/II. Getting started/10. Installing Spring Boot.md +++ b/II. Getting started/10. Installing Spring Boot.md @@ -1,9 +1,9 @@ ### 10. Spring Boot安装 -Spring Boot可以跟典型的Java开发工具一块使用或安装为一个命令行工具。不管怎样,你将需要安装[Java SDK v1.6 ](http://www.java.com/)或更高版本。在开始之前,你需要检查下当前安装的Java版本: +Spring Boot可以跟经典的Java开发工具(Eclipse,IntelliJ等)一起使用或安装成一个命令行工具。不管怎样,你都需要安装[Java SDK v1.6 ](http://www.java.com/)或更高版本。在开始之前,你需要检查下当前安装的Java版本: ```shell $ java -version ``` -如果你是一个Java新手,或你只是想体验一下Spring Boot,你可能想先尝试[Spring Boot CLI](10.2. Installing the Spring Boot CLI.md),否则继续阅读经典地安装指南。 +如果你是一个Java新手,或只是想体验一下Spring Boot,你可能想先尝试[Spring Boot CLI](10.2. Installing the Spring Boot CLI.md),否则继续阅读“经典”地安装指南。 **注**:尽管Spring Boot兼容Java 1.6,如果可能的话,你应该考虑使用Java最新版本。 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 index 9e00a926..cfcc3f94 100644 --- 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 @@ -1,5 +1,5 @@ ### 10.1. 为Java开发者准备的安装指南 -你可以像使用其他任何标准Java库那样使用Spring Boot,只需简单地在你的classpath下包含正确的`spring-boot-*.jar`文件。Spring Boot不需要集成任何特殊的工具,所以你可以使用任何IDE或文本编辑器;Spring Boot应用也没有什么特殊之处,所以你可以像任何其他Java程序那样运行和调试。 +对于java开发者来说,使用Spring Boot就跟使用其他Java库一样,只需要在你的classpath下引入适当的`spring-boot-*.jar`文件。Spring Boot不需要集成任何特殊的工具,所以你可以使用任何IDE或文本编辑器;同时,Spring Boot应用也没有什么特殊之处,你可以像对待其他Java程序那样运行,调试它。 -尽管你可以拷贝Spring Boot jars,不过,我们通常推荐你使用一个支持依赖管理的构建工具(比如Maven或Gradle)。 +尽管可以拷贝Spring Boot jars,但我们还是建议你使用支持依赖管理的构建工具,比如Maven或Gradle。 diff --git a/II. Getting started/10.1.1. Maven installation.md b/II. Getting started/10.1.1. Maven installation.md index 2923c4d7..c6737133 100644 --- a/II. Getting started/10.1.1. Maven installation.md +++ b/II. Getting started/10.1.1. Maven installation.md @@ -1,10 +1,10 @@ ### 10.1.1. Maven安装 -Spring Boot兼容Apache Maven 3.2或更高版本。如果没有安装Maven,你可以参考[maven.apache.org](http://maven.apache.org/)指南。 +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`。 +**注**:在很多操作系统上,可以通过包管理器来安装Maven。OSX Homebrew用户可以尝试`brew install maven`,Ubuntu用户可以运行`sudo apt-get 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也提供了一个用于创建可执行jars的[Maven插件](../VIII. Build tool plugins/58. Spring Boot Maven plugin.md)。 +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 @@ -21,7 +21,7 @@ Spring Boot依赖的groupId为`org.springframework.boot`。通常你的Maven POM org.springframework.boot spring-boot-starter-parent - 1.3.0.BUILD-SNAPSHOT + 1.4.0.BUILD-SNAPSHOT @@ -67,4 +67,4 @@ Spring Boot依赖的groupId为`org.springframework.boot`。通常你的Maven POM ``` -**注**:`spring-boot-starter-parent`是使用Spring Boot的一个不错的方式,但它不总是合适的。有时你需要继承一个不同的parent POM,或者你可能只是不喜欢我们的默认配置。查看[Section 13.1.2, “Using Spring Boot without the parent POM”](../III. Using Spring Boot/13.1.2. Using Spring Boot without the parent POM.md)获取使用import的替代解决方案。 +**注**:`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 index 68a3efc8..9a16f04c 100644 --- a/II. Getting started/10.1.2. Gradle installation.md +++ b/II. Getting started/10.1.2. Gradle installation.md @@ -1,10 +1,10 @@ ### 10.1.2. Gradle安装 -Spring Boot兼容Gradle 1.12或更高版本。如果没有安装Gradle,你可以参考[www.gradle.org](http://www.gradle.org/)上的指南。 +Spring Boot兼容Gradle 1.12或更高版本。如果本地没有安装Gradle,你可以参考[www.gradle.org](http://www.gradle.org/)上的指南。 -Spring Boot依赖可以使用`org.springframework.boot` `group`来声明。通常,你的项目将声明一个或多个[“Starter POMs”](../III. Using Spring Boot/13.4. Starter POMs.md)依赖。Spring Boot提供一个用于简化依赖声明和创建可执行jars的有用的[Gradle插件](../VIII. Build tool plugins/59. Spring Boot Gradle plugin.md)。 +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](www.gradle.org/docs/current/userguide/gradle_wrapper.html)。 +**注**:当你需要构建项目时,Gradle Wrapper提供一种给力的获取Gradle的方式。它是一小段脚本和库,跟你的代码一块提交,用于启动构建进程,具体参考[Gradle Wrapper](www.gradle.org/docs/current/userguide/gradle_wrapper.html)。 下面是一个典型的`build.gradle`文件: ```gradle @@ -15,7 +15,7 @@ buildscript { maven { url "http://repo.spring.io/milestone" } } dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.BUILD-SNAPSHOT") + classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.BUILD-SNAPSHOT") } } 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 index 93299596..8dafc680 100644 --- a/II. Getting started/10.2. Installing the Spring Boot CLI.md +++ b/II. Getting started/10.2. Installing the Spring Boot CLI.md @@ -1,5 +1,5 @@ ### 10.2. Spring Boot CLI安装 -Spring Boot是一个命令行工具,用于使用Spring进行快速原型搭建。它允许你运行[Groovy](http://groovy.codehaus.org/)脚本,这意味着你可以使用类Java的语法,并且没有那么多的模板代码。 +Spring Boot CLI是一个命令行工具,可用于快速搭建基于Spring的原型。它支持运行[Groovy](http://groovy.codehaus.org/)脚本,这也就意味着你可以使用类似Java的语法,但不用写很多的模板代码。 -你没有必要为了使用Spring Boot而去用CLI,但它绝对是助力Spring应用的最快方式。 +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 index 34736230..ab7e1c6d 100644 --- a/II. Getting started/10.2.1. Manual installation.md +++ b/II. Getting started/10.2.1. Manual installation.md @@ -1,10 +1,10 @@ ### 10.2.1. 手动安装 -你可以从Spring软件仓库下载Spring CLI分发包: +Spring CLI分发包可以从Spring软件仓库下载: -1. [spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.zip](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/1.3.0.BUILD-SNAPSHOT/spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.zip) -2. [spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.tar.gz](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/1.3.0.BUILD-SNAPSHOT/spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.tar.gz) +1. [spring-boot-cli-1.4.0.BUILD-SNAPSHOT-bin.zip](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/1.4.0.BUILD-SNAPSHOT/spring-boot-cli-1.4.0.BUILD-SNAPSHOT-bin.zip) +2. [spring-boot-cli-1.4.0.BUILD-SNAPSHOT-bin.tar.gz](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/1.3.0.BUILD-SNAPSHOT/spring-boot-cli-1.4.0.BUILD-SNAPSHOT-bin.tar.gz) -不稳定的[snapshot分发包](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/)也能获取到。 +不稳定的[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`来运行一个`.jar`文件(该脚本会帮你确定classpath被正确设置)。 +下载完成后,解压分发包,根据存档里的[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 GVM.md b/II. Getting started/10.2.2. Installation with GVM.md deleted file mode 100644 index 7d655d43..00000000 --- a/II. Getting started/10.2.2. Installation with GVM.md +++ /dev/null @@ -1,33 +0,0 @@ -### 10.2.2. 使用GVM安装 - -GVM(Groovy环境管理器)可以用来管理多种不同版本的Groovy和Java二进制包,包括Groovy自身和Spring Boot CLI。可以从[gvmtool.net](http://gvmtool.net/)获取gvm,并使用以下命令安装Spring Boot: -```shell -$ gvm install springboot -$ spring --version -Spring Boot v1.3.0.BUILD-SNAPSHOT -``` -如果你正在为CLI开发新的特性,并想轻松获取你刚构建的版本,可以使用以下命令: -```shell -$ gvm install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin/spring-1.3.0.BUILD-SNAPSHOT/ -$ gvm use springboot dev -$ spring --version -Spring CLI v1.3.0.BUILD-SNAPSHOT -``` -这将会在你的gvm仓库中安装一个名叫dev的本地spring实例。它指向你的目标构建位置,所以每次你重新构建Spring Boot,spring将会是最新的。 - -你可以通过以下命令来验证: -```shell -$ gvm ls springboot - -================================================================================ -Available Springboot Versions -================================================================================ -> + dev -* 1.3.0.BUILD-SNAPSHOT - -================================================================================ -+ - local version -* - installed -> - currently in use -================================================================================ -``` diff --git a/II. Getting started/10.2.2. Installation with SDKMAN.md b/II. Getting started/10.2.2. Installation with SDKMAN.md new file mode 100644 index 00000000..1eac4434 --- /dev/null +++ b/II. Getting started/10.2.2. Installation with SDKMAN.md @@ -0,0 +1,33 @@ +### 10.2.2. 使用SDKMAN安装 + +SDKMAN(软件开发包管理器)可以对各种各样的二进制SDK包进行版本管理,包括Groovy和Spring Boot CLI。可以从[sdkman.io](http://sdkman.io/)下载SDKMAN,并使用以下命令安装Spring Boot: +```shell +$ sdk install springboot +$ spring --version +Spring Boot v1.4.0.BUILD-SNAPSHOT +``` +如果你正在为CLI开发新的特性,并想轻松获取刚构建的版本,可以使用以下命令: +```shell +$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-1.4.0.BUILD-SNAPSHOT-bin/spring-1.4.0.BUILD-SNAPSHOT/ +$ sdk default springboot dev +$ spring --version +Spring CLI v1.4.0.BUILD-SNAPSHOT +``` +这将会安装一个名叫dev的本地spring实例,它指向你的目标构建位置,所以每次你重新构建Spring Boot,spring都会更新为最新的。 + +你可以通过以下命令来验证: +```shell +$ sdk ls springboot + +================================================================================ +Available Springboot Versions +================================================================================ +> + dev +* 1.4.0.BUILD-SNAPSHOT + +================================================================================ ++ - local version +* - installed +> - currently in use +================================================================================ +``` diff --git a/II. Getting started/10.2.3. OSX Homebrew installation.md b/II. Getting started/10.2.3. OSX Homebrew installation.md index 6251c2db..bdac8e3a 100644 --- a/II. Getting started/10.2.3. OSX Homebrew installation.md +++ b/II. Getting started/10.2.3. OSX Homebrew installation.md @@ -1,6 +1,6 @@ ### 10.2.3. 使用OSX Homebrew进行安装 -如果你的环境是Mac,并使用[Homebrew](http://brew.sh/),想要安装Spring Boot CLI只需如下操作: +如果你的环境是Mac,并使用[Homebrew](http://brew.sh/),想要安装Spring Boot CLI只需以下操作: ```shell $ brew tap pivotal/tap $ brew install springboot diff --git a/II. Getting started/10.2.4. MacPorts installation.md b/II. Getting started/10.2.4. MacPorts installation.md index 3c9c3538..df019ae7 100644 --- a/II. Getting started/10.2.4. MacPorts installation.md +++ b/II. Getting started/10.2.4. MacPorts installation.md @@ -1,6 +1,6 @@ ### 10.2.4. 使用MacPorts进行安装 -如果你的环境是Mac,并使用[MacPorts](http://www.macports.org/),想要安装Spring Boot CLI只需如下操作: +如果你的环境是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 index c2c10965..cf9f8a13 100644 --- a/II. Getting started/10.2.5. Command-line completion.md +++ b/II. Getting started/10.2.5. Command-line completion.md @@ -1,8 +1,8 @@ ### 10.2.5. 命令行实现 -Spring Boot CLI启动脚本为[BASH](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29)和[zsh](http://en.wikipedia.org/wiki/Zsh) shells提供完整的命令行实现。你可以在任何shell中source脚本(名称也是spring),或将它放到你个人或系统范围的bash实现初始化中。在一个Debian系统里,系统范围的脚本位于`/shell-completion/bash`下,当一个新的shell启动时该目录下的所有脚本都被执行。想要手动运行该脚本,例如,你已经使用GVM进行安装了: +Spring Boot CLI启动脚本为[BASH](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29)和[zsh](http://en.wikipedia.org/wiki/Zsh) shells提供完整的命令行实现。你可以在任何shell中source脚本(名称也是spring),或将它放到用户或系统范围内的bash初始化脚本里。在Debian系统中,系统级的脚本位于`/shell-completion/bash`下,当新的shell启动时该目录下的所有脚本都会被执行。如果想要手动运行脚本,假如你已经安装了SDKMAN,可以使用以下命令: ```shell -$ . ~/.gvm/springboot/current/shell-completion/bash/spring +$ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring $ spring grab help jar run test version ``` 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 index 32fafd71..e10a158c 100644 --- 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 @@ -1,6 +1,6 @@ ### 10.2.6. Spring CLI示例快速入门 -下面是一个相当简单的web应用,你可以用它测试你的安装是否成功。创建一个名叫`app.groovy`的文件: +下面是一个相当简单的web应用,你可以用它测试Spring CLI安装是否成功。创建一个名叫`app.groovy`的文件: ```groovy @RestController class ThisWillActuallyRun { @@ -12,13 +12,13 @@ class ThisWillActuallyRun { } ``` -然后简单地从一个shell中运行它: +然后只需在shell中运行以下命令: ```shell $ spring run app.groovy ``` -**注**:当你首次运行该应用时将会花费一点时间,因为需要下载依赖。后续运行将会快很多。 +**注**:首次运行该应用将会花费一些时间,因为需要下载依赖,后续运行将会快很多。 -在你最喜欢的浏览器中打开[localhost:8080](localhost:8080),然后你应该看到以下输出: +使用你最喜欢的浏览器打开[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 index 6b532140..558844be 100644 --- 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 @@ -1,5 +1,5 @@ -### 10.3. 从Spring Boot早期版本升级 +### 10.3. 版本升级 -如果你正在升级一个Spring Boot早期版本,查看下放在[project wiki](http://github.com/spring-projects/spring-boot/wiki)上的"release notes"。你会发现每次发布的更新指南和一个"new and noteworthy"特性列表。 +如果你正在升级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环境变量以移除任何老的引用。 +想要升级一个已安装的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 index bbe5e36b..a68aa750 100644 --- a/II. Getting started/11. Developing your first Spring Boot application.md +++ b/II. Getting started/11. Developing your first Spring Boot application.md @@ -1,10 +1,10 @@ ### 11. 开发你的第一个Spring Boot应用 -让我们使用Java开发一个简单的"Hello World!" web应用,来强调下Spring Boot的一些关键特性。我们将使用Maven构建该项目,因为大多数IDEs都支持它。 +我们将使用Java开发一个简单的"Hello World" web应用,以此强调下Spring Boot的一些关键特性。项目采用Maven进行构建,因为大多数IDEs都支持它。 -**注**:[spring.io](http://spring.io/)网站包含很多使用Spring Boot的"入门"指南。如果你正在找特定问题的解决方案,可以先去那瞅瞅。 +**注**:[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: +在开始前,你需要打开终端检查下安装的Java和Maven版本是否可用: ```shell $ java -version java version "1.7.0_51" @@ -17,4 +17,4 @@ Apache Maven 3.2.3 (33f8c3e1027c3ddde99d3cdebad2656a31e8fdf4; 2014-08-11T13:58:1 Maven home: /Users/user/tools/apache-maven-3.1.1 Java version: 1.7.0_51, 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 index 23e76fd0..340f8315 100644 --- a/II. Getting started/11.1. Creating the POM.md +++ b/II. Getting started/11.1. Creating the POM.md @@ -1,6 +1,6 @@ ### 11.1. 创建POM -我们需要以创建一个Maven pom.xml文件作为开始。该pom.xml是用来构建项目的处方。打开你最喜欢的文本编辑器,然后添加以下内容: +让我们以创建一个Maven `pom.xml`文件作为开始吧,因为`pom.xml`是构建项目的处方!打开你最喜欢的文本编辑器,并添加以下内容: ```xml org.springframework.boot spring-boot-starter-parent - 1.3.0.BUILD-SNAPSHOT + 1.4.1.BUILD-SNAPSHOT @@ -43,6 +43,6 @@ ``` -这会给你一个可运转的构建,你可以通过运行`mvn package`测试它(现在你可以忽略"jar将是空的-没有包含任何内容!"的警告)。 +这样一个可工作的构建就完成了,你可以通过运行`mvn package`测试它(暂时忽略"jar将是空的-没有包含任何内容!"的警告)。 -**注**:目前你可以将该项目导入一个IDE(大多数现代的Java IDE都包含对Maven的内建支持)。简单起见,我们将继续使用普通的文本编辑器完成该示例。 +**注**:此刻,你可以将该项目导入到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 index dc572876..6919f826 100644 --- a/II. Getting started/11.2. Adding classpath dependencies.md +++ b/II. Getting started/11.2. Adding classpath dependencies.md @@ -1,13 +1,13 @@ ### 11.2. 添加classpath依赖 -Spring Boot提供很多"Starter POMs",这能够让你轻松的将jars添加到你的classpath下。我们的示例程序已经在POM的partent节点使用了`spring-boot-starter-parent`。`spring-boot-starter-parent`是一个特殊的starter,它提供了有用的Maven默认设置。同时,它也提供了一个`dependency-management`节点,这样对于”blessed“依赖你可以省略version标记。 +Spring Boot提供很多"Starters",用来简化添加jars到classpath的操作。示例程序中已经在POM的`parent`节点使用了`spring-boot-starter-parent`,它是一个特殊的starter,提供了有用的Maven默认设置。同时,它也提供一个`dependency-management`节点,这样对于期望(”blessed“)的依赖就可以省略version标记了。 -其他的”Starter POMs“简单的提供依赖,这些依赖可能是你开发特定类型的应用时需要的。由于正在开发一个web应用,我们将添加一个`spring-boot-starter-web`依赖-但在此之前,让我们看下目前所拥有的: +其他”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`依赖: +`mvn dependency:tree`命令可以将项目依赖以树形方式展现出来,你可以看到`spring-boot-starter-parent`本身并没有提供依赖。编辑`pom.xml`,并在`parent`节点下添加`spring-boot-starter-web`依赖: ```xml @@ -16,4 +16,4 @@ $ mvn dependency:tree ``` -如果再次运行`mvn dependency:tree`,你将看到现在有了一些其他依赖,包括Tomcat web服务器和Spring Boot自身。 +如果再次运行`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 index ccb5a66f..3bfa38a6 100644 --- a/II. Getting started/11.3. Writing the code.md +++ b/II. Getting started/11.3. Writing the code.md @@ -1,6 +1,6 @@ ### 11.3. 编写代码 -为了完成应用程序,我们需要创建一个单独的Java文件。Maven默认会编译`src/main/java`下的源码,所以你需要创建那样的文件结构,然后添加一个名为`src/main/java/Example.java`的文件: +为了完成应用程序,我们需要创建一个单独的Java文件。Maven默认会编译`src/main/java`下的源码,所以你需要创建那样的文件结构,并添加一个名为`src/main/java/Example.java`的文件: ```java import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; @@ -22,4 +22,4 @@ public class Example { } ``` -尽管这里没有太多代码,但很多事情正在发生。让我们分步探讨重要的部分。 +尽管代码不多,但已经发生了很多事情,让我们分步探讨重要的部分吧! 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 index 7d93a5dc..86e4cc07 100644 --- 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 @@ -1,8 +1,8 @@ ### 11.3.1. @RestController和@RequestMapping注解 -我们的Example类上使用的第一个注解是`@RestController`。这被称为一个构造型(stereotype)注解。它为阅读代码的人们提供建议。对于Spring,该类扮演了一个特殊角色。在本示例中,我们的类是一个web `@Controller`,所以当处理进来的web请求时,Spring会询问它。 +Example类上使用的第一个注解是`@RestController`,这被称为构造型(stereotype)注解。它为阅读代码的人提供暗示(这是一个支持REST的控制器),对于Spring,该类扮演了一个特殊角色。在本示例中,我们的类是一个web `@Controller`,所以当web请求进来时,Spring会考虑是否使用它来处理。 -`@RequestMapping`注解提供路由信息。它告诉Spring任何来自"/"路径的HTTP请求都应该被映射到`home`方法。`@RestController`注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。 +`@RequestMapping`注解提供路由信息,它告诉Spring任何来自"/"路径的HTTP请求都应该被映射到`home`方法。`@RestController`注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。 -**注**:`@RestController`和`@RequestMapping`注解是Spring MVC注解(它们不是Spring Boot的特定部分)。具体查看Spring参考文档的[MVC章节](http://docs.spring.io/spring/docs/4.1.5.RELEASE/spring-framework-reference/htmlsingle#mvc)。 +**注**:`@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 index ae4ff426..4e2f0ec5 100644 --- a/II. Getting started/11.3.2. The @EnableAutoConfiguration annotation.md +++ b/II. Getting started/11.3.2. The @EnableAutoConfiguration annotation.md @@ -1,5 +1,5 @@ ### 11.3.2. @EnableAutoConfiguration注解 -第二个类级别的注解是`@EnableAutoConfiguration`。这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于`spring-boot-starter-web`添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。 +第二个类级别的注解是`@EnableAutoConfiguration`,这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于`spring-boot-starter-web`添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用,并对Spring进行相应地设置。 -**Starter POMs和Auto-Configuration**:设计auto-configuration的目的是更好的使用"Starter POMs",但这两个概念没有直接的联系。你可以自由地挑选starter POMs以外的jar依赖,并且Spring Boot将仍旧尽最大努力去自动配置你的应用。 +**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" index ea12c7a1..54cd5bc2 100644 --- "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" @@ -1,3 +1,3 @@ ### 11.3.3. main方法 -我们的应用程序最后部分是main方法。这只是一个标准的方法,它遵循Java对于一个应用程序入口点的约定。我们的main方法通过调用run,将业务委托给了Spring Boot的SpringApplication类。SpringApplication将引导我们的应用,启动Spring,相应地启动被自动配置的Tomcat web服务器。我们需要将`Example.class`作为参数传递给run方法来告诉SpringApplication谁是主要的Spring组件。为了暴露任何的命令行参数,args数组也会被传递过去。 +应用程序的最后部分是main方法,这是一个标准的方法,它遵循Java对于一个应用程序入口点的约定。我们的main方法通过调用`run`,将业务委托给了Spring Boot的SpringApplication类。SpringApplication将引导我们的应用,启动Spring,相应地启动被自动配置的Tomcat web服务器。我们需要将`Example.class`作为参数传递给`run`方法,以此告诉SpringApplication谁是主要的Spring组件,并传递args数组以暴露所有的命令行参数。 diff --git a/II. Getting started/11.4. Running the example.md b/II. Getting started/11.4. Running the example.md index 530051f1..dba02650 100644 --- a/II. Getting started/11.4. Running the example.md +++ b/II. Getting started/11.4. Running the example.md @@ -1,6 +1,6 @@ ### 11.4. 运行示例 -到此我们的应用应该可以工作了。由于使用了`spring-boot-starter-parent` POM,这样我们就有了一个非常有用的run目标,我们可以用它启动程序。在项目根目录下输入`mvn spring-boot:run`来启动应用: +到此,示例应用可以工作了。由于使用了`spring-boot-starter-parent` POM,这样我们就有了一个非常有用的run目标来启动程序。在项目根目录下输入`mvn spring-boot:run`启动应用: ```shell $ mvn spring-boot:run @@ -10,13 +10,13 @@ $ mvn spring-boot:run \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v1.3.0.BUILD-SNAPSHOT) + :: Spring Boot :: (v1.4.1.BUILD-SNAPSHOT) ....... . . . ....... . . . (log output here) ....... . . . ........ Started Example in 2.222 seconds (JVM running for 6.514) ``` -如果使用一个浏览器打开[localhost:8080](http://localhost:8080),你应该可以看到以下输出: +如果使用浏览器打开[localhost:8080](http://localhost:8080),你应该可以看到如下输出: ```shell Hello World! ``` diff --git a/II. Getting started/11.5. Creating an executable jar.md b/II. Getting started/11.5. Creating an executable jar.md index fd357e5e..c639678c 100644 --- a/II. Getting started/11.5. Creating an executable jar.md +++ b/II. Getting started/11.5. Creating an executable jar.md @@ -1,10 +1,10 @@ -### 11.5. 创建一个可执行jar +### 11.5. 创建可执行jar -让我们通过创建一个完全自包含的可执行jar文件来结束我们的示例,该jar文件可以在生产环境运行。可执行jars(有时候被成为胖jars "fat jars")是包含你的编译后的类和你的代码运行所需的依赖jar的存档。 +让我们通过创建一个完全自包含,并可以在生产环境运行的可执行jar来结束示例吧!可执行jars(有时被称为胖jars "fat jars")是包含编译后的类及代码运行所需依赖jar的存档。 -**可执行jars和Java**:Java没有提供任何标准的加载内嵌jar文件(即jar文件中还包含jar文件)的方法。如果你想发布一个自包含的应用这就是一个问题。为了解决该问题,很多开发者采用"共享的"jars。一个共享的jar简单地将来自所有jars的类打包进一个单独的“超级jar”。采用共享jar方式的问题是很难区分在你的应用程序中可以使用哪些库。在多个jars中如果存在相同的文件名(但内容不一样)也会是一个问题。Spring Boot采取一个[不同的途径](../X. Appendices/D. The executable jar format.md),并允许你真正的内嵌jars。 +**可执行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节点下插入以下内容: +为了创建可执行的jar,我们需要将`spring-boot-maven-plugin`添加到`pom.xml`中,在dependencies节点后面插入以下内容: ```xml @@ -15,9 +15,9 @@ ``` -**注**:`spring-boot-starter-parent` POM包含用于绑定repackage目标的``配置。如果你不使用parent POM,你将需要自己声明该配置。具体参考[插件文档](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/usage.html)。 +**注**:`spring-boot-starter-parent` POM包含绑定到repackage目标的``配置。如果不使用parent POM,你需要自己声明该配置,具体参考[插件文档](http://docs.spring.io/spring-boot/docs/1.4.1.BUILD-SNAPSHOT/maven-plugin/usage.html)。 -保存你的pom.xml,然后从命令行运行`mvn package`: +保存`pom.xml`,并从命令行运行`mvn package`: ```shell $ mvn package @@ -30,18 +30,18 @@ $ mvn package [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:1.3.0.BUILD-SNAPSHOT:repackage (default) @ myproject --- +[INFO] --- spring-boot-maven-plugin:1.4.1.BUILD-SNAPSHOT:repackage (default) @ myproject --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ ``` -如果查看target目录,你应该看到`myproject-0.0.1-SNAPSHOT.jar`。该文件应该有10Mb左右的大小。如果想偷看内部结构,你可以运行`jar tvf`: +如果查看target目录,你应该可以看到`myproject-0.0.1-SNAPSHOT.jar`,该文件大概有10Mb。想查看内部结构,可以运行`jar tvf`: ```shell $ jar tvf target/myproject-0.0.1-SNAPSHOT.jar ``` -在target目录下,你应该也能看到一个很小的名为`myproject-0.0.1-SNAPSHOT.jar.original`的文件。这是在Spring Boot重新打包前Maven创建的原始jar文件。 +在该目录下,你应该还能看到一个很小的名为`myproject-0.0.1-SNAPSHOT.jar.original`的文件,这是在Spring Boot重新打包前,Maven创建的原始jar文件。 -为了运行该应用程序,你可以使用`java -jar`命令: +可以使用`java -jar`命令运行该应用程序: ```shell $ java -jar target/myproject-0.0.1-SNAPSHOT.jar @@ -57,4 +57,4 @@ $ java -jar target/myproject-0.0.1-SNAPSHOT.jar ....... . . . ........ Started Example in 2.536 seconds (JVM running for 2.864) ``` -和以前一样,点击`ctrl-c`来温柔地退出程序。 +如上所述,点击`ctrl-c`可以温雅地退出应用。 diff --git a/II. Getting started/12. What to read next.md b/II. Getting started/12. What to read next.md index e33c5b77..bdd34414 100644 --- a/II. Getting started/12. What to read next.md +++ b/II. Getting started/12. What to read next.md @@ -1 +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 index 008fec32..c4887606 100644 --- a/II. Getting started/8. Introducing Spring Boot.md +++ b/II. Getting started/8. Introducing Spring Boot.md @@ -1,13 +1,13 @@ ### 8. Spring Boot介绍 -Spring Boot使开发独立的,产品级别的基于Spring的应用变得非常简单,你只需"just run"。 -我们为Spring平台及第三方库提供开箱即用的设置,这样你就可以有条不紊地开始。多数Spring Boot应用需要很少的Spring配置。 +Spring Boot简化了基于Spring的应用开发,你只需要"run"就能创建一个独立的,产品级别的Spring应用。 +我们为Spring平台及第三方库提供开箱即用的设置,这样你就可以有条不紊地开始。多数Spring Boot应用只需要很少的Spring配置。 你可以使用Spring Boot创建Java应用,并使用`java -jar`启动它或采用传统的war部署方式。我们也提供了一个运行"spring脚本"的命令行工具。 我们主要的目标是: -- 为所有的Spring开发提供一个从根本上更快的和广泛使用的入门经验。 -- 开箱即用,但你可以通过不采用默认设置来摆脱这种方式。 -- 提供一系列大型项目常用的非功能性特征(比如,内嵌服务器,安全,指标,健康检测,外部化配置)。 -- 绝对不需要代码生成及XML配置。 +- 为所有Spring开发提供一个从根本上更快,且随处可得的入门体验。 +- 开箱即用,但通过不采用默认设置可以快速摆脱这种方式。 +- 提供一系列大型项目常用的非功能性特征,比如:内嵌服务器,安全,指标,健康检测,外部化配置。 +- 绝对没有代码生成,也不需要XML配置。 diff --git a/II. Getting started/9. System Requirements.md b/II. Getting started/9. System Requirements.md index 063980a2..d3290c86 100644 --- a/II. Getting started/9. System Requirements.md +++ b/II. Getting started/9. System Requirements.md @@ -1,5 +1,5 @@ ### 9. 系统要求 -默认情况下,Spring Boot 1.3.0.BUILD-SNAPSHOT 需要Java7和Spring框架4.1.3或以上。你可以在Java6下使用Spring Boot,不过需要添加额外配置。具体参考[Section 73.9, “How to use Java 6” ](../IX. ‘How-to’ guides/73.9. How to use Java 6.md)。构建环境明确支持的有Maven(3.2+)和Gradle(1.12+)。 +默认情况下,Spring Boot 1.4.0.BUILD-SNAPSHOT 需要[Java7](http://www.java.com/)环境,Spring框架4.3.2.BUILD-SNAPSHOT或以上版本。你可以在Java6下使用Spring Boot,不过需要添加额外配置。具体参考[Section 82.11, “How to use Java 6” ](../IX. ‘How-to’ guides/73.9. How to use Java 6.md)。明确提供构建支持的有Maven(3.2+)和Gradle(1.12+)。 -**注**:尽管你可以在Java6或Java7环境下使用Spring Boot,通常我们建议你如果可能的话就使用Java8。 +**注**:尽管你可以在Java6或Java7环境下使用Spring Boot,通常建议尽可能使用Java8。 diff --git a/II. Getting started/9.1. Servlet containers.md b/II. Getting started/9.1. Servlet containers.md index a3ba2241..8c82523a 100644 --- a/II. Getting started/9.1. Servlet containers.md +++ b/II. Getting started/9.1. Servlet containers.md @@ -6,8 +6,9 @@ |--------|:-------|:-------| |Tomcat 8|3.1|Java 7+| |Tomcat 7|3.0|Java 6+| -|Jetty 9|3.1|Java 7+| +|Jetty 9.3|3.1|Java 8+| +|Jetty 9.2|3.1|Java 7+| |Jetty 8|3.0|Java 6+| -|Undertow 1.1|3.1|Java 7+| +|Undertow 1.3|3.1|Java 7+| 你也可以将Spring Boot应用部署到任何兼容Servlet 3.0+的容器。 diff --git a/II. Getting started/README.md b/II. Getting started/README.md index 599f1a2c..5ea4ed27 100644 --- a/II. Getting started/README.md +++ b/II. Getting started/README.md @@ -1,3 +1,3 @@ -### 开始 +### 入门指南 -如果你想从总体上对Spring Boot或Spring入门,本章节就是为你准备的!在这里,我们将回答基本的"what?","how?"和"why?"问题。你会发现一个温雅的Spring Boot介绍及安装指南。然后我们构建第一个Spring Boot应用,并讨论一些我们需要遵循的核心原则。 +如果你想从大体上了解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 index b1ca2712..b6a7cfa0 100644 --- a/III. Using Spring Boot/13. Build systems.md +++ b/III. Using Spring Boot/13. Build systems.md @@ -1,3 +1,3 @@ ### 13. 构建系统 -强烈建议你选择一个支持依赖管理,能消费发布到Maven中央仓库的artifacts的构建系统。我们推荐你选择Maven或Gradle。选择其他构建系统来使用Spring Boot也是可能的(比如Ant),但它们不会被很好的支持。 +强烈建议你选择一个支持依赖管理,能消费发布到"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..25d96039 --- /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模块及第三方库,该列表可以在[材料清单(spring-boot-dependencies)](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-maven-without-a-parent)获取到,也可以找到一些支持[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每次发布都关联一个Spring框架的基础版本,所以强烈建议你不要自己指定Spring版本。 diff --git a/III. Using Spring Boot/13.1. Maven.md b/III. Using Spring Boot/13.1. Maven.md deleted file mode 100644 index ef075458..00000000 --- a/III. Using Spring Boot/13.1. Maven.md +++ /dev/null @@ -1,11 +0,0 @@ -### 13.1. Maven - -Maven用户可以继承`spring-boot-starter-parent`项目来获取合适的默认设置。该父项目提供以下特性: -- 默认编译级别为Java 1.6 -- 源码编码为UTF-8 -- 一个依赖管理节点,允许你省略普通依赖的``标签,继承自`spring-boot-dependencies` POM。 -- 合适的[资源过滤](https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html) -- 合适的插件配置([exec插件](http://mojo.codehaus.org/exec-maven-plugin/),[surefire](http://maven.apache.org/surefire/maven-surefire-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`的资源过滤 - -最后一点:由于默认配置文件接收Spring风格的占位符(`${...}`),Maven filtering改用`@..@`占位符(你可以使用Maven属性`resource.delimiter`来覆盖它)。 diff --git a/III. Using Spring Boot/13.1.1. Inheriting the starter parent.md b/III. Using Spring Boot/13.1.1. Inheriting the starter parent.md deleted file mode 100644 index 1af29ee8..00000000 --- a/III. Using Spring Boot/13.1.1. Inheriting the starter parent.md +++ /dev/null @@ -1,12 +0,0 @@ -### 13.1.1. 继承starter parent - -想配置你的项目继承`spring-boot-starter-parent`只需要简单地设置`parent`为: -```xml - - - org.springframework.boot - spring-boot-starter-parent - 1.3.0.BUILD-SNAPSHOT - -``` -**注**:你应该只需要在该依赖上指定Spring Boot版本。如果导入其他的starters,你可以放心的省略版本号。 diff --git a/III. Using Spring Boot/13.1.2. Using Spring Boot without the parent POM.md b/III. Using Spring Boot/13.1.2. Using Spring Boot without the parent POM.md deleted file mode 100644 index f24e87f5..00000000 --- a/III. Using Spring Boot/13.1.2. Using Spring Boot without the parent POM.md +++ /dev/null @@ -1,19 +0,0 @@ -### 13.1.2. 使用没有父POM的Spring Boot - -不是每个人都喜欢继承`spring-boot-starter-parent` POM。你可能需要使用公司标准parent,或你可能倾向于显式声明所有Maven配置。 - -如果你不使用`spring-boot-starter-parent`,通过使用一个`scope=import`的依赖,你仍能获取到依赖管理的好处: -```xml - - - - - org.springframework.boot - spring-boot-dependencies - 1.3.0.BUILD-SNAPSHOT - pom - import - - - -``` diff --git a/III. Using Spring Boot/13.1.3. Changing the Java version.md b/III. Using Spring Boot/13.1.3. Changing the Java version.md deleted file mode 100644 index d975dc6a..00000000 --- a/III. Using Spring Boot/13.1.3. Changing the Java version.md +++ /dev/null @@ -1,8 +0,0 @@ -### 13.1.3. 改变Java版本 - -`spring-boot-starter-parent`选择相当保守的Java兼容策略。如果你遵循我们的建议,使用最新的Java版本,你可以添加一个`java.version`属性: -```xml - - 1.8 - -``` diff --git a/III. Using Spring Boot/13.2. Gradle.md b/III. Using Spring Boot/13.2. Gradle.md deleted file mode 100644 index abc21265..00000000 --- a/III. Using Spring Boot/13.2. Gradle.md +++ /dev/null @@ -1,29 +0,0 @@ -### 13.2. Gradle - -Gradle用户可以直接在它们的`dependencies`节点处导入”starter POMs“。跟Maven不同的是,这里没有用于导入共享配置的"超父"(super parent)。 -```gradle -apply plugin: 'java' - -repositories { jcenter() } -dependencies { - compile("org.springframework.boot:spring-boot-starter-web:1.3.0.BUILD-SNAPSHOT") -} -``` -[spring-boot-gradle-plugin](../VIII. Build tool plugins/59. Spring Boot Gradle plugin.md)插件也是可以使用的,它提供创建可执行jar和从source运行项目的任务。它也添加了一个`ResolutionStrategy`用于让你省略常用依赖的版本号: -```gradle -buildscript { - repositories { jcenter() } - dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.BUILD-SNAPSHOT") - } -} - -apply plugin: 'java' -apply plugin: 'spring-boot' - -repositories { jcenter() } -dependencies { - compile("org.springframework.boot:spring-boot-starter-web") - testCompile("org.springframework.boot:spring-boot-starter-test") -} -``` diff --git a/III. Using Spring Boot/13.2. Maven.md b/III. Using Spring Boot/13.2. Maven.md new file mode 100644 index 00000000..3f2e6e66 --- /dev/null +++ b/III. Using Spring Boot/13.2. Maven.md @@ -0,0 +1,11 @@ +### 13.2. Maven + +Maven用户可以继承`spring-boot-starter-parent`项目来获取合适的默认设置。该parent项目提供以下特性: +- 默认编译级别为Java 1.6 +- 源码编码为UTF-8 +- 一个[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/),[surefire](http://maven.apache.org/surefire/maven-surefire-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` + +最后一点:由于配置文件默认接收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..8f5d8e59 --- /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 + 1.4.1.BUILD-SNAPSHOT + +``` +**注**:你应该只需在该依赖上指定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..77835041 --- /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 + 1.4.1.BUILD-SNAPSHOT + 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 + 1.4.1.BUILD-SNAPSHOT + pom + import + + + +``` +**注** 示例中,我们指定了一个BOM,但任何的依赖类型都可以通过这种方式覆盖。 diff --git a/III. Using Spring Boot/13.2.3. Changing the Java version.md b/III. Using Spring Boot/13.2.3. Changing the Java version.md new file mode 100644 index 00000000..d8d05552 --- /dev/null +++ b/III. Using Spring Boot/13.2.3. Changing the Java version.md @@ -0,0 +1,8 @@ +### 13.2.3. 改变Java版本 + +`spring-boot-starter-parent`选择了相当保守的Java兼容策略,如果你遵循我们的建议,使用最新的Java版本,可以添加一个`java.version`属性: +```xml + + 1.8 + +``` diff --git a/III. Using Spring Boot/13.1.4. Using the Spring Boot Maven plugin.md b/III. Using Spring Boot/13.2.4. Using the Spring Boot Maven plugin.md similarity index 77% rename from III. Using Spring Boot/13.1.4. Using the Spring Boot Maven plugin.md rename to III. Using Spring Boot/13.2.4. Using the Spring Boot Maven plugin.md index 703e4051..d7663277 100644 --- a/III. Using Spring Boot/13.1.4. Using the Spring Boot Maven plugin.md +++ b/III. Using Spring Boot/13.2.4. Using the Spring Boot Maven plugin.md @@ -1,4 +1,4 @@ -### 13.1.4. 使用Spring Boot Maven插件 +### 13.2.4. 使用Spring Boot Maven插件 Spring Boot包含一个[Maven插件](../VIII. Build tool plugins/58. Spring Boot Maven plugin.md),它可以将项目打包成一个可执行jar。如果想使用它,你可以将该插件添加到``节点处: ```xml @@ -11,4 +11,4 @@ Spring Boot包含一个[Maven插件](../VIII. Build tool plugins/58. Spring Boot ``` -**注**:如果使用Spring Boot starter parent pom,你只需要添加该插件而无需配置它,除非你想改变定义在partent中的设置。 +**注**:如果使用Spring Boot starter parent pom,你只需添加该插件而无需配置它,除非你想改变定义在partent中的设置。 diff --git a/III. Using Spring Boot/13.3. Ant.md b/III. Using Spring Boot/13.3. Ant.md deleted file mode 100644 index d216e6b3..00000000 --- a/III. Using Spring Boot/13.3. Ant.md +++ /dev/null @@ -1,5 +0,0 @@ -### 13.3. Ant - -使用Apache Ant构建一个Spring Boot项目是完全可能的,然而,Spring Boot没有为它提供特殊的支持或插件。Ant脚本可以使用Ivy依赖管理系统来导入starter POMs。 - -查看[Section 73.8, “Build an executable archive with Ant”](../IX. ‘How-to’ guides/73.8. Build an executable archive with Ant.md)获取更多指导。 diff --git a/III. Using Spring Boot/13.3. Gradle.md b/III. Using Spring Boot/13.3. Gradle.md new file mode 100644 index 00000000..36361bb3 --- /dev/null +++ b/III. Using Spring Boot/13.3. Gradle.md @@ -0,0 +1,41 @@ +### 13.3. Gradle + +Gradle用户可以直接在它们的`dependencies`节点处导入”starters“。跟Maven不同的是,这里不用导入"super parent",也就不能共享配置。 +```gradle +apply plugin: 'java' + +repositories { + maven { url "http://repo.spring.io/snapshot" } + maven { url "http://repo.spring.io/milestone" } +} + +dependencies { + compile("org.springframework.boot:spring-boot-starter-web:1.4.1.BUILD-SNAPSHOT") +} +``` +跟maven类似,spring boot也有gradle插件[spring-boot-gradle-plugin](../VIII. Build tool plugins/65. Spring Boot Gradle plugin.md),它能够提供任务用于创建可执行jar,或从源码(source)运行项目。它也提供[依赖管理](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-gradle-dependency-management)的能力,该功能允许你省略Spring Boot管理的任何依赖的version版本号: +```gradle +buildscript { + repositories { + maven { url "http://repo.spring.io/snapshot" } + maven { url "http://repo.spring.io/milestone" } + } + + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.BUILD-SNAPSHOT") + } +} + +apply plugin: 'java' +apply plugin: 'spring-boot' + +repositories { + 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/III. Using Spring Boot/13.4. Ant.md b/III. Using Spring Boot/13.4. Ant.md new file mode 100644 index 00000000..33f9f70c --- /dev/null +++ b/III. Using Spring Boot/13.4. Ant.md @@ -0,0 +1,54 @@ +### 13.4. Ant + +使用Apache Ant+Ivy构建Spring Boot项目是完全可能的。`spring-boot-antlib` AntLib模块能够帮助Ant创建可执行jars,一个传统的用于声明依赖的`ivy.xml`文件可能如下所示: +```xml + + + + + + + + + + +``` +同样,一个传统的`build.xml`可能是这样的: +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +**注** 如果你不想使用`spring-boot-antlib`模块,那查看[Section 81.10, “Build an executable archive from Ant without using spring-boot-antlib”](../IX. ‘How-to’ guides/73.8. Build an executable archive with Ant.md)获取更多指导。 diff --git a/III. Using Spring Boot/13.4. Starter POMs.md b/III. Using Spring Boot/13.4. Starter POMs.md deleted file mode 100644 index d17b9356..00000000 --- a/III. Using Spring Boot/13.4. Starter POMs.md +++ /dev/null @@ -1,72 +0,0 @@ -### 13.4. Starter POMs - -Starter POMs是可以包含到应用中的一个方便的依赖关系描述符集合。你可以获取所有Spring及相关技术的一站式服务,而不需要翻阅示例代码,拷贝粘贴大量的依赖描述符。例如,如果你想使用Spring和JPA进行数据库访问,只需要在你的项目中包含`spring-boot-starter-data-jpa`依赖,然后你就可以开始了。 - -该starters包含很多你搭建项目,快速运行所需的依赖,并提供一致的,管理的传递依赖集。 - -**名字有什么含义**:所有的starters遵循一个相似的命名模式:`spring-boot-starter-*`,在这里`*`是一种特殊类型的应用程序。该命名结构旨在帮你找到需要的starter。很多IDEs集成的Maven允许你通过名称搜索依赖。例如,使用相应的Eclipse或STS插件,你可以简单地在POM编辑器中点击`ctrl-space`,然后输入"spring-boot-starter"可以获取一个完整列表。 - -下面的应用程序starters是Spring Boot在`org.springframework.boot`组下提供的: - -**表 13.1. Spring Boot application starters** - -|名称|描述| -|------|:-----| -|spring-boot-starter|核心Spring Boot starter,包括自动配置支持,日志和YAML| -|spring-boot-starter-actuator|生产准备的特性,用于帮你监控和管理应用| -|spring-boot-starter-amqp|对"高级消息队列协议"的支持,通过`spring-rabbit`实现| -|spring-boot-starter-aop|对面向切面编程的支持,包括`spring-aop`和AspectJ| -|spring-boot-starter-batch|对Spring Batch的支持,包括HSQLDB数据库| -|spring-boot-starter-cloud-connectors|对Spring Cloud Connectors的支持,简化在云平台下(例如,Cloud Foundry 和Heroku)服务的连接| -|spring-boot-starter-data-elasticsearch|对Elasticsearch搜索和分析引擎的支持,包括`spring-data-elasticsearch`| -|spring-boot-starter-data-gemfire|对GemFire分布式数据存储的支持,包括`spring-data-gemfire`| -|spring-boot-starter-data-jpa|对"Java持久化API"的支持,包括`spring-data-jpa`,`spring-orm`和Hibernate| -|spring-boot-starter-data-mongodb|对MongoDB NOSQL数据库的支持,包括`spring-data-mongodb`| -|spring-boot-starter-data-rest|对通过REST暴露Spring Data仓库的支持,通过`spring-data-rest-webmvc`实现| -|spring-boot-starter-data-solr|对Apache Solr搜索平台的支持,包括`spring-data-solr`| -|spring-boot-starter-freemarker|对FreeMarker模板引擎的支持| -|spring-boot-starter-groovy-templates|对Groovy模板引擎的支持| -|spring-boot-starter-hateoas|对基于HATEOAS的RESTful服务的支持,通过`spring-hateoas`实现| -|spring-boot-starter-hornetq|对"Java消息服务API"的支持,通过HornetQ实现| -|spring-boot-starter-integration|对普通`spring-integration`模块的支持| -|spring-boot-starter-jdbc|对JDBC数据库的支持| -|spring-boot-starter-jersey|对Jersey RESTful Web服务框架的支持| -|spring-boot-starter-jta-atomikos|对JTA分布式事务的支持,通过Atomikos实现| -|spring-boot-starter-jta-bitronix|对JTA分布式事务的支持,通过Bitronix实现| -|spring-boot-starter-mail|对`javax.mail`的支持| -|spring-boot-starter-mobile|对`spring-mobile`的支持| -|spring-boot-starter-mustache|对Mustache模板引擎的支持| -|spring-boot-starter-redis|对REDIS键值数据存储的支持,包括`spring-redis`| -|spring-boot-starter-security|对`spring-security`的支持| -|spring-boot-starter-social-facebook|对`spring-social-facebook`的支持| -|spring-boot-starter-social-linkedin|对`spring-social-linkedin`的支持| -|spring-boot-starter-social-twitter|对`spring-social-twitter`的支持| -|spring-boot-starter-test|对常用测试依赖的支持,包括JUnit, Hamcrest和Mockito,还有`spring-test`模块| -|spring-boot-starter-thymeleaf|对Thymeleaf模板引擎的支持,包括和Spring的集成| -|spring-boot-starter-velocity|对Velocity模板引擎的支持| -|spring-boot-starter-web|对全栈web开发的支持,包括Tomcat和`spring-webmvc`| -|spring-boot-starter-websocket|对WebSocket开发的支持| -|spring-boot-starter-ws|对Spring Web服务的支持| - -除了应用程序的starters,下面的starters可以用于添加[生产准备](../V. Spring Boot Actuator/README.md)的特性。 - -**表 13.2. Spring Boot生产准备的starters** - -|名称|描述| -|----|:----| -|spring-boot-starter-actuator|添加生产准备特性,比如指标和监控| -|spring-boot-starter-remote-shell|添加远程`ssh` shell支持| - -最后,Spring Boot包含一些可用于排除或交换具体技术方面的starters。 - -**表 13.3. Spring Boot technical starters** - -|名称|描述| -|------|:------| -|spring-boot-starter-jetty|导入Jetty HTTP引擎(作为Tomcat的替代)| -|spring-boot-starter-log4j|对Log4J日志系统的支持| -|spring-boot-starter-logging|导入Spring Boot的默认日志系统(Logback)| -|spring-boot-starter-tomcat|导入Spring Boot的默认HTTP引擎(Tomcat)| -|spring-boot-starter-undertow|导入Undertow HTTP引擎(作为Tomcat的替代)| - -**注**:查看GitHub上位于`spring-boot-starters`模块内的[README文件](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/README.adoc),可以获取到一个社区贡献的其他starter POMs列表。 diff --git a/III. Using Spring Boot/13.5. Starters.md b/III. Using Spring Boot/13.5. Starters.md new file mode 100644 index 00000000..9dc6ad48 --- /dev/null +++ b/III. Using Spring Boot/13.5. Starters.md @@ -0,0 +1,82 @@ +### 13.5. Starters + +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](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-custom-starter)章节中讨论的,第三方starters不应该以`spring-boot`开头,因为它跟Spring Boot官方artifacts冲突。一个acme的第三方starter通常命名为`acme-spring-boot-starter`。 + +以下应用程序starters是Spring Boot在`org.springframework.boot` group下提供的: + +**表 13.1. Spring Boot application starters** + +|名称|描述|Pom| +|------|:-----|:-----| +|spring-boot-starter-test|用于测试Spring Boot应用,支持常用测试类库,包括JUnit, Hamcrest和Mockito|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-test/pom.xml)| +|spring-boot-starter-mobile|用于使用Spring Mobile开发web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-mobile/pom.xml)| +|spring-boot-starter-social-twitter|对使用Spring Social Twitter的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-social-twitter/pom.xml)| +|spring-boot-starter-cache|用于使用Spring框架的缓存支持|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-cache/pom.xml)| +|spring-boot-starter-activemq|用于使用Apache ActiveMQ实现JMS消息|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-activemq/pom.xml)| +|spring-boot-starter-jta-atomikos|用于使用Atomikos实现JTA事务|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-jta-atomikos/pom.xml)| +|spring-boot-starter-aop|用于使用Spring AOP和AspectJ实现面向切面编程|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-aop/pom.xml)| +|spring-boot-starter-web|用于使用Spring MVC构建web应用,包括RESTful。Tomcat是默认的内嵌容器|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-web/pom.xml)| +|spring-boot-starter-data-elasticsearch|用于使用Elasticsearch搜索,分析引擎和Spring Data Elasticsearch|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-elasticsearch/pom.xml)| +|spring-boot-starter-jdbc|对JDBC的支持(使用Tomcat JDBC连接池)|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-jdbc/pom.xml)| +|spring-boot-starter-batch|对Spring Batch的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-batch/pom.xml)| +|spring-boot-starter-social-facebook|用于使用Spring Social Facebook|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-social-facebook/pom.xml)| +|spring-boot-starter-web-services|对Spring Web服务的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-web-services/pom.xml)| +|spring-boot-starter-jta-narayana|Spring Boot Narayana JTA Starter|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-jta-narayana/pom.xml)| +|spring-boot-starter-thymeleaf|用于使用Thymeleaf模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-thymeleaf/pom.xml)| +|spring-boot-starter-mail|用于使用Java Mail和Spring框架email发送支持|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-mail/pom.xml)| +|spring-boot-starter-jta-bitronix|用于使用Bitronix实现JTA事务|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-jta-bitronix/pom.xml)| +|spring-boot-starter-data-mongodb|用于使用基于文档的数据库MongoDB和Spring Data MongoDB|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-mongodb/pom.xml)| +|spring-boot-starter-validation|用于使用Hibernate Validator实现Java Bean校验|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-validation/pom.xml)| +|spring-boot-starter-jooq|用于使用JOOQ访问SQL数据库,可使用[spring-boot-starter-data-jpa](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-data-jpa)或[spring-boot-starter-jdbc](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-jdbc)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-jooq/pom.xml)| +|spring-boot-starter-redis|用于使用Spring Data Redis和Jedis客户端操作键-值存储的Redis,在1.4中已被[spring-boot-starter-data-redis](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-data-redis)取代|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-redis/pom.xml)| +|spring-boot-starter-data-cassandra|用于使用分布式数据库Cassandra和Spring Data Cassandra|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-cassandra/pom.xml)| +|spring-boot-starter-hateoas|用于使用Spring MVC和Spring HATEOAS实现基于超媒体的RESTful web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-hateoas/pom.xml)| +|spring-boot-starter-integration|用于使用Spring Integration|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-integration/pom.xml)| +|spring-boot-starter-data-solr|通过Spring Data Solr使用Apache Solr搜索平台|[Pom](https://github.com/spring-projects/spring-boot/tree/master/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/master/spring-boot-starters/spring-boot-starter-freemarker/pom.xml)| +|spring-boot-starter-jersey|用于使用JAX-RS和Jersey构建RESTful web应用,可使用[spring-boot-starter-web](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-web)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-jersey/pom.xml)| +|spring-boot-starter|核心starter,包括自动配置支持,日志和YAML|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter/pom.xml)| +|spring-boot-starter-data-couchbase|用于使用基于文档的数据库Couchbase和Spring Data Couchbase|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-couchbase/pom.xml)| +|spring-boot-starter-artemis|使用Apache Artemis实现JMS消息|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-artemis/pom.xml)| +|spring-boot-starter-cloud-connectors|对Spring Cloud Connectors的支持,用于简化云平台下(例如Cloud Foundry 和Heroku)服务的连接|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-cloud-connectors/pom.xml)| +|spring-boot-starter-social-linkedin|用于使用Spring Social LinkedIn|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-social-linkedin/pom.xml)| +|spring-boot-starter-velocity|用于使用Velocity模板引擎构建MVC web应用,**从1.4版本过期**|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-velocity/pom.xml)| +|spring-boot-starter-data-rest|用于使用Spring Data REST暴露基于REST的Spring Data仓库|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-rest/pom.xml)| +|spring-boot-starter-data-gemfire|用于使用分布式数据存储GemFire和Spring Data GemFire|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-gemfire/pom.xml)| +|spring-boot-starter-groovy-templates|用于使用Groovy模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-groovy-templates/pom.xml)| +|spring-boot-starter-amqp|用于使用Spring AMQP和Rabbit MQ|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-amqp/pom.xml)| +|spring-boot-starter-hornetq|用于使用HornetQ实现JMS消息,被[spring-boot-starter-artemis](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-artemis)取代|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-hornetq/pom.xml)| +|spring-boot-starter-ws|用于使用Spring Web服务,被[spring-boot-starter-web-services](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-web-services)取代|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-ws/pom.xml)| +|spring-boot-starter-security|对Spring Security的支持|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-security/pom.xml)| +|spring-boot-starter-data-redis|用于使用Spring Data Redis和Jedis客户端操作键—值数据存储Redis|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-redis/pom.xml)| +|spring-boot-starter-websocket|用于使用Spring框架的WebSocket支持构建WebSocket应用|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-websocket/pom.xml)| +|spring-boot-starter-mustache|用于使用Mustache模板引擎构建MVC web应用|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-mustache/pom.xml)| +|spring-boot-starter-data-neo4j|用于使用图数据库Neo4j和Spring Data Neo4j|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-neo4j/pom.xml)| +|spring-boot-starter-data-jpa|用于使用Hibernate实现Spring Data JPA|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-data-jpa/pom.xml)| + +除了应用程序starters,以下starters可用于添加[production ready](../V. Spring Boot Actuator/README.md)的功能: + +**表 13.2. Spring Boot生产级starters** + +|名称|描述|Pom| +|----|:----|:----| +|spring-boot-starter-actuator|用于使用Spring Boot的Actuator,它提供了production ready功能来帮助你监控和管理应用程序|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-actuator/pom.xml)| +|spring-boot-starter-remote-shell|用于通过SSH,使用CRaSH远程shell监控,管理你的应用|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-remote-shell/pom.xml)| + +最后,Spring Boot还包含一些用于排除或交换某些特定技术方面的starters: + +**表 13.3. Spring Boot技术性starters** + +|名称|描述|Pom| +|------|:------|:------| +|spring-boot-starter-undertow|用于使用Undertow作为内嵌servlet容器,可使用[spring-boot-starter-tomcat](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-tomcat)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-undertow/pom.xml)| +|spring-boot-starter-logging|用于使用Logback记录日志,默认的日志starter|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-logging/pom.xml)| +|spring-boot-starter-tomcat|用于使用Tomcat作为内嵌servlet容器,[spring-boot-starter-web](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-web)使用的默认servlet容器|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-tomcat/pom.xml)| +|spring-boot-starter-jetty|用于使用Jetty作为内嵌servlet容器,可使用[spring-boot-starter-tomcat](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-tomcat)替代|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-jetty/pom.xml)| +|spring-boot-starter-log4j2|用于使用Log4j2记录日志,可使用[spring-boot-starter-logging](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#spring-boot-starter-logging)代替|[Pom](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/spring-boot-starter-log4j2/pom.xml)| + +**注**:查看GitHub上位于`spring-boot-starters`模块内的[README文件](http://github.com/spring-projects/spring-boot/tree/master/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 index 4a580ae2..7ad1771a 100644 --- a/III. Using Spring Boot/14. Structuring your code.md +++ b/III. Using Spring Boot/14. Structuring your code.md @@ -1,3 +1,3 @@ ### 14. 组织你的代码 -Spring Boot不需要使用任何特殊的代码结构,然而,这里有一些有用的最佳实践。 +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" index ffb7bb54..d54f123e 100644 --- "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" @@ -1,5 +1,5 @@ ### 14.1. 使用"default"包 -当类没有包含`package`声明时,它被认为处于`default package`下。通常不推荐使用`default package`,并应该避免使用它。因为对于使用`@ComponentScan`,`@EntityScan`或`@SpringBootApplication`注解的Spring Boot应用来说,来自每个jar的类都会被读取,这会造成一定的问题。 +当类没有声明`package`时,它被认为处于`default package`下。通常不推荐使用`default package`,因为对于使用`@ComponentScan`,`@EntityScan`或`@SpringBootApplication`注解的Spring Boot应用来说,它会扫描每个jar中的类,这会造成一定的问题。 -**注**:我们建议你遵循Java推荐的包命名规范,使用一个反转的域名(例如`com.example.project`)。 +**注** 我们建议你遵循Java推荐的包命名规范,使用一个反转的域名(例如`com.example.project`)。 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 index 80e84c46..ccff049b 100644 --- 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 @@ -1,8 +1,9 @@ -### 14.2. 定位main应用类 +### 14.2. 放置应用的main类 -我们通常建议你将main应用类放在位于其他类上面的根包(root package)中。通常使用`@EnableAutoConfiguration`注解你的main类,并且隐式定义了一个基础“search package”去查找一些具体的注解。例如,如果你正在编写一个JPA应用,被`@EnableAutoConfiguration`注解的类所在包将被用来搜索`@Entity`注解。 +通常建议将应用的main类放到其他类所在包的顶层(root package),并将`@EnableAutoConfiguration`注解到你的main类上,这样就隐式地定义了一个基础的包搜索路径(search package),以搜索某些特定的注解实体(比如@Service,@Component等) +。例如,如果你正在编写一个JPA应用,Spring将搜索`@EnableAutoConfiguration`注解的类所在包下的`@Entity`实体。 -使用根包允许你使用`@ComponentScan`注解而不需要定义一个`basePackage`属性。如果main类位于根包中,你也可以使用`@SpringBootApplication`注解。 +采用root package方式,你就可以使用`@ComponentScan`注解而不需要指定`basePackage`属性,也可以使用`@SpringBootApplication`注解,只要将main类放到root package中。 下面是一个典型的结构: ```shell @@ -21,7 +22,7 @@ com +- web +- CustomerController.java ``` -`Application.java`文件将声明`main`方法,还有基本的`@Configuration`。 +`Application.java`将声明`main`方法,还有基本的`@Configuration`。 ```java package com.example.myproject; diff --git a/III. Using Spring Boot/15. Configuration classes.md b/III. Using Spring Boot/15. Configuration classes.md index 0c167d5f..e7e2292d 100644 --- a/III. Using Spring Boot/15. Configuration classes.md +++ b/III. Using Spring Boot/15. Configuration classes.md @@ -1,5 +1,5 @@ ### 15. 配置类 -Spring Boot提倡基于Java的配置。尽管你可以使用一个XML源来调用`SpringApplication.run()`,我们通常建议你使用`@Configuration`类作为主要源。通常定义了`main`方法的类是作为使用`@Configuration`注解的一个很好的候选源。 +Spring Boot提倡基于Java的配置。尽管你可以使用XML源调用`SpringApplication.run()`,不过还是建议你使用`@Configuration`类作为主要配置源。通常定义了`main`方法的类也是使用`@Configuration`注解的一个很好的替补。 -**注**:很多使用XML配置的Spring配置示例已经被发布到网络上。你应该总是尽可能的使用基于Java的配置。搜索查看`enable*`注解就是一个好的开端。 +**注**:虽然网络上有很多使用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 index df5757ea..a5906223 100644 --- a/III. Using Spring Boot/15.1. Importing additional configuration classes.md +++ b/III. Using Spring Boot/15.1. Importing additional configuration classes.md @@ -1,3 +1,3 @@ ### 15.1. 导入其他配置类 -你不需要将所有的`@Configuration`放进一个单独的类。`@Import`注解可以用来导入其他配置类。另外,你也可以使用`@ComponentScan`注解自动收集所有的Spring组件,包括`@Configuration`类。 +你不需要将所有的`@Configuration`放进一个单独的类,`@Import`注解可以用来导入其他配置类。另外,你也可以使用`@ComponentScan`注解自动收集所有Spring组件,包括`@Configuration`类。 diff --git a/III. Using Spring Boot/15.2. Importing XML configuration.md b/III. Using Spring Boot/15.2. Importing XML configuration.md index 3919fbe9..826db17d 100644 --- a/III. Using Spring Boot/15.2. Importing XML configuration.md +++ b/III. Using Spring Boot/15.2. Importing XML configuration.md @@ -1,3 +1,3 @@ ### 15.2. 导入XML配置 -如果你必须要使用基于XML的配置,我们建议你依然从一个`@Configuration`类开始。之后你就可以使用`@ImportResource`注解来加载XML配置文件。 +如果必须使用XML配置,建议你仍旧从一个`@Configuration`类开始,然后使用`@ImportResource`注解加载XML配置文件。 diff --git a/III. Using Spring Boot/16. Auto-configuration.md b/III. Using Spring Boot/16. Auto-configuration.md index 6469b0b4..f2baca6a 100644 --- a/III. Using Spring Boot/16. Auto-configuration.md +++ b/III. Using Spring Boot/16. Auto-configuration.md @@ -1,7 +1,7 @@ ### 16. 自动配置 -Spring Boot自动配置(auto-configuration)尝试根据你添加的jar依赖自动配置你的Spring应用。例如,如果你的classpath下存在`HSQLDB`,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库。 +Spring Boot自动配置(auto-configuration)尝试根据添加的jar依赖自动配置你的Spring应用。例如,如果classpath下存在`HSQLDB`,并且你没有手动配置任何数据库连接的beans,那么Spring Boot将自动配置一个内存型(in-memory)数据库。 -你可以通过将`@EnableAutoConfiguration`或`@SpringBootApplication`注解添加到一个`@Configuration`类上来选择自动配置。 +实现自动配置有两种可选方式,分别是将`@EnableAutoConfiguration`或`@SpringBootApplication`注解到`@Configuration`类上。 -**注**:你只需要添加一个`@EnableAutoConfiguration`注解。我们建议你将它添加到主`@Configuration`类上。 +**注**:你应该只添加一个`@EnableAutoConfiguration`注解,通常建议将它添加到主配置类(primary `@Configuration`)上。 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 index 3cfad52a..d0794200 100644 --- a/III. Using Spring Boot/16.1. Gradually replacing auto-configuration.md +++ b/III. Using Spring Boot/16.1. Gradually replacing auto-configuration.md @@ -1,5 +1,5 @@ ### 16.1. 逐步替换自动配置 -自动配置是非侵占性的,任何时候你都可以定义自己的配置类来替换自动配置的特定部分。例如,如果你添加自己的`DataSource` bean,默认的内嵌数据库支持将不被考虑。 +自动配置(Auto-configuration)是非侵入性的,任何时候你都可以定义自己的配置类来替换自动配置的特定部分。例如,如果你添加自己的`DataSource` bean,默认的内嵌数据库支持将不被考虑。 -如果需要找出当前应用了哪些自动配置及应用的原因,你可以使用`--debug`开关启动应用。这将会记录一个自动配置的报告并输出到控制台。 +如果需要查看当前应用启动了哪些自动配置项,你可以在运行应用时打开`--debug`开关,这将为核心日志开启debug日志级别,并将自动配置相关的日志输出到控制台。 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 index c52381da..2807663f 100644 --- a/III. Using Spring Boot/16.2. Disabling specific auto-configuration.md +++ b/III. Using Spring Boot/16.2. Disabling specific auto-configuration.md @@ -1,6 +1,6 @@ -### 16.2. 禁用特定的自动配置 +### 16.2. 禁用特定的自动配置项 -如果发现应用了你不想要的特定自动配置类,你可以使用`@EnableAutoConfiguration`注解的排除属性来禁用它们。 +如果发现启用了不想要的自动配置项,你可以使用`@EnableAutoConfiguration`注解的exclude属性禁用它们: ```java import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; @@ -11,3 +11,6 @@ import org.springframework.context.annotation.*; 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 index 59ba903e..81686337 100644 --- a/III. Using Spring Boot/17. Spring Beans and dependency injection.md +++ b/III. Using Spring Boot/17. Spring Beans and dependency injection.md @@ -2,7 +2,7 @@ 你可以自由地使用任何标准的Spring框架技术去定义beans和它们注入的依赖。简单起见,我们经常使用`@ComponentScan`注解搜索beans,并结合`@Autowired`构造器注入。 -如果使用上面建议的结构组织代码(将应用类放到根包下),你可以添加`@ComponentScan`注解而不需要任何参数。你的所有应用程序组件(`@Component`, `@Service`, `@Repository`, `@Controller`等)将被自动注册为Spring Beans。 +如果遵循以上的建议组织代码结构(将应用的main类放到包的最上层,即root package),那么你就可以添加`@ComponentScan`注解而不需要任何参数,所有应用组件(`@Component`, `@Service`, `@Repository`, `@Controller`等)都会自动注册成Spring Beans。 下面是一个`@Service` Bean的示例,它使用构建器注入获取一个需要的`RiskAssessor` bean。 ```java @@ -24,4 +24,4 @@ public class DatabaseAccountService implements AccountService { // ... } ``` -**注**:注意如何使用构建器注入来允许`riskAssessor`字段被标记为`final`,这意味着`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 index c1b68bfb..62a6ca4a 100644 --- a/III. Using Spring Boot/18. Using the @SpringBootApplication annotation.md +++ b/III. Using Spring Boot/18. Using the @SpringBootApplication annotation.md @@ -1,8 +1,8 @@ ### 18. 使用@SpringBootApplication注解 -很多Spring Boot开发者总是使用`@Configuration`,`@EnableAutoConfiguration`和`@ComponentScan`注解他们的main类。由于这些注解被如此频繁地一块使用(特别是你遵循以上[最佳实践](14. Structuring your code.md)时),Spring Boot提供一个方便的`@SpringBootApplication`选择。 +很多Spring Boot开发者经常使用`@Configuration`,`@EnableAutoConfiguration`,`@ComponentScan`注解他们的main类,由于这些注解如此频繁地一块使用(特别是遵循以上[最佳实践](14. Structuring your code.md)的时候),Spring Boot就提供了一个方便的`@SpringBootApplication`注解作为代替。 -该`@SpringBootApplication`注解等价于以默认属性使用`@Configuration`,`@EnableAutoConfiguration`和`@ComponentScan`。 +`@SpringBootApplication`注解等价于以默认属性使用`@Configuration`,`@EnableAutoConfiguration`和`@ComponentScan`: ```java package com.example.myproject; @@ -18,3 +18,4 @@ public class Application { } ``` +**注** `@SpringBootApplication`注解也提供了用于自定义`@EnableAutoConfiguration`和`@ComponentScan`属性的别名(aliases)。 diff --git a/III. Using Spring Boot/19. Running your application.md b/III. Using Spring Boot/19. Running your application.md index 12c47ad2..b7b6c8d3 100644 --- a/III. Using Spring Boot/19. Running your application.md +++ b/III. Using Spring Boot/19. Running your application.md @@ -1,5 +1,5 @@ ### 19. 运行应用程序 -将应用打包成jar并使用一个内嵌HTTP服务器的一个最大好处是,你可以像其他方式那样运行你的应用程序。调试Spring Boot应用也很简单;你不需要任何特殊IDE或扩展。 +将应用打包成jar,并使用内嵌HTTP服务器的一个最大好处是,你可以像其他方式那样运行你的应用程序。调试Spring Boot应用也很简单,你都不需要任何特殊IDE插件或扩展! -**注**:本章节只覆盖基于jar的打包,如果选择将应用打包成war文件,你最好参考一下服务器和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 2c16982a..a2d272de 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`按钮。 +**注** 如果意外地多次运行一个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 index 101c3b3e..405c37f1 100644 --- 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 @@ -1,10 +1,10 @@ ### 19.2. 作为一个打包后的应用运行 -如果使用Spring Boot Maven或Gradle插件创建一个可执行jar,你可以使用`java -jar`运行你的应用。例如: +如果使用Spring Boot Maven或Gradle插件创建一个可执行jar,你可以使用`java -jar`运行应用。例如: ```shell $ java -jar target/myproject-0.0.1-SNAPSHOT.jar ``` -运行一个打包的程序并开启远程调试支持是可能的,这允许你将调试器附加到打包的应用程序上: +Spring Boot支持以远程调试模式运行一个打包的应用,下面的命令可以为应用关联一个调试器: ```shell $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ -jar target/myproject-0.0.1-SNAPSHOT.jar 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 index 9615145d..ed3228f3 100644 --- a/III. Using Spring Boot/19.3. Using the Maven plugin.md +++ b/III. Using Spring Boot/19.3. Using the Maven plugin.md @@ -1,11 +1,10 @@ ### 19.3. 使用Maven插件运行 -Spring Boot Maven插件包含一个`run`目标,它可以用来快速编译和运行应用程序。应用程序以一种暴露的方式运行,由于即时"热"加载,你可以编辑资源。 +Spring Boot Maven插件包含一个`run`目标,可用来快速编译和运行应用程序,并且跟在IDE运行一样支持热加载。 ```shell $ mvn spring-boot:run ``` -你可能想使用有用的操作系统环境变量: +你可以使用一些有用的操作系统环境变量: ```shell -$ export MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom +$ export MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=128M ``` -("egd"设置是通过为Tomcat提供一个更快的会话keys熵源来加速Tomcat的。) 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 index f2c03174..e66519d1 100644 --- a/III. Using Spring Boot/19.4. Using the Gradle plugin.md +++ b/III. Using Spring Boot/19.4. Using the Gradle plugin.md @@ -1,10 +1,10 @@ ### 19.4. 使用Gradle插件运行 -Spring Boot Gradle插件也包含一个`run`目标,它可以用来以暴露的方式运行你的应用程序。不管你什么时候导入`spring-boot-plugin`,`bootRun`任务总是被添加进去。 +Spring Boot Gradle插件也包含一个`bootRun`任务,可用来运行你的应用程序。无论你何时import `spring-boot-gradle-plugin`,`bootRun`任务总会被添加进去。 ```shell $ gradle bootRun ``` -你可能想使用那些有用的操作系统环境变量: +你可能想使用一些有用的操作系统环境变量: ```shell -$ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom +$ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M ``` diff --git a/III. Using Spring Boot/19.5. Hot swapping.md b/III. Using Spring Boot/19.5. Hot swapping.md index 903ec4b4..ffb50ff3 100644 --- a/III. Using Spring Boot/19.5. Hot swapping.md +++ b/III. Using Spring Boot/19.5. Hot swapping.md @@ -1,5 +1,5 @@ ### 19.5. 热交换 -由于Spring Boot应用程序只是普通的Java应用,那JVM热交换(hot-swapping)应该能出色的工作。JVM热交换在它能替换的字节码上有些限制,更全面的解决方案可以使用[Spring Loaded](https://github.com/spring-projects/spring-loaded)项目或[JRebel](http://zeroturnaround.com/software/jrebel/)。 +由于Spring Boot应用只是普通的Java应用,所以JVM热交换(hot-swapping)也能开箱即用。不过JVM热交换能替换的字节码有限制,想要更彻底的解决方案可以使用[Spring Loaded](https://github.com/spring-projects/spring-loaded)项目或[JRebel](http://zeroturnaround.com/software/jrebel/)。`spring-boot-devtools`模块也支持应用快速重启(restart)。 -关于热交换可以参考[“How-to”](../IX. ‘How-to’ guides/README.md)相应章节。 +详情参考下面的[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..425f9e37 --- /dev/null +++ b/III. Using Spring Boot/20. Developer tools.md @@ -0,0 +1,20 @@ +###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)。如果想确保devtools绝对不会包含在一个产品级构建中,你可以使用`excludeDevtools`构建属性彻底移除该JAR,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..7b61dc73 --- /dev/null +++ b/III. Using Spring Boot/20.1 Property defaults.md @@ -0,0 +1,7 @@ +###20.1 默认属性 + +Spring Boot支持的一些库(libraries)使用缓存提高性能,比如Thymeleaf将缓存模板以避免重复解析XML源文件。虽然缓存在生产环境很有用,但开发期间就是个累赘了。如果在IDE里修改了模板,你可能会想立即看到结果。 + +缓存选项通常配置在`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..dc718292 --- /dev/null +++ b/III. Using Spring Boot/20.2 Automatic restart.md @@ -0,0 +1,30 @@ +###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需要一个隔离的应用类加载器执行正确的操作。Gradle默认支持该行为,按照以下配置可强制Maven插件fork进程: +```properties + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + +``` +自动重启跟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`。 + +**Restart vs Reload** Spring Boot提供的重启技术是通过使用两个类加载器实现的。没有变化的类(比如那些第三方jars)会加载进一个基础(basic)classloader,正在开发的类会加载进一个重启(restart)classloader。当应用重启时,restart类加载器会被丢弃,并创建一个新的。这种方式意味着应用重启通常比冷启动(cold starts)快很多,因为基础类加载器已经可用,并且populated(意思是基础类加载器加载的类比较多?)。 + +如果发现重启对于你的应用来说不够快,或遇到类加载的问题,那你可以考虑reload技术,比如[JRebel](http://zeroturnaround.com/software/jrebel/),这些技术是通过重写它们加载过的类实现的。[Spring Loaded](https://github.com/spring-projects/spring-loaded)提供了另一种选择,然而很多框架不支持它,也得不到商业支持。 + diff --git a/III. Using Spring Boot/20.2.1 Excluding resources.md b/III. Using Spring Boot/20.2.1 Excluding resources.md new file mode 100644 index 00000000..61cb14e3 --- /dev/null +++ b/III. Using Spring Boot/20.2.1 Excluding resources.md @@ -0,0 +1,8 @@ +###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.2 Watching additional paths.md b/III. Using Spring Boot/20.2.2 Watching additional paths.md new file mode 100644 index 00000000..b2145a57 --- /dev/null +++ b/III. Using Spring Boot/20.2.2 Watching additional paths.md @@ -0,0 +1,3 @@ +###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 new file mode 100644 index 00000000..fe0e1796 --- /dev/null +++ b/III. Using Spring Boot/20.2.3 Disabling restart.md @@ -0,0 +1,11 @@ +###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.4 Using a trigger file.md b/III. Using Spring Boot/20.2.4 Using a trigger file.md new file mode 100644 index 00000000..4bc94c30 --- /dev/null +++ b/III. Using Spring Boot/20.2.4 Using a trigger file.md @@ -0,0 +1,7 @@ +###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 new file mode 100644 index 00000000..2e8bf124 --- /dev/null +++ b/III. Using Spring Boot/20.2.5 Customizing the restart classloader.md @@ -0,0 +1,12 @@ +###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.6 Known limitations.md b/III. Using Spring Boot/20.2.6 Known limitations.md new file mode 100644 index 00000000..b7a4e045 --- /dev/null +++ b/III. Using Spring Boot/20.2.6 Known limitations.md @@ -0,0 +1,5 @@ +###20.2.6 已知限制 + +重启功能不能跟使用标准`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 new file mode 100644 index 00000000..a08956e7 --- /dev/null +++ b/III. Using Spring Boot/20.3 LiveReload.md @@ -0,0 +1,7 @@ +###20.3 LiveReload + +`spring-boot-devtools`模块包含一个内嵌的LiveReload服务器,它可以在资源改变时触发浏览器刷新。LiveReload浏览器扩展可以免费从[livereload.com](http://livereload.com/extensions/)站点获取,支持Chrome,Firefox,Safari等浏览器。 + +如果不想在运行应用时启动LiveReload服务器,你可以将`spring.devtools.livereload.enabled`属性设置为false。 + +**注** 每次只能运行一个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..f1dfe24a --- /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.5 Remote applications.md b/III. Using Spring Boot/20.5 Remote applications.md new file mode 100644 index 00000000..d9726125 --- /dev/null +++ b/III. Using Spring Boot/20.5 Remote applications.md @@ -0,0 +1,9 @@ +###20.5 远程应用 + +Spring Boot开发者工具并不仅限于本地开发,在运行远程应用时你也可以使用一些特性。远程支持是可选的,通过设置`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..25522486 --- /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)。 + +运行中的远程客户端看起来如下: +```shell + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \ + \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / + =========|_|==============|___/===================================/_/_/_/ + :: Spring Boot Remote :: 1.4.1.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.2 Remote update.md b/III. Using Spring Boot/20.5.2 Remote update.md new file mode 100644 index 00000000..6c3b7f69 --- /dev/null +++ b/III. Using Spring Boot/20.5.2 Remote update.md @@ -0,0 +1,4 @@ +###20.5.2 远程更新 +远程客户端将监听应用的classpath变化,任何更新的资源都会发布到远程应用,并触发重启,这在你使用云服务迭代某个特性时非常有用。通常远程更新和重启比完整rebuild和deploy快多了。 + +**注** 文件只有在远程客户端运行时才监控。如果你在启动远程客户端之前改变一个文件,它是不会被发布到远程server的。 diff --git a/III. Using Spring Boot/20.5.3 Remote debug tunnel.md b/III. Using Spring Boot/20.5.3 Remote debug tunnel.md new file mode 100644 index 00000000..8d1db20b --- /dev/null +++ b/III. Using Spring Boot/20.5.3 Remote debug tunnel.md @@ -0,0 +1,14 @@ +###20.5.3 远程调试通道 +Java的远程调试在诊断远程应用问题时很有用,不幸的是,当应用部署在你的数据中心外时,它并不总能够启用远程调试。如果你使用基于容器的技术,比如Docker,远程调试设置起来非常麻烦。 + +为了突破这些限制,devtools支持基于HTTP的远程调试通道。远程客户端在8000端口提供一个本地server,这样远程debugger就可以连接了。一旦连接建立,调试信息就通过HTTP发送到远程应用。你可以使用`spring.devtools.remote.debug.local-port`属性设置不同的端口。 + +你需要确保远程应用启动时开启了远程调试功能,通常,这可以通过配置`JAVA_OPTS`实现,例如,对于Cloud Foundry,你可以将以下内容添加到manifest.yml: +```properties +--- + env: + JAVA_OPTS: "-Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n" +``` +**注** 注意你不需要传递一个`address=NNNN`的配置项到`-Xrunjdwp`,如果遗漏了,java会使用一个随机可用端口。 + +调试基于Internet的远程服务可能很慢,你可能需要增加IDE的超时时间。例如,在Eclipse中你可以从`Preferences…`选择`Java` -> `Debug`,改变`Debugger timeout (ms)`为更合适的值(60000在多数情况下就能解决)。 diff --git a/III. Using Spring Boot/20. Packaging your application for production.md b/III. Using Spring Boot/21. Packaging your application for production.md similarity index 88% rename from III. Using Spring Boot/20. Packaging your application for production.md rename to III. Using Spring Boot/21. Packaging your application for production.md index 88c25425..985e91dd 100644 --- a/III. Using Spring Boot/20. Packaging your application for production.md +++ b/III. Using Spring Boot/21. Packaging your application for production.md @@ -1,3 +1,3 @@ -### 20. 打包用于生产的应用程序 +### 21. 打包用于生产的应用 可执行jars可用于生产部署。由于它们是自包含的,非常适合基于云的部署。关于其他“生产准备”的特性,比如健康监控,审计和指标REST,或JMX端点,可以考虑添加`spring-boot-actuator`。具体参考[Part V, “Spring Boot Actuator: Production-ready features”](../V. Spring Boot Actuator/README.md)。 diff --git a/III. Using Spring Boot/21. What to read next.md b/III. Using Spring Boot/21. What to read next.md deleted file mode 100644 index b8d2da18..00000000 --- a/III. Using Spring Boot/21. What to read next.md +++ /dev/null @@ -1 +0,0 @@ -### 21. 接下来阅读什么 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..bfc15326 --- /dev/null +++ b/III. Using Spring Boot/22. What to read next.md @@ -0,0 +1,2 @@ +### 22. 接下来阅读什么 +现在你应该明白怎么结合最佳实践使用Spring Boot,接下来可以深入学习特殊的部分[Spring Boot features](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features),或者你可以跳过开头,阅读Spring Boot的[production ready](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#production-ready)部分。 diff --git a/III. Using Spring Boot/README.md b/III. Using Spring Boot/README.md index 62f673bd..59565fb8 100644 --- a/III. Using Spring Boot/README.md +++ b/III. Using Spring Boot/README.md @@ -1,4 +1,4 @@ ### 使用Spring Boot -本章节将会详细介绍如何使用Spring Boot。它覆盖了构建系统,自动配置和运行/部署选项等主题。我们也覆盖了一些Spring Boot最佳实践。尽管Spring Boot没有什么特别的(只是一个你能消费的库),但仍有一些建议,如果你遵循的话将会让你的开发进程更容易。 +本章节将详细介绍如何使用Spring Boot,不仅覆盖构建系统,自动配置,如何运行应用等主题,还包括一些Spring Boot的最佳实践。尽管Spring Boot本身没有什么特别的(跟其他一样,它只是另一个你可以使用的库),但仍有一些建议,如果遵循的话将会事半功倍。 -如果你刚接触Spring Boot,那最好先读下上一章节的[Getting Started](../II. Getting started/README.md)指南。 +如果你刚接触Spring Boot,那最好先阅读上一章节的[Getting Started](../II. Getting started/README.md)指南。 diff --git a/IV. Spring Boot features/22.1. Customizing the Banner.md b/IV. Spring Boot features/22.1. Customizing the Banner.md deleted file mode 100644 index 221e68b2..00000000 --- a/IV. Spring Boot features/22.1. Customizing the Banner.md +++ /dev/null @@ -1,14 +0,0 @@ -###22.1. 自定义Banner - -通过在classpath下添加一个banner.txt或设置banner.location来指定相应的文件可以改变启动过程中打印的banner。如果这个文件有特殊的编码,你可以使用banner.encoding设置它(默认为UTF-8)。 - -在banner.txt中可以使用如下的变量: - -| 变量 | 描述 | -| ----------- | :--------| -|${application.version}|MANIFEST.MF中声明的应用版本号,例如1.0| -|${application.formatted-version}|MANIFEST.MF中声明的被格式化后的应用版本号(被括号包裹且以v作为前缀),用于显示,例如(v1.0)| -|${spring-boot.version}|正在使用的Spring Boot版本号,例如1.2.2.BUILD-SNAPSHOT| -|${spring-boot.formatted-version}|正在使用的Spring Boot被格式化后的版本号(被括号包裹且以v作为前缀), 用于显示,例如(v1.2.2.BUILD-SNAPSHOT)| - -**注**:如果想以编程的方式产生一个banner,可以使用SpringBootApplication.setBanner(…)方法。使用org.springframework.boot.Banner接口,实现你自己的printBanner()方法。 diff --git a/IV. Spring Boot features/22.2. Customizing SpringApplication.md b/IV. Spring Boot features/22.2. Customizing SpringApplication.md deleted file mode 100644 index 404a0cce..00000000 --- a/IV. Spring Boot features/22.2. Customizing SpringApplication.md +++ /dev/null @@ -1,13 +0,0 @@ -### 22.2. 自定义SpringApplication - -如果默认的SpringApplication不符合你的口味,你可以创建一个本地的实例并自定义它。例如,关闭banner你可以这样写: -```java -public static void main(String[] args){ - SpringApplication app = new SpringApplication(MySpringConfiguration.class); - app.setShowBanner(false); - app.run(args); -} -``` -**注**:传递给SpringApplication的构造器参数是spring beans的配置源。在大多数情况下,这些将是@Configuration类的引用,但它们也可能是XML配置或要扫描包的引用。 - -你也可以使用application.properties文件来配置SpringApplication。具体参考[Externalized 配置](23. Externalized Configuration.md)。查看配置选项的完整列表,可参考[SpringApplication Javadoc](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/api/org/springframework/boot/SpringApplication.html). diff --git a/IV. Spring Boot features/22.3. Fluent builder API.md b/IV. Spring Boot features/22.3. Fluent builder API.md deleted file mode 100644 index 55f6a5fb..00000000 --- a/IV. Spring Boot features/22.3. Fluent builder API.md +++ /dev/null @@ -1,11 +0,0 @@ -### 22.3. 流畅的构建API - -如果你需要创建一个分层的ApplicationContext(多个具有父子关系的上下文),或你只是喜欢使用流畅的构建API,你可以使用SpringApplicationBuilder。SpringApplicationBuilder允许你以链式方式调用多个方法,包括可以创建层次结构的parent和child方法。 -```java -new SpringApplicationBuilder() - .showBanner(false) - .sources(Parent.class) - .child(Application.class) - .run(args); -``` -**注**:创建ApplicationContext层次时有些限制,比如,Web组件(components)必须包含在子上下文(child context)中,且相同的Environment即用于父上下文也用于子上下文中。具体参考[SpringApplicationBuilder javadoc](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/api/org/springframework/boot/builder/SpringApplicationBuilder.html) diff --git a/IV. Spring Boot features/22.4. Application events and listeners.md b/IV. Spring Boot features/22.4. Application events and listeners.md deleted file mode 100644 index b4c43050..00000000 --- a/IV. Spring Boot features/22.4. Application events and listeners.md +++ /dev/null @@ -1,12 +0,0 @@ -### 22.4. Application事件和监听器 - -除了常见的Spring框架事件,比如[ContextRefreshedEvent](http://docs.spring.io/spring/docs/4.1.4.RELEASE/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html),一个SpringApplication也发送一些额外的应用事件。一些事件实际上是在ApplicationContext被创建前触发的。 - -你可以使用多种方式注册事件监听器,最普通的是使用SpringApplication.addListeners(…)方法。在你的应用运行时,应用事件会以下面的次序发送: - -1. 在运行开始,但除了监听器注册和初始化以外的任何处理之前,会发送一个ApplicationStartedEvent。 -2. 在Environment将被用于已知的上下文,但在上下文被创建前,会发送一个ApplicationEnvironmentPreparedEvent。 -3. 在refresh开始前,但在bean定义已被加载后,会发送一个ApplicationPreparedEvent。 -4. 启动过程中如果出现异常,会发送一个ApplicationFailedEvent。 - -**注**:你通常不需要使用应用程序事件,但知道它们的存在会很方便(在某些场合可能会使用到)。在Spring内部,Spring Boot使用事件处理各种各样的任务。 diff --git a/IV. Spring Boot features/22.5. Web environment.md b/IV. Spring Boot features/22.5. Web environment.md deleted file mode 100644 index 3142e4ed..00000000 --- a/IV. Spring Boot features/22.5. Web environment.md +++ /dev/null @@ -1,7 +0,0 @@ -### 22.5. Web环境 - -一个SpringApplication将尝试为你创建正确类型的ApplicationContext。在默认情况下,使用AnnotationConfigApplicationContext或AnnotationConfigEmbeddedWebApplicationContext取决于你正在开发的是否是web应用。 - -用于确定一个web环境的算法相当简单(基于是否存在某些类)。如果需要覆盖默认行为,你可以使用setWebEnvironment(boolean webEnvironment)。通过调用setApplicationContextClass(…),你可以完全控制ApplicationContext的类型。 - -**注**:当JUnit测试里使用SpringApplication时,调用setWebEnvironment(false)是可取的。 diff --git a/IV. Spring Boot features/22.6. Using the CommandLineRunner.md b/IV. Spring Boot features/22.6. Using the CommandLineRunner.md deleted file mode 100644 index 5ce744c7..00000000 --- a/IV. Spring Boot features/22.6. Using the CommandLineRunner.md +++ /dev/null @@ -1,15 +0,0 @@ -### 22.6. 命令行启动器 - -如果你想获取原始的命令行参数,或一旦SpringApplication启动,你需要运行一些特定的代码,你可以实现CommandLineRunner接口。在所有实现该接口的Spring beans上将调用run(String… args)方法。 -```java -import org.springframework.boot.* -import org.springframework.stereotype.* - -@Component -public class MyBean implements CommandLineRunner { - public void run(String... args) { - // Do something... - } -} -``` -如果一些CommandLineRunner beans被定义必须以特定的次序调用,你可以额外实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解。 diff --git a/IV. Spring Boot features/22.7. Application exit.md b/IV. Spring Boot features/22.7. Application exit.md deleted file mode 100644 index 959eef09..00000000 --- a/IV. Spring Boot features/22.7. Application exit.md +++ /dev/null @@ -1,5 +0,0 @@ -### 22.7. Application退出 - -每个SpringApplication在退出时为了确保ApplicationContext被优雅的关闭,将会注册一个JVM的shutdown钩子。所有标准的Spring生命周期回调(比如,DisposableBean接口或@PreDestroy注解)都能使用。 - -此外,如果beans想在应用结束时返回一个特定的退出码(exit code),可以实现org.springframework.boot.ExitCodeGenerator接口。 diff --git a/IV. Spring Boot features/23. Externalized Configuration.md b/IV. Spring Boot features/23. Externalized Configuration.md deleted file mode 100644 index 78e3c45c..00000000 --- a/IV. Spring Boot features/23. Externalized Configuration.md +++ /dev/null @@ -1,29 +0,0 @@ -### 23.外化配置 - -Spring Boot允许外化(externalize)你的配置,这样你能够在不同的环境下使用相同的代码。你可以使用properties文件,YAML文件,环境变量和命令行参数来外化配置。使用@Value注解,可以直接将属性值注入到你的beans中,并通过Spring的Environment抽象或绑定到结构化对象来访问。 - -Spring Boot使用一个非常特别的PropertySource次序来允许对值进行合理的覆盖,需要以下面的次序考虑属性: - -1. 命令行参数 -2. 来自于java:comp/env的JNDI属性 -3. Java系统属性(System.getProperties()) -4. 操作系统环境变量 -5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource -6. 在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量) -7. 在打包的jar内的应用程序配置文件(application.properties,包含YAML和profile变量) -8. 在@Configuration类上的@PropertySource注解 -9. 默认属性(使用SpringApplication.setDefaultProperties指定) - -下面是一个具体的示例(假设你开发一个使用name属性的@Component): -```java -import org.springframework.stereotype.* -import org.springframework.beans.factory.annotation.* - -@Component -public class MyBean { - @Value("${name}") - private String name; - // ... -} -``` -你可以将一个application.properties文件捆绑到jar内,用来提供一个合理的默认name属性值。当运行在生产环境时,可以在jar外提供一个application.properties文件来覆盖name属性。对于一次性的测试,你可以使用特定的命令行开关启动(比如,java -jar app.jar --name="Spring")。 diff --git a/IV. Spring Boot features/22. SpringApplication.md b/IV. Spring Boot features/23. SpringApplication.md similarity index 78% rename from IV. Spring Boot features/22. SpringApplication.md rename to IV. Spring Boot features/23. SpringApplication.md index 509530fd..e7cc2dda 100644 --- a/IV. Spring Boot features/22. SpringApplication.md +++ b/IV. Spring Boot features/23. SpringApplication.md @@ -1,11 +1,11 @@ -###22. 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); } ``` -当应用启动时,你应该会看到类似下面的东西(这是何方神兽??): +当应用启动时,你应该会看到类似下面的东西: ```other . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ @@ -13,7 +13,7 @@ public static void main(String[] args){ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: v1.2.2.BUILD-SNAPSHOT + :: Spring Boot :: v1.4.1.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] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy 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..e49bed2c --- /dev/null +++ b/IV. Spring Boot features/23.1 Startup failure.md @@ -0,0 +1,23 @@ +###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`实现,你[自己实现](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto-failure-analyzer)也很容易。 + +如果没有可用于处理该异常的失败分析器(failure analyzers),你需要展示完整的auto-configuration报告以便更好的查看出问题的地方,因此你需要启用`org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer`的[debug](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-external-config)属性,或开启[DEBUG日志级别](http://docs.spring.io/spring-boot/docs/1.4.1.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. Configuring random values.md b/IV. Spring Boot features/23.1. Configuring random values.md deleted file mode 100644 index 1ac41a61..00000000 --- a/IV. Spring Boot features/23.1. Configuring random values.md +++ /dev/null @@ -1,11 +0,0 @@ -### 23.1. 配置随机值 - -RandomValuePropertySource在注入随机值(比如,密钥或测试用例)时很有用。它能产生整数,longs或字符串,比如: -```java -my.secret=${random.value} -my.number=${random.int} -my.bignumber=${random.long} -my.number.less.than.ten=${random.int(10)} -my.number.in.range=${random.int[1024,65536]} -``` -random.int*语法是OPEN value (,max) CLOSE,此处OPEN,CLOSE可以是任何字符,并且value,max是整数。如果提供max,那么value是最小的值,max是最大的值(不包含在内)。 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..a25aa7db --- /dev/null +++ b/IV. Spring Boot features/23.10 Admin features.md @@ -0,0 +1,6 @@ +### 23.10 Admin特性 + +通过设置`spring.application.admin.enabled`属性可以启用管理相关的(admin-related)特性,这将暴露[SpringApplicationAdminMXBean](https://github.com/spring-projects/spring-boot/tree/v1.4.1.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.2. Accessing command line properties.md b/IV. Spring Boot features/23.2. Accessing command line properties.md deleted file mode 100644 index f2005f0b..00000000 --- a/IV. Spring Boot features/23.2. Accessing command line properties.md +++ /dev/null @@ -1,5 +0,0 @@ -### 23.2. 访问命令行属性 - -默认情况下,SpringApplication将任何可选的命令行参数(以'--'开头,比如,--server.port=9000)转化为property,并将其添加到Spring Environment中。如上所述,命令行属性总是优先于其他属性源。 - -如果你不想将命令行属性添加到Environment里,你可以使用SpringApplication.setAddCommandLineProperties(false)来禁止它们。 diff --git a/IV. Spring Boot features/23.2. Customizing the Banner.md b/IV. Spring Boot features/23.2. Customizing the Banner.md new file mode 100644 index 00000000..0d4592ef --- /dev/null +++ b/IV. Spring Boot features/23.2. Customizing the Banner.md @@ -0,0 +1,27 @@ +###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上方显示。 + +在banner.txt中可以使用如下占位符: + +| 变量 | 描述 | +| ----------- | :--------| +|${application.version}|MANIFEST.MF中声明的应用版本号,例如`Implementation-Version: 1.0`会打印`1.0`| +|${application.formatted-version}|MANIFEST.MF中声明的被格式化后的应用版本号(被括号包裹且以v作为前缀),用于显示,例如(`v1.0`)| +|${spring-boot.version}|当前Spring Boot的版本号,例如`1.4.1.RELEASE`| +|${spring-boot.formatted-version}|当前Spring Boot被格式化后的版本号(被括号包裹且以v作为前缀), 用于显示,例如(`v1.4.1.RELEASE`)| +|${Ansi.NAME}(或${AnsiColor.NAME},${AnsiBackground.NAME}, ${AnsiStyle.NAME})|NAME代表一种ANSI编码,具体详情查看[AnsiPropertySource](https://github.com/spring-projects/spring-boot/tree/v1.4.1.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()`方法。 + +你也可以使用`spring.main.banner-mode`属性决定将banner打印到何处,`System.out`(`console`),配置的logger(`log`)或都不输出(`off`)。 + +打印的banner将注册成一个名为`springBootBanner`的单例bean。 + +**注** YAML会将`off`映射为`false`,如果想在应用中禁用banner,你需要确保`off`添加了括号: +```json +spring: + main: + banner-mode: "off" +``` diff --git a/IV. Spring Boot features/23.3. Application property files.md b/IV. Spring Boot features/23.3. Application property files.md deleted file mode 100644 index 46455136..00000000 --- a/IV. Spring Boot features/23.3. Application property files.md +++ /dev/null @@ -1,22 +0,0 @@ -### 23.3. Application属性文件 - -SpringApplication将从以下位置加载application.properties文件,并把它们添加到Spring Environment中: - -1. 当前目录下的一个/config子目录 -2. 当前目录 -3. 一个classpath下的/config包 -4. classpath根路径(root) - -这个列表是按优先级排序的(列表中位置高的将覆盖位置低的)。 - -**注**:你可以使用YAML('.yml')文件替代'.properties'。 - -如果不喜欢将application.properties作为配置文件名,你可以通过指定spring.config.name环境属性来切换其他的名称。你也可以使用spring.config.location环境属性来引用一个明确的路径(目录位置或文件路径列表以逗号分割)。 -```shell -$ java -jar myproject.jar --spring.config.name=myproject -//or -$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties -``` -如果spring.config.location包含目录(相对于文件),那它们应该以/结尾(在加载前,spring.config.name产生的名称将被追加到后面)。不管spring.config.location是什么值,默认的搜索路径classpath:,classpath:/config,file:,file:config/总会被使用。以这种方式,你可以在application.properties中为应用设置默认值,然后在运行的时候使用不同的文件覆盖它,同时保留默认配置。 - -**注**:如果你使用环境变量而不是系统配置,大多数操作系统不允许以句号分割(period-separated)的key名称,但你可以使用下划线(underscores)代替(比如,使用SPRING_CONFIG_NAME代替spring.config.name)。如果你的应用运行在一个容器中,那么JNDI属性(java:comp/env)或servlet上下文初始化参数可以用来取代环境变量或系统属性,当然也可以使用环境变量或系统属性。 diff --git a/IV. Spring Boot features/23.3. Customizing SpringApplication.md b/IV. Spring Boot features/23.3. Customizing SpringApplication.md new file mode 100644 index 00000000..9cad81f5 --- /dev/null +++ b/IV. Spring Boot features/23.3. Customizing SpringApplication.md @@ -0,0 +1,13 @@ +### 23.3. 自定义SpringApplication + +如果默认的`SpringApplication`不符合你的口味,你可以创建一个本地实例并对它进行自定义。例如,想要关闭banner你可以这样写: +```java +public static void main(String[] args) { + SpringApplication app = new SpringApplication(MySpringConfiguration.class); + app.setBannerMode(Banner.Mode.OFF); + app.run(args); +} +``` +**注**:传递给`SpringApplication`的构造器参数将作为spring beans的配置源,多数情况下,它们是一些`@Configuration`类的引用,但也可能是XML配置或要扫描包的引用。 + +你也可以使用`application.properties`文件来配置`SpringApplication`,具体参考[24. Externalized 配置](24. Externalized Configuration.md),访问[SpringApplication Javadoc](http://docs.spring.io/spring-boot/docs/1.4.1.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..b37679ed --- /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](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/api/org/springframework/boot/builder/SpringApplicationBuilder.html)。 diff --git a/IV. Spring Boot features/23.4. Profile-specific properties.md b/IV. Spring Boot features/23.4. Profile-specific properties.md deleted file mode 100644 index f87028c1..00000000 --- a/IV. Spring Boot features/23.4. Profile-specific properties.md +++ /dev/null @@ -1,3 +0,0 @@ -### 23.4. 特定的Profile属性 - -除了application.properties文件,特定配置属性也能通过命令惯例application-{profile}.properties来定义。特定Profile属性从跟标准application.properties相同的路径加载,并且特定profile文件会覆盖默认的配置。 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..484a94fa --- /dev/null +++ b/IV. Spring Boot features/23.5. Application events and listeners.md @@ -0,0 +1,18 @@ +### 23.5. Application事件和监听器 + +除了常见的Spring框架事件,比如[ContextRefreshedEvent](http://docs.spring.io/spring/docs/4.3.3.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. 在运行开始,但除了监听器注册和初始化以外的任何处理之前,会发送一个`ApplicationStartedEvent`。 +2. 在Environment将被用于已知的上下文,但在上下文被创建前,会发送一个`ApplicationEnvironmentPreparedEvent`。 +3. 在refresh开始前,但在bean定义已被加载后,会发送一个`ApplicationPreparedEvent`。 +4. 在refresh之后,相关的回调处理完,会发送一个`ApplicationReadyEvent`,表示应用准备好接收请求了。 +4. 启动过程中如果出现异常,会发送一个`ApplicationFailedEvent`。 + +**注** 通常不需要使用application事件,但知道它们的存在是有用的(在某些场合可能会使用到),比如,在Spring Boot内部会使用事件处理各种任务。 diff --git a/IV. Spring Boot features/23.5. Placeholders in properties.md b/IV. Spring Boot features/23.5. Placeholders in properties.md deleted file mode 100644 index 851266cb..00000000 --- a/IV. Spring Boot features/23.5. Placeholders in properties.md +++ /dev/null @@ -1,8 +0,0 @@ -### 23.5. 属性占位符 - -当application.properties里的值被使用时,它们会被存在的Environment过滤,所以你能够引用先前定义的值(比如,系统属性)。 -```java -app.name=MyApp -app.description=${app.name} is a Spring Boot application -``` -**注**:你也能使用相应的技巧为存在的Spring Boot属性创建'短'变量,具体参考[Section 63.3, “Use ‘short’ command line arguments”](../IX. ‘How-to’ guides/63.3. Use ‘short’ command line arguments.md)。 diff --git a/IV. Spring Boot features/23.6. Using YAML instead of Properties.md b/IV. Spring Boot features/23.6. Using YAML instead of Properties.md deleted file mode 100644 index c1232a07..00000000 --- a/IV. Spring Boot features/23.6. Using YAML instead of Properties.md +++ /dev/null @@ -1,5 +0,0 @@ -### 23.6. 使用YAML代替Properties - -[YAML](http://yaml.org/)是JSON的一个超集,也是一种方便的定义层次配置数据的格式。无论你何时将[SnakeYAML ](http://code.google.com/p/snakeyaml/)库放到classpath下,SpringApplication类都会自动支持YAML作为properties的替换。 - -**注**:如果你使用'starter POMs',spring-boot-starter会自动提供SnakeYAML。 diff --git a/IV. Spring Boot features/23.6. Web environment.md b/IV. Spring Boot features/23.6. Web environment.md new file mode 100644 index 00000000..19ae9f39 --- /dev/null +++ b/IV. Spring Boot features/23.6. Web environment.md @@ -0,0 +1,9 @@ +### 23.6. Web环境 + +`SpringApplication`将尝试为你创建正确类型的`ApplicationContext`,默认情况下,根据你开发的是否为web应用决定使用`AnnotationConfigApplicationContext`或`AnnotationConfigEmbeddedWebApplicationContext`。 + +用于确定是否为web环境的算法相当简单(判断是否存在某些类),你可以使用`setWebEnvironment(boolean webEnvironment)`覆盖默认行为。 + +通过调用`setApplicationContextClass(…)`,你可以完全控制`ApplicationContext`的类型。 + +**注** 在Junit测试中使用`SpringApplication`,调用`setWebEnvironment(false)`是很有意义的。 diff --git a/IV. Spring Boot features/23.6.1. Loading YAML.md b/IV. Spring Boot features/23.6.1. Loading YAML.md deleted file mode 100644 index 5c8c1e15..00000000 --- a/IV. Spring Boot features/23.6.1. Loading YAML.md +++ /dev/null @@ -1,43 +0,0 @@ -### 23.6.1. 加载YAML - -Spring框架提供两个便利的类用于加载YAML文档,YamlPropertiesFactoryBean会将YAML作为Properties来加载,YamlMapFactoryBean会将YAML作为Map来加载。 - -示例: -```json -environments: - dev: - url: http://dev.bar.com - name: Developer Setup - prod: - url: http://foo.bar.com - name: My Cool App -``` -上面的YAML文档会被转化到下面的属性中: -```java -environments.dev.url=http://dev.bar.com -environments.dev.name=Developer Setup -environments.prod.url=http://foo.bar.com -environments.prod.name=My Cool App -``` -YAML列表被表示成使用[index]间接引用作为属性keys的形式,例如下面的YAML: -```json -my: - servers: - - dev.bar.com - - foo.bar.com -``` -将会转化到下面的属性中: -```java -my.servers[0]=dev.bar.com -my.servers[1]=foo.bar.com -``` -使用Spring DataBinder工具绑定那样的属性(这是@ConfigurationProperties做的事),你需要确定目标bean中有个java.util.List或Set类型的属性,并且需要提供一个setter或使用可变的值初始化它,比如,下面的代码将绑定上面的属性: -```java -@ConfigurationProperties(prefix="my") -public class Config { - private List servers = new ArrayList(); - public List getServers() { - return this.servers; - } -} -``` diff --git a/IV. Spring Boot features/23.6.2. Exposing YAML as properties in the Spring Environment.md b/IV. Spring Boot features/23.6.2. Exposing YAML as properties in the Spring Environment.md deleted file mode 100644 index 63b50c3c..00000000 --- a/IV. Spring Boot features/23.6.2. Exposing YAML as properties in the Spring Environment.md +++ /dev/null @@ -1,3 +0,0 @@ -### 23.6.2. 在Spring环境中使用YAML暴露属性 - -YamlPropertySourceLoader类能够用于将YAML作为一个PropertySource导出到Sprig Environment。这允许你使用熟悉的@Value注解和占位符语法访问YAML属性。 diff --git a/IV. Spring Boot features/23.6.3. Multi-profile YAML documents.md b/IV. Spring Boot features/23.6.3. Multi-profile YAML documents.md deleted file mode 100644 index 2c283b7f..00000000 --- a/IV. Spring Boot features/23.6.3. Multi-profile YAML documents.md +++ /dev/null @@ -1,18 +0,0 @@ -### 23.6.3. Multi-profile YAML文档 - -你可以在单个文件中定义多个特定配置(profile-specific)的YAML文档,并通过一个spring.profiles key标示应用的文档。例如: -```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配置被激活,那server.address属性将是127.0.0.1。如果development和production配置(profiles)没有启用,则该属性的值将是192.168.1.100。 diff --git a/IV. Spring Boot features/23.6.4. YAML shortcomings.md b/IV. Spring Boot features/23.6.4. YAML shortcomings.md deleted file mode 100644 index f0fe7214..00000000 --- a/IV. Spring Boot features/23.6.4. YAML shortcomings.md +++ /dev/null @@ -1,3 +0,0 @@ -### 23.6.4. YAML缺点 - -YAML文件不能通过@PropertySource注解加载。所以,在这种情况下,如果需要使用@PropertySource注解的方式加载值,那就要使用properties文件。 diff --git a/IV. Spring Boot features/23.7 Accessing application arguments.md b/IV. Spring Boot features/23.7 Accessing application arguments.md new file mode 100644 index 00000000..82cdfae6 --- /dev/null +++ b/IV. Spring Boot features/23.7 Accessing application arguments.md @@ -0,0 +1,21 @@ +### 23.7 访问应用参数 + +如果需要获取传递给`SpringApplication.run(…)`的应用参数,你可以注入一个`org.springframework.boot.ApplicationArguments`类型的bean。`ApplicationArguments`接口即提供对原始`String[]`参数的访问,也提供对解析成`option`和`non-option`参数的访问: +```java +import org.springframework.boot.* +import org.springframework.beans.factory.annotation.* +import org.springframework.stereotype.* + +@Component +public class MyBean { + + @Autowired + public MyBean(ApplicationArguments args) { + boolean debug = args.containsOption("debug"); + List files = args.getNonOptionArgs(); + // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] + } + +} +``` +**注** Spring Boot也会注册一个包含Spring `Environment`属性的`CommandLinePropertySource`,这就允许你使用`@Value`注解注入单个的应用参数。 diff --git a/IV. Spring Boot features/23.7. Typesafe Configuration Properties.md b/IV. Spring Boot features/23.7. Typesafe Configuration Properties.md deleted file mode 100644 index bd67f7e8..00000000 --- a/IV. Spring Boot features/23.7. Typesafe Configuration Properties.md +++ /dev/null @@ -1,44 +0,0 @@ -### 23.7. 类型安全的配置属性 - -使用@Value("${property}")注解注入配置属性有时可能比较笨重,特别是需要使用多个properties或你的数据本身有层次结构。为了控制和校验你的应用配置,Spring Boot提供一个允许强类型beans的替代方法来使用properties。 - -示例: -```java -@Component -@ConfigurationProperties(prefix="connection") -public class ConnectionSettings { - private String username; - private InetAddress remoteAddress; - // ... getters and setters -} -``` -当@EnableConfigurationProperties注解应用到你的@Configuration时,任何被@ConfigurationProperties注解的beans将自动被Environment属性配置。这种风格的配置特别适合与SpringApplication的外部YAML配置进行配合使用。 -```json -# application.yml -connection: - username: admin - remoteAddress: 192.168.1.1 -# additional configuration as required -``` -为了使用@ConfigurationProperties beans,你可以使用与其他任何bean相同的方式注入它们。 -```java -@Service -public class MyService { - @Autowired - private ConnectionSettings connection; - //... - @PostConstruct - public void openConnection() { - Server server = new Server(); - this.connection.configure(server); - } -} -``` -你可以通过在@EnableConfigurationProperties注解中直接简单的列出属性类来快捷的注册@ConfigurationProperties bean的定义。 -```java -@Configuration -@EnableConfigurationProperties(ConnectionSettings.class) -public class MyConfiguration { -} -``` -**注**:使用@ConfigurationProperties能够产生可被IDEs使用的元数据文件。具体参考[Appendix B, Configuration meta-data](../X. Appendices/B. Configuration meta-data.md)。 diff --git a/IV. Spring Boot features/23.7.1. Third-party configuration.md b/IV. Spring Boot features/23.7.1. Third-party configuration.md deleted file mode 100644 index 064e9f32..00000000 --- a/IV. Spring Boot features/23.7.1. Third-party configuration.md +++ /dev/null @@ -1,13 +0,0 @@ -### 23.7.1. 第三方配置 - -正如使用@ConfigurationProperties注解一个类,你也可以在@Bean方法上使用它。当你需要绑定属性到不受你控制的第三方组件时,这种方式非常有用。 - -为了从Environment属性配置一个bean,将@ConfigurationProperties添加到它的bean注册过程: -```java -@ConfigurationProperties(prefix = "foo") -@Bean -public FooComponent fooComponent() { - ... -} -``` -和上面ConnectionSettings的示例方式相同,任何以foo为前缀的属性定义都会被映射到FooComponent上。 diff --git a/IV. Spring Boot features/23.7.2. Relaxed binding.md b/IV. Spring Boot features/23.7.2. Relaxed binding.md deleted file mode 100644 index 900dbdda..00000000 --- a/IV. Spring Boot features/23.7.2. Relaxed binding.md +++ /dev/null @@ -1,21 +0,0 @@ -### 23.7.2. 松散的绑定(Relaxed binding) - -Spring Boot使用一些宽松的规则用于绑定Environment属性到@ConfigurationProperties beans,所以Environment属性名和bean属性名不需要精确匹配。常见的示例中有用的包括虚线分割(比如,context--path绑定到contextPath)和将环境属性转为大写字母(比如,PORT绑定port)。 - -示例: -```java -@Component -@ConfigurationProperties(prefix="person") -public class ConnectionSettings { - private String firstName; -} -``` -下面的属性名都能用于上面的@ConfigurationProperties类: - -| 属性 | 说明 | -| -------- | :----- | -|person.firstName|标准驼峰规则| -|person.first-name|虚线表示,推荐用于.properties和.yml文件中| -|PERSON_FIRST_NAME|大写形式,使用系统环境变量时推荐| - -Spring会尝试强制外部的应用属性在绑定到@ConfigurationProperties beans时类型是正确的。如果需要自定义类型转换,你可以提供一个ConversionService bean(bean id为conversionService)或自定义属性编辑器(通过一个CustomEditorConfigurer bean)。 diff --git a/IV. Spring Boot features/23.7.3. @ConfigurationProperties Validation.md b/IV. Spring Boot features/23.7.3. @ConfigurationProperties Validation.md deleted file mode 100644 index 6cfb91c8..00000000 --- a/IV. Spring Boot features/23.7.3. @ConfigurationProperties Validation.md +++ /dev/null @@ -1,15 +0,0 @@ -### 23.7.3. @ConfigurationProperties校验 - -Spring Boot将尝试校验外部的配置,默认使用JSR-303(如果在classpath路径中)。你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解: -```java -@Component -@ConfigurationProperties(prefix="connection") -public class ConnectionSettings { - @NotNull - private InetAddress remoteAddress; - // ... getters and setters -} -``` -你也可以通过创建一个叫做configurationPropertiesValidator的bean来添加自定义的Spring Validator。 - -**注**:spring-boot-actuator模块包含一个暴露所有@ConfigurationProperties beans的端点。简单地将你的web浏览器指向/configprops或使用等效的JMX端点。具体参考[Production ready features](../V. Spring Boot Actuator/40. Endpoints.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 new file mode 100644 index 00000000..29531eed --- /dev/null +++ b/IV. Spring Boot features/23.8 Using the ApplicationRunner or CommandLineRunner.md @@ -0,0 +1,19 @@ +### 23.8. 使用ApplicationRunner或CommandLineRunner + +如果需要在`SpringApplication`启动后执行一些特殊的代码,你可以实现`ApplicationRunner`或`CommandLineRunner`接口,这两个接口工作方式相同,都只提供单一的`run`方法,该方法仅在`SpringApplication.run(…)`完成之前调用。 + +`CommandLineRunner`接口能够访问string数组类型的应用参数,而`ApplicationRunner`使用的是上面描述过的`ApplicationArguments`接口: +```java +import org.springframework.boot.* +import org.springframework.stereotype.* + +@Component +public class MyBean implements CommandLineRunner { + + public void run(String... args) { + // Do something... + } + +} +``` +如果某些定义的`CommandLineRunner`或`ApplicationRunner` beans需要以特定的顺序调用,你可以实现`org.springframework.core.Ordered`接口或使用`org.springframework.core.annotation.Order`注解。 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..6064c837 --- /dev/null +++ b/IV. Spring Boot features/23.9 Application exit.md @@ -0,0 +1,5 @@ +### 23.9 Application退出 + +为确保`ApplicationContext`在退出时被平静的(gracefully)关闭,每个`SpringApplication`都会注册一个JVM的shutdown钩子,所有标准的Spring生命周期回调(比如`DisposableBean`接口或`@PreDestroy`注解)都能使用。 + +此外,如果想在应用结束时返回特定的退出码(exit code),这些beans可以实现`org.springframework.boot.ExitCodeGenerator`接口。 diff --git a/IV. Spring Boot features/24. Externalized Configuration.md b/IV. Spring Boot features/24. Externalized Configuration.md new file mode 100644 index 00000000..28f58fdd --- /dev/null +++ b/IV. Spring Boot features/24. Externalized Configuration.md @@ -0,0 +1,51 @@ +### 24.外部化配置 + +Spring Boot允许将配置外部化(externalize),这样你就能够在不同的环境下使用相同的代码。你可以使用properties文件,YAML文件,环境变量和命令行参数来外部化配置。使用@Value注解,可以直接将属性值注入到beans中,然后通过Spring的`Environment`抽象或通过`@ConfigurationProperties`[绑定到结构化对象](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties)来访问。 + +Spring Boot设计了一个非常特别的`PropertySource`顺序,以允许对属性值进行合理的覆盖,属性会以如下的顺序进行设值: + +1. home目录下的[devtools全局设置属性](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#using-boot-devtools-globalsettings)(`~/.spring-boot-devtools.properties`,如果devtools激活)。 +2. 测试用例上的[@TestPropertySource](http://docs.spring.io/spring/docs/4.3.3.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html)注解。 +3. 测试用例上的[@SpringBootTest#properties](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/api/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTest.html)注解。 +4. 命令行参数 +5. 来自`SPRING_APPLICATION_JSON`的属性(环境变量或系统属性中内嵌的内联JSON)。 +6. `ServletConfig`初始化参数。 +7. `ServletContext`初始化参数。 +8. 来自于`java:comp/env`的JNDI属性。 +9. Java系统属性(System.getProperties())。 +10. 操作系统环境变量。 +11. RandomValuePropertySource,只包含`random.*`中的属性。 +12. 没有打进jar包的[Profile-specific应用属性](http://docs.spring.io/spring-boot/docs/1.4.1.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/1.4.1.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`注解](http://docs.spring.io/spring/docs/4.3.3.RELEASE/javadoc-api/org/springframework/context/annotation/PropertySource.html)。 +17. 默认属性(使用`SpringApplication.setDefaultProperties`指定)。 + +下面是具体的示例,假设你开发一个使用name属性的`@Component`: +```java +import org.springframework.stereotype.* +import org.springframework.beans.factory.annotation.* + +@Component +public class MyBean { + @Value("${name}") + private String name; + // ... +} +``` +你可以将一个`application.properties`放到应用的classpath下,为`name`提供一个合适的默认属性值。当在新的环境中运行时,可以在jar包外提供一个`application.properties`覆盖`name`属性。对于一次性的测试,你可以使用特定的命令行开关启动应用(比如,`java -jar app.jar --name="Spring"`)。 + +**注** `SPRING_APPLICATION_JSON`属性可以通过命令行的环境变量设置,例如,在一个UNIX shell中可以这样: +```shell +$ SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar +``` +本示例中,如果是Spring `Environment`,你可以以`foo.bar=spam`结尾;如果在一个系统变量中,可以提供作为`spring.application.json`的JSON字符串: +```shell +$ java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar +``` +或命令行参数: +```shell +$ java -jar myapp.jar --spring.application.json='{"foo":"bar"}' +``` +或作为一个JNDI变量`java:comp/env/spring.application.json`。 diff --git a/IV. Spring Boot features/24. Profiles.md b/IV. Spring Boot features/24. Profiles.md deleted file mode 100644 index b7df576b..00000000 --- a/IV. Spring Boot features/24. Profiles.md +++ /dev/null @@ -1,17 +0,0 @@ -### 24. Profiles -Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。任何@Component或@Configuration都能被@Profile标记,从而限制加载它的时机。 -```java -@Configuration -@Profile("production") -public class ProductionConfiguration { - // ... -} -``` -以正常的Spring方式,你可以使用一个spring.profiles.active的Environment属性来指定哪个配置生效。你可以使用平常的任何方式来指定该属性,例如,可以将它包含到你的application.properties中: -```java -spring.profiles.active=dev,hsqldb -``` -或使用命令行开关: -```shell ---spring.profiles.active=dev,hsqldb -``` diff --git a/IV. Spring Boot features/24.1. Adding active profiles.md b/IV. Spring Boot features/24.1. Adding active profiles.md deleted file mode 100644 index da57b02e..00000000 --- a/IV. Spring Boot features/24.1. Adding active profiles.md +++ /dev/null @@ -1,15 +0,0 @@ -### 24.1. 添加激活的配置(profiles) - -spring.profiles.active属性和其他属性一样都遵循相同的排列规则,最高的PropertySource获胜。也就是说,你可以在application.properties中指定生效的配置,然后使用命令行开关替换它们。 - -有时,将特定的配置属性添加到生效的配置中而不是替换它们是有用的。spring.profiles.include属性可以用来无条件的添加生效的配置。SpringApplication的入口点也提供了一个用于设置额外配置的Java API(比如,在那些通过spring.profiles.active属性生效的配置之上):参考setAdditionalProfiles()方法。 - -示例:当一个应用使用下面的属性,并用`--spring.profiles.active=prod`开关运行,那proddb和prodmq配置也会生效: -```java ---- -my.property: fromyamlfile ---- -spring.profiles: prod -spring.profiles.include: proddb,prodmq -``` -**注**:spring.profiles属性可以定义到一个YAML文档中,用于决定什么时候该文档被包含进配置中。具体参考[Section 63.6, “Change configuration depending on the environment”](../IX. ‘How-to’ guides/63.6. Change configuration depending on the environment.md) diff --git a/IV. Spring Boot features/24.1. Configuring random values.md b/IV. Spring Boot features/24.1. Configuring random values.md new file mode 100644 index 00000000..11a1fe15 --- /dev/null +++ b/IV. Spring Boot features/24.1. Configuring random values.md @@ -0,0 +1,11 @@ +### 24.1. 配置随机值 + +在注入随机值(比如,密钥或测试用例)时`RandomValuePropertySource`很有用,它能产生整数,longs或字符串,比如: +```java +my.secret=${random.value} +my.number=${random.int} +my.bignumber=${random.long} +my.number.less.than.ten=${random.int(10)} +my.number.in.range=${random.int[1024,65536]} +``` +`random.int*`语法是`OPEN value (,max) CLOSE`,此处`OPEN,CLOSE`可以是任何字符,并且`value,max`是整数。如果提供`max`,那么`value`是最小值,`max`是最大值(不包含在内)。 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..3f2354bc --- /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. Programmatically setting profiles.md b/IV. Spring Boot features/24.2. Programmatically setting profiles.md deleted file mode 100644 index fe11064d..00000000 --- a/IV. Spring Boot features/24.2. Programmatically setting profiles.md +++ /dev/null @@ -1,3 +0,0 @@ -### 24.2.以编程方式设置profiles - -在应用运行前,你可以通过调用SpringApplication.setAdditionalProfiles(…)方法,以编程的方式设置生效的配置。使用Spring的ConfigurableEnvironment接口激动配置也是可行的。 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..b717484c --- /dev/null +++ b/IV. Spring Boot features/24.3. Application property files.md @@ -0,0 +1,30 @@ +### 24.3. Application属性文件 + +`SpringApplication`将从以下位置加载`application.properties`文件,并把它们添加到Spring `Environment`中: + +1. 当前目录下的`/config`子目录。 +2. 当前目录。 +3. classpath下的`/config`包。 +4. classpath根路径(root)。 + +该列表是按优先级排序的(列表中位置高的路径下定义的属性将覆盖位置低的)。 + +**注** 你可以使用[YAML('.yml')文件](http://docs.spring.io/spring-boot/docs/1.4.1.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`决定加载哪个文件,所以它们必须定义为environment属性(通常为OS env,系统属性或命令行参数)。 + +如果`spring.config.location`包含目录(相对于文件),那它们应该以`/`结尾(在被加载前,`spring.config.name`关联的名称将被追加到后面,包括profile-specific的文件名)。`spring.config.location`下定义的文件使用方法跟往常一样,没有profile-specific变量支持的属性,将被profile-specific的属性覆盖。 + +不管`spring.config.location`配置什么值,默认总会按照`classpath:,classpath:/config,file:,file:config/`的顺序进行搜索,优先级由低到高,也就是`file:config/`获胜。如果你指定自己的位置,它们会优先于所有的默认位置(locations),并使用相同的由低到高的优先级顺序。那样,你就可以在`application.properties`为应用设置默认值,然后在运行的时候使用不同的文件覆盖它,同时保留默认配置。 + +**注** 如果使用环境变量而不是系统属性,需要注意多数操作系统的key名称不允许以句号分割(period-separated),但你可以使用下划线(underscores)代替(比如,使用`SPRING_CONFIG_NAME`代替`spring.config.name`)。 + +**注** 如果应用运行在容器中,那么JNDI属性(java:comp/env)或servlet上下文初始化参数可以用来代替环境变量或系统属性,当然也可以使用环境变量或系统属性。 diff --git a/IV. Spring Boot features/24.3. Profile specific configuration files.md b/IV. Spring Boot features/24.3. Profile specific configuration files.md deleted file mode 100644 index bd871c33..00000000 --- a/IV. Spring Boot features/24.3. Profile specific configuration files.md +++ /dev/null @@ -1,3 +0,0 @@ -### 24.3. Profile特定配置文件 - -application.properties(或application.yml)和通过@ConfigurationProperties引用的文件这两种配置特定变种都被当作文件来加载的,具体参考[Section 23.3, “Profile specific properties”](23.4. Profile-specific properties.md)。 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..908fc5c6 --- /dev/null +++ b/IV. Spring Boot features/24.4. Profile-specific properties.md @@ -0,0 +1,11 @@ +### 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..3d73ded7 --- /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属性创建'短'变量,具体参考[Section 69.4, “Use ‘short’ command line arguments”](../IX. ‘How-to’ guides/63.3. 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..8e648269 --- /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.1. Loading YAML.md b/IV. Spring Boot features/24.6.1. Loading YAML.md new file mode 100644 index 00000000..77247e3c --- /dev/null +++ b/IV. Spring Boot features/24.6.1. Loading YAML.md @@ -0,0 +1,43 @@ +### 24.6.1. 加载YAML + +Spring框架提供两个便利的类用于加载YAML文档,`YamlPropertiesFactoryBean`会将YAML加载为`Properties`,`YamlMapFactoryBean`会将YAML加载为`Map`。 + +例如,下面的YAML文档: +```json +environments: + dev: + url: http://dev.bar.com + name: Developer Setup + prod: + url: http://foo.bar.com + name: My Cool App +``` +会被转化到这些属性: +```java +environments.dev.url=http://dev.bar.com +environments.dev.name=Developer Setup +environments.prod.url=http://foo.bar.com +environments.prod.name=My Cool App +``` +YAML列表被表示成使用`[index]`间接引用作为属性keys的形式,例如下面的YAML: +```json +my: + servers: + - dev.bar.com + - foo.bar.com +``` +将会转化到这些属性: +```java +my.servers[0]=dev.bar.com +my.servers[1]=foo.bar.com +``` +使用Spring `DataBinder`工具集绑定这些属性(这是`@ConfigurationProperties`做的事)时,你需要确保目标bean有个`java.util.List`或`Set`类型的属性,并且需要提供一个setter或使用可变的值初始化它,比如,下面的代码将绑定上面的属性: +```java +@ConfigurationProperties(prefix="my") +public class Config { + private List servers = new ArrayList(); + public List getServers() { + return this.servers; + } +} +``` 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..707a396d --- /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.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..570e7001 --- /dev/null +++ b/IV. Spring Boot features/24.6.3. Multi-profile YAML documents.md @@ -0,0 +1,39 @@ +### 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 new file mode 100644 index 00000000..e88afe66 --- /dev/null +++ b/IV. Spring Boot features/24.6.4. YAML shortcomings.md @@ -0,0 +1,3 @@ +### 24.6.4. YAML缺点 + +YAML文件不能通过`@PropertySource`注解加载,如果需要使用该方式,那就必须使用properties文件。 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..65635b97 --- /dev/null +++ b/IV. Spring Boot features/24.6.5 Merging YAML lists.md @@ -0,0 +1,46 @@ +###24.6.5 合并YAML列表 + +正如[上面](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/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 new file mode 100644 index 00000000..872c2bd8 --- /dev/null +++ b/IV. Spring Boot features/24.7. Type-safe Configuration Properties.md @@ -0,0 +1,70 @@ +### 23.7. 类型安全的配置属性 + +使用`@Value("${property}")`注解注入配置属性有时会比较麻烦(cumbersome),特别是需要使用多个properties,或数据本身有层次结构。Spring Boot提供一种使用配置的替代方法,这种方法允许强类型的beans以管理和校验应用的配置,例如: +```java +@Component +@ConfigurationProperties(prefix="connection") +public class ConnectionSettings { + private String username; + private InetAddress remoteAddress; + // ... getters and setters +} +``` +**注** 添加setter和getter是相当正确的,因为绑定是通过标准的Java Beans属性描述符进行的,跟Spring MVC一样,对于不可变类型或从`String`强制转换的也一样。只要它们初始化了,maps,collections,arrays只需要getter,setter不是必须的,因为绑定者(binder)能够改变它们。如果有setter,maps,collections,arrays就能够被创建。Maps和collections可以仅通过getter进行扩展,而arrays需要setter。嵌套的POJO属性只能通过默认的构造器,或接收一个单一的能够转换为string的值的构造器。有些人使用Project Lombok自动添加getters和setters。 + +**注** 查看[@Value和@ConfigurationProperties](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-external-config-vs-value)之间的区别。 + +你需要在`@EnableConfigurationProperties`注解中列出要注册的属性类: +```java +@Configuration +@EnableConfigurationProperties(ConnectionProperties.class) +public class MyConfiguration { +} +``` +**注** 当`@ConfigurationProperties` bean以这种方式注册时,该bean将有个约定的名称:`-`,``是`@ConfigurationProperties`注解中定义的environment key前缀,``是bean的全限定名。如果注解中没有提供任何前缀,那就只使用bean的全限定名。上述示例中的bean名称将是`connection-com.example.ConnectionProperties`,假定`ConnectionProperties`位于`com.example`包下。 + +尽管上述配置为`ConnectionProperties`创建了一个常规的bean,不过我们建议`@ConfigurationProperties`只用来处理environment(只用于注入配置,系统环境之类的),特别是不要注入上下文中的其他beans。话虽如此,`@EnableConfigurationProperties`注解会自动应用到你的项目,任何存在的,注解`@ConfigurationProperties`的bean将会从`Environment`属性中得到配置。只要确定`ConnectionProperties`是一个已存在的bean,`MyConfiguration`就可以不用了。 +```java +@Component +@ConfigurationProperties(prefix="connection") +public class ConnectionProperties { + + // ... getters and setters + +} +``` +这种配置风格跟`SpringApplication`的外部化YAML配置配合的很好: +```json +# application.yml + +connection: + username: admin + remoteAddress: 192.168.1.1 + +# additional configuration as required +``` +为了使用`@ConfigurationProperties` beans,你可以像使用其他bean那样注入它们: +```java +@Service +public class MyService { + + private final ConnectionProperties connection; + + @Autowired + public MyService(ConnectionProperties connection) { + this.connection = connection; + } + + //... + + @PostConstruct + public void openConnection() { + Server server = new Server(); + this.connection.configure(server); + } + +} +``` +**注** 使用`@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..73da0bb8 --- /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 = "foo") +@Bean +public FooComponent fooComponent() { + ... +} +``` +和上面`ConnectionSettings`的示例方式相同,所有以`foo`为前缀的属性定义都会被映射到`FooComponent`上。 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..1f8bef46 --- /dev/null +++ b/IV. Spring Boot features/24.7.2. Relaxed binding.md @@ -0,0 +1,29 @@ +### 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; + } + +} +``` +下面的属性名都能使用: + +| 属性 | 说明 | +| -------- | :----- | +|`person.firstName`|标准驼峰规则| +|`person.first-name`|虚线表示,推荐用于`.properties`和`.yml`文件中| +|`person.first_name`|下划线表示,用于`.properties`和`.yml`文件的可选格式| +|`PERSON_FIRST_NAME`|大写形式,使用系统环境变量时推荐| 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..b6382c15 --- /dev/null +++ b/IV. Spring Boot features/24.7.3 Properties conversion.md @@ -0,0 +1,5 @@ +### 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 new file mode 100644 index 00000000..a2869129 --- /dev/null +++ b/IV. Spring Boot features/24.7.4. @ConfigurationProperties Validation.md @@ -0,0 +1,39 @@ +### 24.7.4. @ConfigurationProperties校验 + +Spring Boot将尝试校验外部配置,默认使用JSR-303(如果在classpath路径中),你只需要将JSR-303 `javax.validation`约束注解添加到`@ConfigurationProperties`类上: +```java +@ConfigurationProperties(prefix="connection") +public class ConnectionProperties { + + @NotNull + private InetAddress remoteAddress; + + // ... getters and setters + +} +``` +为了校验内嵌属性的值,你需要使用`@Valid`注解关联的字段以触发它的校验,例如: +```java +@ConfigurationProperties(prefix="connection") +public class ConnectionProperties { + + @NotNull + @Valid + private RemoteAddress remoteAddress; + + // ... getters and setters + + public static class RemoteAddress { + + @NotEmpty + public String hostname; + + // ... getters and setters + + } + +} +``` +你也可以通过创建一个叫做`configurationPropertiesValidator`的bean来添加自定义的Spring `Validator`。`@Bean`方法需要声明为`static`,因为配置属性校验器在应用程序生命周期中创建的比较早,将`@Bean`方法声明为`static`允许该bean在创建时不需要实例化`@Configuration`类,从而避免了早期实例化(early instantiation)的所有问题。相关的示例可以看[这里](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-property-validation)。 + +**注** `spring-boot-actuator`模块包含一个暴露所有`@ConfigurationProperties` beans的端点(endpoint),通过浏览器打开`/configprops`进行浏览,或使用等效的JMX端点,具体参考[Production ready features](../V. Spring Boot Actuator/40. 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 new file mode 100644 index 00000000..97b5a5d7 --- /dev/null +++ b/IV. Spring Boot features/24.7.5 @ConfigurationProperties vs. @Value.md @@ -0,0 +1,11 @@ +### 24.7.5 @ConfigurationProperties vs. @Value + +`@Value`是Spring容器的一个核心特性,它没有提供跟type-safe Configuration Properties相同的特性。下面的表格总结了`@ConfigurationProperties`和`@Value`支持的特性: + +|特性|`@ConfigurationProperties`|`@Value`| +|---|---|---| +|[Relaxed绑定](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-external-config-relaxed-binding)|Yes|No| +|[Meta-data支持](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#configuration-metadata)|Yes|No| +|`SpEL`表达式|No|Yes| + +如果你为自己的组件定义了一系列的配置keys,我们建议你将它们以`@ConfigurationProperties`注解的POJO进行分组。由于`@Value`不支持relaxed绑定,所以如果你使用环境变量提供属性值的话,它就不是很好的选择。最后,尽管`@Value`可以写`SpEL`表达式,但这些表达式不会处理来自[Application属性文件](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-external-config-application-property-files)的属性。 diff --git a/IV. Spring Boot features/25. Logging.md b/IV. Spring Boot features/25. Logging.md deleted file mode 100644 index be7fcee1..00000000 --- a/IV. Spring Boot features/25. Logging.md +++ /dev/null @@ -1,6 +0,0 @@ -### 25. 日志 -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/)提供配置。每种情况下都会预先配置使用控制台输出,也可以使用可选的文件输出。 - -默认情况下,如果你使用'Starter POMs',那么就会使用Logback记录日志。为了确保那些使用Java Util Logging, Commons Logging, Log4J或SLF4J的依赖库能够正常工作,正确的Logback路由也被包含进来。 - -**注**:如果上面的列表看起来令人困惑,不要担心,Java有很多可用的日志框架。通常,你不需要改变日志依赖,Spring Boot默认的就能很好的工作。 diff --git a/IV. Spring Boot features/25. Profiles.md b/IV. Spring Boot features/25. Profiles.md new file mode 100644 index 00000000..c35f8272 --- /dev/null +++ b/IV. Spring Boot features/25. Profiles.md @@ -0,0 +1,19 @@ +### 25. Profiles +Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只在特定的环境下生效。任何`@Component`或`@Configuration`都能注解`@Profile`,从而限制加载它的时机: +```java +@Configuration +@Profile("production") +public class ProductionConfiguration { + + // ... + +} +``` +以正常的Spring方式,你可以使用`spring.profiles.active`的`Environment`属性来指定哪个配置生效。你可以使用通常的任何方式来指定该属性,例如,可以将它包含到`application.properties`中: +```java +spring.profiles.active=dev,hsqldb +``` +或使用命令行开关: +```shell +--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..d4b85199 --- /dev/null +++ b/IV. Spring Boot features/25.1. Adding active profiles.md @@ -0,0 +1,15 @@ +### 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文档中,以决定何时将该文档包含进配置,具体参考[Section 63.6, “Change configuration depending on the environment”](../IX. ‘How-to’ guides/63.6. Change configuration depending on the environment.md) diff --git a/IV. Spring Boot features/25.2. Console output.md b/IV. Spring Boot features/25.2. Console output.md deleted file mode 100644 index f8912b9a..00000000 --- a/IV. Spring Boot features/25.2. Console output.md +++ /dev/null @@ -1,7 +0,0 @@ -### 25.2. 控制台输出 - -默认的日志配置会在写日志消息时将它们回显到控制台。默认,ERROR, WARN和INFO级别的消息会被记录。可以在启动应用时,通过`--debug`标识开启控制台的DEBUG级别日志记录。 -```shell -$ java -jar myapp.jar --debug -``` -如果你的终端支持ANSI,为了增加可读性将会使用彩色的日志输出。你可以设置`spring.output.ansi.enabled`为一个[支持的值](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/api/org/springframework/boot/ansi/AnsiOutput.Enabled.html)来覆盖自动检测。 diff --git a/IV. Spring Boot features/25.2. Programmatically setting profiles.md b/IV. Spring Boot features/25.2. Programmatically setting profiles.md new file mode 100644 index 00000000..9f5d8245 --- /dev/null +++ b/IV. Spring Boot features/25.2. Programmatically setting profiles.md @@ -0,0 +1,3 @@ +### 25.2.以编程方式设置profiles + +在应用运行前,你可以通过调用`SpringApplication.setAdditionalProfiles(…)`方法,以编程的方式设置激活的配置,也可以使用Spring的`ConfigurableEnvironment`接口激活配置(profiles)。 diff --git a/IV. Spring Boot features/25.3. File output.md b/IV. Spring Boot features/25.3. File output.md deleted file mode 100644 index aa4c1d09..00000000 --- a/IV. Spring Boot features/25.3. File output.md +++ /dev/null @@ -1,13 +0,0 @@ -### 25.3. 文件输出 - -默认情况下,Spring Boot只会将日志记录到控制台而不会写进日志文件。如果除了输出到控制台你还想写入到日志文件,那你需要设置`logging.file`或`logging.path`属性(例如在你的application.properties中)。 - -下表显示如何组合使用`logging.*`: - -|logging.file|logging.path| 示例 | 描述 | -| -------- | :----- | :----- | :-----| -| (none) | (none) | | 只记录到控制台 | -|Specific file|(none)|my.log|写到特定的日志文件里,名称可以是一个精确的位置或相对于当前目录| -|(none)|Specific folder|/var/log|写到特定文件夹下的spring.log里,名称可以是一个精确的位置或相对于当前目录| - -日志文件每达到10M就会被轮换(分割),和控制台一样,默认记录ERROR, WARN和INFO级别的信息。 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..9f71dcd9 --- /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.3, “Profile specific properties”](24.4. Profile-specific properties.md)。 diff --git a/IV. Spring Boot features/25.4. Log Levels.md b/IV. Spring Boot features/25.4. Log Levels.md deleted file mode 100644 index 19cb3f13..00000000 --- a/IV. Spring Boot features/25.4. Log Levels.md +++ /dev/null @@ -1,9 +0,0 @@ -### 25.4. 日志级别 - -所有支持的日志系统在Spring的Environment(例如在application.properties里)都有通过'logging.level.*=LEVEL'('LEVEL'是TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF中的一个)设置的日志级别。 - -示例:application.properties -```java -logging.level.org.springframework.web: DEBUG -logging.level.org.hibernate: ERROR -``` diff --git a/IV. Spring Boot features/25.5. Custom log configuration.md b/IV. Spring Boot features/25.5. Custom log configuration.md deleted file mode 100644 index 9bdae4ac..00000000 --- a/IV. Spring Boot features/25.5. Custom log configuration.md +++ /dev/null @@ -1,24 +0,0 @@ -### 25.5. 自定义日志配置 - -通过将适当的库添加到classpath,可以激活各种日志系统。然后在classpath的根目录(root)或通过Spring Environment的`logging.config`属性指定的位置提供一个合适的配置文件来达到进一步的定制(注意由于日志是在ApplicationContext被创建之前初始化的,所以不可能在Spring的@Configuration文件中,通过@PropertySources控制日志。系统属性和平常的Spring Boot外部配置文件能正常工作)。 - -根据你的日志系统,下面的文件会被加载: - -| 日志系统 | 定制 | -| -------- | :-----: | -|Logback|logback.xml| -|Log4j|log4j.properties或log4j.xml| -|Log4j2|log4j2.xml| -|JDK (Java Util Logging)|logging.properties| - -为了帮助定制一些其他的属性,从Spring的Envrionment转换到系统属性: - -| Spring Environment| System Property| 评价 | -| -------- | :-----: | :----: | -|logging.file|LOG_FILE|如果定义,在默认的日志配置中使用| -|logging.path|LOG_PATH|如果定义,在默认的日志配置中使用| -|PID|PID|当前的处理进程(process)ID(如果能够被发现且还没有作为操作系统环境变量被定义)| - -所有支持的日志系统在解析它们的配置文件时都能查询系统属性。具体可以参考spring-boot.jar中的默认配置。 - -**注**:在运行可执行的jar时,Java Util Logging有类加载问题,我们建议你尽可能避免使用它。 diff --git a/IV. Spring Boot features/26. Developing web applications.md b/IV. Spring Boot features/26. Developing web applications.md deleted file mode 100644 index 141b4a4c..00000000 --- a/IV. Spring Boot features/26. Developing web applications.md +++ /dev/null @@ -1,2 +0,0 @@ -### 26. 开发Web应用 -Spring Boot非常适合开发web应用程序。你可以使用内嵌的Tomcat,Jetty或Undertow轻轻松松地创建一个HTTP服务器。大多数的web应用都使用spring-boot-starter-web模块进行快速搭建和运行。 diff --git a/IV. Spring Boot features/26. Logging.md b/IV. Spring Boot features/26. Logging.md new file mode 100644 index 00000000..285428fd --- /dev/null +++ b/IV. Spring Boot features/26. Logging.md @@ -0,0 +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路由也会包含进来。 + +**注** 如果上面的列表看起来令人困惑,不要担心,Java有很多可用的日志框架。通常,你不需要改变日志依赖,Spring Boot默认的就能很好的工作。 diff --git a/IV. Spring Boot features/25.1. Log format.md b/IV. Spring Boot features/26.1. Log format.md similarity index 82% rename from IV. Spring Boot features/25.1. Log format.md rename to IV. Spring Boot features/26.1. Log format.md index 560d5bdb..f20d6bca 100644 --- a/IV. Spring Boot features/25.1. Log format.md +++ b/IV. Spring Boot features/26.1. Log format.md @@ -1,4 +1,4 @@ -### 25.1. 日志格式 +### 26.1. 日志格式 Spring Boot默认的日志输出格式如下: ```java @@ -11,9 +11,11 @@ Spring Boot默认的日志输出格式如下: 输出的节点(items)如下: 1. 日期和时间 - 精确到毫秒,且易于排序。 -2. 日志级别 - ERROR, WARN, INFO, DEBUG 或 TRACE。 +2. 日志级别 - `ERROR`, `WARN`, `INFO`, `DEBUG` 或 `TRACE`。 3. Process ID。 -4. 一个用于区分实际日志信息开头的---分隔符。 +4. `---`分隔符,用于区分实际日志信息开头。 5. 线程名 - 包括在方括号中(控制台输出可能会被截断)。 6. 日志名 - 通常是源class的类名(缩写)。 7. 日志信息。 + +**注** Logback没有`FATAL`级别,它会映射到`ERROR`。 diff --git a/IV. Spring Boot features/26.1.1. Spring MVC auto-configuration.md b/IV. Spring Boot features/26.1.1. Spring MVC auto-configuration.md deleted file mode 100644 index 0b847588..00000000 --- a/IV. Spring Boot features/26.1.1. Spring MVC auto-configuration.md +++ /dev/null @@ -1,13 +0,0 @@ -### 26.1.1. Spring MVC自动配置 - -Spring Boot为Spring MVC提供适用于多数应用的自动配置功能。在Spring默认基础上,自动配置添加了以下特性: - -1. 引入ContentNegotiatingViewResolver和BeanNameViewResolver beans。 -2. 对静态资源的支持,包括对WebJars的支持。 -3. 自动注册Converter,GenericConverter,Formatter beans。 -4. 对HttpMessageConverters的支持。 -5. 自动注册MessageCodeResolver。 -6. 对静态index.html的支持。 -7. 对自定义Favicon的支持。 - -如果想全面控制Spring MVC,你可以添加自己的@Configuration,并使用@EnableWebMvc对其注解。如果想保留Spring Boot MVC的特性,并只是添加其他的[MVC配置](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle#mvc)(拦截器,formatters,视图控制器等),你可以添加自己的WebMvcConfigurerAdapter类型的@Bean(不使用@EnableWebMvc注解)。 diff --git a/IV. Spring Boot features/26.1.2. HttpMessageConverters.md b/IV. Spring Boot features/26.1.2. HttpMessageConverters.md deleted file mode 100644 index 68b076d3..00000000 --- a/IV. Spring Boot features/26.1.2. HttpMessageConverters.md +++ /dev/null @@ -1,22 +0,0 @@ -### 26.1.2. HttpMessageConverters - -Spring MVC使用HttpMessageConverter接口转换HTTP请求和响应。合理的缺省值被包含的恰到好处(out of the box),例如对象可以自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用则使用它,否则使用JAXB)。字符串默认使用UTF-8编码。 - -如果需要添加或自定义转换器,你可以使用Spring Boot的HttpMessageConverters类: -```java -import org.springframework.boot.autoconfigure.web.HttpMessageConverters; -import org.springframework.context.annotation.*; -import org.springframework.http.converter.*; - -@Configuration -public class MyConfiguration { - - @Bean - public HttpMessageConverters customConverters() { - HttpMessageConverter additional = ... - HttpMessageConverter another = ... - return new HttpMessageConverters(additional, another); - } -} -``` -任何在上下文中出现的HttpMessageConverter bean将会添加到converters列表,你可以通过这种方式覆盖默认的转换器(converters)。 diff --git a/IV. Spring Boot features/26.1.3. MessageCodesResolver.md b/IV. Spring Boot features/26.1.3. MessageCodesResolver.md deleted file mode 100644 index 221f0a96..00000000 --- a/IV. Spring Boot features/26.1.3. MessageCodesResolver.md +++ /dev/null @@ -1,3 +0,0 @@ -### 26.1.3. MessageCodesResolver - -Spring MVC有一个策略,用于从绑定的errors产生用来渲染错误信息的错误码:MessageCodesResolver。如果设置`spring.mvc.message-codes-resolver.format`属性为`PREFIX_ERROR_CODE`或`POSTFIX_ERROR_CODE`(具体查看`DefaultMessageCodesResolver.Format`枚举值),Spring Boot会为你创建一个MessageCodesResolver。 diff --git a/IV. Spring Boot features/26.1.4. Static Content.md b/IV. Spring Boot features/26.1.4. Static Content.md deleted file mode 100644 index 891748c1..00000000 --- a/IV. Spring Boot features/26.1.4. Static Content.md +++ /dev/null @@ -1,9 +0,0 @@ -### 26.1.4. 静态内容 - -默认情况下,Spring Boot从classpath下一个叫/static(/public,/resources或/META-INF/resources)的文件夹或从ServletContext根目录提供静态内容。这使用了Spring MVC的ResourceHttpRequestHandler,所以你可以通过添加自己的WebMvcConfigurerAdapter并覆写addResourceHandlers方法来改变这个行为(加载静态文件)。 - -在一个单独的web应用中,容器默认的servlet是开启的,如果Spring决定不处理某些请求,默认的servlet作为一个回退(降级)将从ServletContext根目录加载内容。大多数时候,这不会发生(除非你修改默认的MVC配置),因为Spring总能够通过DispatcherServlet处理请求。 - -此外,上述标准的静态资源位置有个例外情况是[Webjars内容](http://www.webjars.org/)。任何在/webjars/**路径下的资源都将从jar文件中提供,只要它们以Webjars的格式打包。 - -**注**:如果你的应用将被打包成jar,那就不要使用src/main/webapp文件夹。尽管该文件夹是一个共同的标准,但它仅在打包成war的情况下起作用,并且如果产生一个jar,多数构建工具都会静悄悄的忽略它。 diff --git a/IV. Spring Boot features/26.1.5. Template engines.md b/IV. Spring Boot features/26.1.5. Template engines.md deleted file mode 100644 index 29832c37..00000000 --- a/IV. Spring Boot features/26.1.5. Template engines.md +++ /dev/null @@ -1,16 +0,0 @@ -### 26.1.5. 模板引擎 - -正如REST web服务,你也可以使用Spring MVC提供动态HTML内容。Spring MVC支持各种各样的模板技术,包括Velocity, FreeMarker和JSPs。很多其他的模板引擎也提供它们自己的Spring MVC集成。 - -Spring Boot为以下的模板引擎提供自动配置支持: - -1. [FreeMarker](http://freemarker.org/docs/) -2. [Groovy](http://beta.groovy-lang.org/docs/groovy-2.3.0/html/documentation/markup-template-engine.html) -3. [Thymeleaf](http://www.thymeleaf.org/) -4. [Velocity](http://velocity.apache.org/) - -**注**:如果可能的话,应该忽略JSPs,因为在内嵌的servlet容器使用它们时存在一些[已知的限制](26.3.4. 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/26.1.6. Error Handling.md b/IV. Spring Boot features/26.1.6. Error Handling.md deleted file mode 100644 index d32b8057..00000000 --- a/IV. Spring Boot features/26.1.6. Error Handling.md +++ /dev/null @@ -1,35 +0,0 @@ -### 26.1.6. 错误处理 - -Spring Boot默认提供一个/error映射用来以合适的方式处理所有的错误,并且它在servlet容器中注册了一个全局的 -错误页面。对于机器客户端(相对于浏览器而言,浏览器偏重于人的行为),它会产生一个具有详细错误,HTTP状态,异常信息的JSON响应。对于浏览器客户端,它会产生一个白色标签样式(whitelabel)的错误视图,该视图将以HTML格式显示同样的数据(可以添加一个解析为erro的View来自定义它)。为了完全替换默认的行为,你可以实现ErrorController,并注册一个该类型的bean定义,或简单地添加一个ErrorAttributes类型的bean以使用现存的机制,只是替换显示的内容。 - -如果在某些条件下需要比较多的错误页面,内嵌的servlet容器提供了一个统一的Java DSL(领域特定语言)来自定义错误处理。 -示例: -```java -@Bean -public EmbeddedServletContainerCustomizer containerCustomizer(){ - return new MyCustomizer(); -} - -// ... -private static class MyCustomizer implements EmbeddedServletContainerCustomizer { - @Override - public void customize(ConfigurableEmbeddedServletContainer container) { - container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - } -} -``` -你也可以使用常规的Spring MVC特性来处理错误,比如[@ExceptionHandler方法](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers)和[@ControllerAdvice](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-controller-advice)。ErrorController将会捡起任何没有处理的异常。 - -N.B. 如果你为一个路径注册一个ErrorPage,最终被一个过滤器(Filter)处理(对于一些非Spring web框架,像Jersey和Wicket这很常见),然后过滤器需要显式注册为一个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分发器类型。 diff --git a/IV. Spring Boot features/26.1.7. Spring HATEOAS.md b/IV. Spring Boot features/26.1.7. Spring HATEOAS.md deleted file mode 100644 index ed3e348b..00000000 --- a/IV. Spring Boot features/26.1.7. Spring HATEOAS.md +++ /dev/null @@ -1,5 +0,0 @@ -### 26.1.7. Spring HATEOAS - -如果你正在开发一个使用超媒体的RESTful API,Spring Boot将为Spring HATEOAS提供自动配置,这在多数应用中都工作良好。自动配置替换了对使用@EnableHypermediaSupport的需求,并注册一定数量的beans来简化构建基于超媒体的应用,这些beans包括一个LinkDiscoverer和配置好的用于将响应正确编排为想要的表示的ObjectMapper。ObjectMapper可以根据spring.jackson.*属性或一个存在的Jackson2ObjectMapperBuilder bean进行自定义。 - -通过使用@EnableHypermediaSupport,你可以控制Spring HATEOAS的配置。注意这会禁用上述的对ObjectMapper的自定义。 diff --git a/IV. Spring Boot features/26.2. Console output.md b/IV. Spring Boot features/26.2. Console output.md new file mode 100644 index 00000000..63dd04fe --- /dev/null +++ b/IV. Spring Boot features/26.2. Console output.md @@ -0,0 +1,9 @@ +### 26.2. 控制台输出 + +默认的日志配置会在写日志消息时将它们回显到控制台,级别为`ERROR`, `WARN`和`INFO`的消息会被记录。你可以在启动应用时,通过`--debug`标识开启控制台的`DEBUG`级别日志记录,也可以在`application.properties`中指定`debug=true`。 +```shell +$ java -jar myapp.jar --debug +``` +当debug模式启用时,一系列核心loggers(内嵌容器,Hibernate,Spring Boot等)记录的日志会变多,但不会输出所有的信息。 + +相应地,你可以在启动应用时,通过`--trace`(或在`application.properties`设置`trace=true`)启用"trace"模式,该模式能够追踪核心loggers(内嵌容器,Hibernate生成的schema,Spring全部的portfolio)的所有日志信息。 diff --git a/IV. Spring Boot features/26.2. JAX-RS and Jersey.md b/IV. Spring Boot features/26.2. JAX-RS and Jersey.md deleted file mode 100644 index 5fad0af1..00000000 --- a/IV. Spring Boot features/26.2. JAX-RS and Jersey.md +++ /dev/null @@ -1,29 +0,0 @@ -### 26.2. JAX-RS和Jersey - -如果喜欢JAX-RS为REST端点提供的编程模型,你可以使用可用的实现替代Spring MVC。如果在你的应用上下文中将Jersey 1.x和Apache Celtix的Servlet或Filter注册为一个@Bean,那它们工作的相当好。Jersey 2.x有一些原生的Spring支持,所以我们会在Spring Boot为它提供自动配置支持,连同一个启动器(starter)。 - -想要开始使用Jersey 2.x只需要加入spring-boot-starter-jersey依赖,然后你需要一个ResourceConfig类型的@Bean,用于注册所有的端点(endpoints)。 -```java -@Component -public class JerseyConfig extends ResourceConfig { - public JerseyConfig() { - register(Endpoint.class); - } -} -``` -所有注册的端点都应该被@Components和HTTP资源annotations(比如@GET)注解。 -```java -@Component -@Path("/hello") -public class Endpoint { - @GET - public String message() { - return "Hello"; - } -} -``` -由于Endpoint是一个Spring组件(@Component),所以它的生命周期受Spring管理,并且你可以使用@Autowired添加依赖及使用@Value注入外部配置。Jersey servlet将被注册,并默认映射到/*。你可以将@ApplicationPath添加到ResourceConfig来改变该映射。 - -默认情况下,Jersey将在一个ServletRegistrationBean类型的@Bean中被设置成名称为jerseyServletRegistration的Servlet。通过创建自己的相同名称的bean,你可以禁止或覆盖这个bean。你也可以通过设置`spring.jersey.type=filter`来使用一个Filter代替Servlet(在这种情况下,被覆盖或替换的@Bean是jerseyFilterRegistration)。该servlet有@Order属性,你可以通过`spring.jersey.filter.order`进行设置。不管是Servlet还是Filter注册都可以使用spring.jersey.init.*定义一个属性集合作为初始化参数传递过去。 - -这里有一个[Jersey示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jersey),你可以查看如何设置相关事项。 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..983feb12 --- /dev/null +++ b/IV. Spring Boot features/26.2.1 Color-coded output.md @@ -0,0 +1,33 @@ +### 26.2.1 Color-coded输出 +如果你的终端支持ANSI,Spring Boot将使用彩色编码(color output)输出日志以增强可读性,你可以将`spring.output.ansi.enabled`设置为一个[支持的值](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/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. Embedded servlet container support.md b/IV. Spring Boot features/26.3. Embedded servlet container support.md deleted file mode 100644 index f4cd9f5c..00000000 --- a/IV. Spring Boot features/26.3. Embedded servlet container support.md +++ /dev/null @@ -1,3 +0,0 @@ -### 26.3. 内嵌servlet容器支持 - -Spring Boot支持内嵌的Tomcat, Jetty和Undertow服务器。多数开发者只需要使用合适的'Starter POM'来获取一个完全配置好的实例即可。默认情况下,内嵌的服务器会在8080端口监听HTTP请求。 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..800b1004 --- /dev/null +++ b/IV. Spring Boot features/26.3. File output.md @@ -0,0 +1,13 @@ +### 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`里,名称可以是精确的位置或相对于当前目录| + +日志文件每达到10M就会被分割,跟控制台一样,默认记录`ERROR`, `WARN`和`INFO`级别的信息。 diff --git a/IV. Spring Boot features/26.3.1. Servlets and Filters.md b/IV. Spring Boot features/26.3.1. Servlets and Filters.md deleted file mode 100644 index 70056447..00000000 --- a/IV. Spring Boot features/26.3.1. Servlets and Filters.md +++ /dev/null @@ -1,5 +0,0 @@ -### 26.3.1. Servlets和Filters - -当使用内嵌的servlet容器时,你可以直接将servlet和filter注册为Spring的beans。在配置期间,如果你想引用来自application.properties的值,这是非常方便的。默认情况下,如果上下文只包含单一的Servlet,那它将被映射到根路径(/)。在多Servlet beans的情况下,bean的名称将被用作路径的前缀。过滤器会被映射到/*。 - -如果基于约定(convention-based)的映射不够灵活,你可以使用ServletRegistrationBean和FilterRegistrationBean类实现完全的控制。如果你的bean实现了ServletContextInitializer接口,也可以直接注册它们。 diff --git a/IV. Spring Boot features/26.3.2. The EmbeddedWebApplicationContext.md b/IV. Spring Boot features/26.3.2. The EmbeddedWebApplicationContext.md deleted file mode 100644 index e587d7bb..00000000 --- a/IV. Spring Boot features/26.3.2. The EmbeddedWebApplicationContext.md +++ /dev/null @@ -1,5 +0,0 @@ -### 26.3.2. EmbeddedWebApplicationContext - -Spring Boot底层使用了一个新的ApplicationContext类型,用于对内嵌servlet容器的支持。EmbeddedWebApplicationContext是一个特殊类型的WebApplicationContext,它通过搜索一个单一的EmbeddedServletContainerFactory bean来启动自己。通常,TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory将被自动配置。 - -**注**:你通常不需要知道这些实现类。大多数应用将被自动配置,并根据你的行为创建合适的ApplicationContext和EmbeddedServletContainerFactory。 diff --git a/IV. Spring Boot features/26.3.3. Customizing embedded servlet containers.md b/IV. Spring Boot features/26.3.3. Customizing embedded servlet containers.md deleted file mode 100644 index 3d1bb227..00000000 --- a/IV. Spring Boot features/26.3.3. Customizing embedded servlet containers.md +++ /dev/null @@ -1,40 +0,0 @@ -### 26.3.3. 自定义内嵌servlet容器 - -常见的Servlet容器设置可以通过Spring Environment属性进行配置。通常,你会把这些属性定义到application.properties文件中。 -常见的服务器设置包括: - -1. server.port - 进来的HTTP请求的监听端口号 -2. server.address - 绑定的接口地址 -3. server.sessionTimeout - session超时时间 - -具体参考[ServerProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)。 - -* 编程方式的自定义 - -如果需要以编程的方式配置内嵌的servlet容器,你可以注册一个实现EmbeddedServletContainerCustomizer接口的Spring bean。EmbeddedServletContainerCustomizer提供对ConfigurableEmbeddedServletContainer的访问,ConfigurableEmbeddedServletContainer包含很多自定义的setter方法。 -```java -import org.springframework.boot.context.embedded.*; -import org.springframework.stereotype.Component; - -@Component -public class CustomizationBean implements EmbeddedServletContainerCustomizer { - @Override - public void customize(ConfigurableEmbeddedServletContainer container) { - container.setPort(9000); - } -} -``` -* 直接自定义ConfigurableEmbeddedServletContainer - -如果上面的自定义手法过于受限,你可以自己注册TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory。 -```java -@Bean -public EmbeddedServletContainerFactory servletContainer() { - TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); - 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/26.3.4. JSP limitations.md b/IV. Spring Boot features/26.3.4. JSP limitations.md deleted file mode 100644 index 8509279d..00000000 --- a/IV. Spring Boot features/26.3.4. JSP limitations.md +++ /dev/null @@ -1,9 +0,0 @@ -### 26.3.4. JSP的限制 - -在内嵌的servlet容器中运行一个Spring Boot应用时(并打包成一个可执行的存档archive),容器对JSP的支持有一些限制。 - -1. tomcat只支持war的打包方式,不支持可执行的jar。 -2. 内嵌的Jetty目前不支持JSPs。 -3. Undertow不支持JSPs。 - -这里有个[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/26.4. Log Levels.md b/IV. Spring Boot features/26.4. Log Levels.md new file mode 100644 index 00000000..f3434d6b --- /dev/null +++ b/IV. Spring Boot features/26.4. Log Levels.md @@ -0,0 +1,11 @@ +### 26.4. 日志级别 + +所有Spring Boot支持的日志系统都可以在Spring `Environment`中设置级别(`application.properties`里也一样),设置格式为'logging.level.*=LEVEL',其中`LEVEL`是`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`, `OFF`之一: + +以下是`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/v1.4.1.RELEASE/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..19222f3e --- /dev/null +++ b/IV. Spring Boot features/26.5. Custom log configuration.md @@ -0,0 +1,41 @@ +### 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/1.4.1.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.6 Logback extensions.md b/IV. Spring Boot features/26.6 Logback extensions.md new file mode 100644 index 00000000..5e054249 --- /dev/null +++ b/IV. Spring Boot features/26.6 Logback extensions.md @@ -0,0 +1,4 @@ +### 26.6 Logback扩展 +Spring Boot包含很多有用的Logback扩展,你可以在`logback-spring.xml`配置文件中使用它们。 + +**注** 你不能在标准的`logback.xml`配置文件中使用扩展,因为它加载的太早了,不过可以使用`logback-spring.xml`,或指定`logging.config`属性。 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..1476f9d0 --- /dev/null +++ b/IV. Spring Boot features/26.6.1 Profile-specific configuration.md @@ -0,0 +1,15 @@ +### 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..f17f7fc4 --- /dev/null +++ b/IV. Spring Boot features/26.6.2 Environment properties.md @@ -0,0 +1,11 @@ +### 26.6.2 Environment属性 +``标签允许你从Spring `Environment`读取属性,以便在Logback中使用。如果你想在logback配置获取`application.properties`中的属性值,该功能就很有用。该标签工作方式跟Logback标准``标签类似,但不是直接指定`value`值,你需要定义属性的`source`(来自`Environment`),也可以指定存储属性作用域的`scope`。如果`Environment`没有相应属性,你可以通过`defaultValue`设置默认值。 +```xml + + + ${fluentHost} + ... + +``` +**注** `RelaxedPropertyResolver`用于获取`Environment`属性,如果以中划线的方式指定`source`(`my-property-name`),则所有relaxed变体都会进行尝试(`myPropertyName`,`MY_PROPERTY_NAME `等)。 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..000be5d5 --- /dev/null +++ b/IV. Spring Boot features/27. Developing web applications.md @@ -0,0 +1,4 @@ +### 27. 开发Web应用 +Spring Boot非常适合开发web应用程序。你可以使用内嵌的Tomcat,Jetty或Undertow轻轻松松地创建一个HTTP服务器。大多数的web应用都可以使用`spring-boot-starter-web`模块进行快速搭建和运行。 + +如果没有开发过Spring Boot web应用,可以参考[Getting started章节](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#getting-started-first-application)的"Hello World!"示例。 diff --git a/IV. Spring Boot features/27. Security.md b/IV. Spring Boot features/27. Security.md deleted file mode 100644 index 6e783a6a..00000000 --- a/IV. Spring Boot features/27. Security.md +++ /dev/null @@ -1,30 +0,0 @@ -### 27. 安全 -如果Spring Security在classpath下,那么web应用默认对所有的HTTP路径(也称为终点,端点,表示API的具体网址)使用'basic'认证。为了给web应用添加方法级别的保护,你可以添加@EnableGlobalMethodSecurity并使用想要的设置。其他信息参考[Spring Security Reference](http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle#jc-method)。 - -默认的AuthenticationManager有一个单一的user('user'的用户名和随机密码会在应用启动时以INFO日志级别打印出来)。如下: -```java -Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 -``` -**注**:如果你对日志配置进行微调,确保`org.springframework.boot.autoconfigure.security`类别能记录INFO信息,否则默认的密码不会被打印。 - -你可以通过提供`security.user.password`改变默认的密码。这些和其他有用的属性通过[SecurityProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java)(以security为前缀的属性)被外部化了。 - -默认的安全配置(security configuration)是在SecurityAutoConfiguration和导入的类中实现的(SpringBootWebSecurityConfiguration用于web安全,AuthenticationManagerConfiguration用于与非web应用也相关的认证配置)。你可以添加一个@EnableWebSecurity bean来彻底关掉Spring Boot的默认配置。为了对它进行自定义,你需要使用外部的属性配置和WebSecurityConfigurerAdapter类型的beans(比如,添加基于表单的登陆)。在[Spring Boot示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/)里有一些安全相关的应用可以带你体验常见的用例。 - -在一个web应用中你能得到的基本特性如下: - -1. 一个使用内存存储的AuthenticationManager bean和唯一的user(查看SecurityProperties.User获取user的属性)。 -2. 忽略(不保护)常见的静态资源路径(`/css/**, /js/**, /images/**`和 `**/favicon.ico`)。 -3. 对其他的路径实施HTTP Basic安全保护。 -4. 安全相关的事件会发布到Spring的ApplicationEventPublisher(成功和失败的认证,拒绝访问)。 -5. Spring Security提供的常见底层特性(HSTS, XSS, CSRF, 缓存)默认都被开启。 - -上述所有特性都能打开和关闭,或使用外部的配置进行修改(security.*)。为了覆盖访问规则(access rules)而不改变其他自动配置的特性,你可以添加一个使用@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)注解的WebSecurityConfigurerAdapter类型的@Bean。 - -如果Actuator也在使用,你会发现: - -1. 即使应用路径不受保护,被管理的路径也会受到保护。 -2. 安全相关的事件被转换为AuditEvents(审计事件),并发布给AuditService。 -3. 默认的用户有ADMIN和USER的角色。 - -使用外部属性能够修改Actuator(执行器)的安全特性(management.security.*)。为了覆盖应用程序的访问规则,你可以添加一个WebSecurityConfigurerAdapter类型的@Bean。同时,如果不想覆盖执行器的访问规则,你可以使用@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)注解该bean,否则使用@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)注解该bean。 diff --git "a/IV. Spring Boot features/26.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" similarity index 51% rename from "IV. Spring Boot features/26.1. The \342\200\230Spring Web MVC framework\342\200\231.md" rename to "IV. Spring Boot features/27.1. The \342\200\230Spring Web MVC framework\342\200\231.md" index a3eb9764..190d17f0 100644 --- "a/IV. Spring Boot features/26.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" @@ -1,8 +1,7 @@ -### 26.1. Spring Web MVC框架 +### 27.1. Spring Web MVC框架 -Spring Web MVC框架(通常简称为"Spring MVC")是一个富"模型,视图,控制器"的web框架。 -Spring MVC允许你创建特定的@Controller或@RestController beans来处理传入的HTTP请求。 -使用@RequestMapping注解可以将控制器中的方法映射到相应的HTTP请求。 +Spring Web MVC框架(通常简称为"Spring MVC")是一个富“模型,视图,控制器”web框架, +允许用户创建特定的`@Controller`或`@RestController` beans来处理传入的HTTP请求,通过`@RequestMapping`注解可以将控制器中的方法映射到相应的HTTP请求。 示例: ```java @@ -26,3 +25,4 @@ public class MyRestController { } } ``` +Spring MVC是Spring框架的核心部分,详细信息可以参考[reference documentation](http://docs.spring.io/spring/docs/4.3.3.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..e2fa82e4 --- /dev/null +++ b/IV. Spring Boot features/27.1.1. Spring MVC auto-configuration.md @@ -0,0 +1,17 @@ +### 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配置](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle#mvc)(拦截器,格式化处理器,视图控制器等)。你可以添加自己的`WebMvcConfigurerAdapter`类型的`@Configuration`类,而不需要注解`@EnableWebMvc`。如果希望使用自定义的`RequestMappingHandlerMapping`,`RequestMappingHandlerAdapter`,或`ExceptionHandlerExceptionResolver`,你可以声明一个`WebMvcRegistrationsAdapter`实例提供这些组件。 + + +如果想全面控制Spring MVC,你可以添加自己的`@Configuration`,并使用`@EnableWebMvc`注解。 diff --git a/IV. Spring Boot features/27.1.10 CORS support.md b/IV. Spring Boot features/27.1.10 CORS support.md new file mode 100644 index 00000000..2d348444 --- /dev/null +++ b/IV. Spring Boot features/27.1.10 CORS support.md @@ -0,0 +1,19 @@ +### 27.1.10 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](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#cors)提供开箱即用的支持。不用添加任何特殊配置,只需要在Spring Boot应用的controller方法上注解[`@CrossOrigin`](http://docs.spring.io/spring/docs/4.3.3.RELEASE/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html),并添加[CORS配置](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#_controller_method_cors_configuration)。通过注册一个自定义`addCorsMappings(CorsRegistry)`方法的`WebMvcConfigurer` bean可以指定[全局CORS配置](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#_global_cors_configuration): +```java +@Configuration +public class MyConfiguration { + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurerAdapter() { + @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 new file mode 100644 index 00000000..478ab543 --- /dev/null +++ b/IV. Spring Boot features/27.1.2. HttpMessageConverters.md @@ -0,0 +1,22 @@ +### 27.1.2. HttpMessageConverters + +Spring MVC使用`HttpMessageConverter`接口转换HTTP请求和响应,合适的默认配置可以开箱即用,例如对象自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用,否则使用JAXB),字符串默认使用`UTF-8`编码。 + +可以使用Spring Boot的`HttpMessageConverters`类添加或自定义转换类: +```java +import org.springframework.boot.autoconfigure.web.HttpMessageConverters; +import org.springframework.context.annotation.*; +import org.springframework.http.converter.*; + +@Configuration +public class MyConfiguration { + + @Bean + public HttpMessageConverters customConverters() { + HttpMessageConverter additional = ... + HttpMessageConverter another = ... + return new HttpMessageConverters(additional, another); + } +} +``` +上下文中出现的所有`HttpMessageConverter` bean都将添加到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 new file mode 100644 index 00000000..3f2bab43 --- /dev/null +++ b/IV. Spring Boot features/27.1.3 Custom JSON Serializers and Deserializers.md @@ -0,0 +1,3 @@ +###27.1.3 自定义JSON序列化器和反序列化器 + +如果使用Jackson序列化,反序列化JSON数据,你可能想编写自己的`JsonSerializer`和`JsonDeserializer`类。自定义序列化器(serializers)通常[通过Module注册到Jackson](http://wiki.fasterxml.com/JacksonHowToCustomDeserializers),但Spring Boot提供了`@JsonComponent`注解这一替代方式,它能轻松的将序列化器注册为Spring Beans。 diff --git a/IV. Spring Boot features/27.1.4 MessageCodesResolver.md b/IV. Spring Boot features/27.1.4 MessageCodesResolver.md new file mode 100644 index 00000000..c657cd2d --- /dev/null +++ b/IV. Spring Boot features/27.1.4 MessageCodesResolver.md @@ -0,0 +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`枚举值)。 diff --git a/IV. Spring Boot features/27.1.5 Static Content.md b/IV. Spring Boot features/27.1.5 Static Content.md new file mode 100644 index 00000000..b080cbb5 --- /dev/null +++ b/IV. Spring Boot features/27.1.5 Static Content.md @@ -0,0 +1,36 @@ +### 27.1.5 静态内容 + +默认情况下,Spring Boot从classpath下的`/static`(`/public`,`/resources`或`/META-INF/resources`)文件夹,或从`ServletContext`根目录提供静态内容。这是通过Spring MVC的`ResourceHttpRequestHandler`实现的,你可以自定义`WebMvcConfigurerAdapter`并覆写`addResourceHandlers`方法来改变该行为(加载静态文件)。 + +在单机web应用中,容器会启动默认的servlet,并用它加载`ServletContext`根目录下的内容以响应那些Spring不处理的请求。大多数情况下这都不会发生(除非你修改默认的MVC配置),因为Spring总能够通过`DispatcherServlet`处理这些请求。 + +你可以设置`spring.resources.staticLocations`属性自定义静态资源的位置(配置一系列目录位置代替默认的值),如果你这样做,默认的欢迎页面将从自定义位置加载,所以只要这些路径中的任何地方有一个`index.html`,它都会成为应用的主页。 + +此外,除了上述标准的静态资源位置,有个例外情况是[Webjars内容](http://www.webjars.org/)。任何在`/webjars/**`路径下的资源都将从jar文件中提供,只要它们以Webjars的格式打包。 + +**注** 如果你的应用将被打包成jar,那就不要使用`src/main/webapp`文件夹。尽管该文件夹是通常的标准格式,但它仅在打包成war的情况下起作用,在打包成jar时,多数构建工具都会默认忽略它。 + +Spring Boot也支持Spring MVC提供的高级资源处理特性,可用于清除缓存的静态资源或对WebJar使用版本无感知的URLs。 + +如果想使用针对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`。 + +以下的配置为所有的静态资源提供一种缓存清除(cache busting)方案,实际上是将内容hash添加到URLs中,比如``: +```properties +spring.resources.chain.strategy.content.enabled=true +spring.resources.chain.strategy.content.paths=/** +``` +**注** 实现该功能的是`ResourceUrlEncodingFilter`,它在模板运行期会重写资源链接,Thymeleaf,Velocity和FreeMarker会自动配置该filter,JSP需要手动配置。其他模板引擎还没自动支持,不过你可以使用[ResourceUrlProvider](http://docs.spring.io/spring/docs/4.3.3.RELEASE/javadoc-api/org/springframework/web/servlet/resource/ResourceUrlProvider.html)自定义模块宏或帮助类。 + +当使用比如JavaScript模块加载器动态加载资源时,重命名文件是不行的,这也是提供其他策略并能结合使用的原因。下面是一个"fixed"策略,在URL中添加一个静态version字符串而不需要改变文件名: +```properties +spring.resources.chain.strategy.content.enabled=true +spring.resources.chain.strategy.content.paths=/** +spring.resources.chain.strategy.fixed.enabled=true +spring.resources.chain.strategy.fixed.paths=/js/lib/ +spring.resources.chain.strategy.fixed.version=v12 +``` +使用以上策略,JavaScript模块加载器加载`"/js/lib/"`下的文件时会使用一个固定的版本策略`"/v12/js/lib/mymodule.js"`,其他资源仍旧使用内容hash的方式``。查看[ResourceProperties](https://github.com/spring-projects/spring-boot/tree/v1.4.1.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://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources)中有透彻描述。 diff --git a/IV. Spring Boot features/27.1.6 ConfigurableWebBindingInitializer.md b/IV. Spring Boot features/27.1.6 ConfigurableWebBindingInitializer.md new file mode 100644 index 00000000..243c4c55 --- /dev/null +++ b/IV. Spring Boot features/27.1.6 ConfigurableWebBindingInitializer.md @@ -0,0 +1,3 @@ +### 27.1.6 ConfigurableWebBindingInitializer +Spring MVC使用`WebBindingInitializer`为每个特殊的请求初始化相应的`WebDataBinder`,如果你创建自己的`ConfigurableWebBindingInitializer @Bean`,Spring Boot会自动配置Spring MVC使用它。 + diff --git a/IV. Spring Boot features/27.1.7 Template engines.md b/IV. Spring Boot features/27.1.7 Template engines.md new file mode 100644 index 00000000..0a1cfbae --- /dev/null +++ b/IV. Spring Boot features/27.1.7 Template engines.md @@ -0,0 +1,17 @@ +### 27.1.7 模板引擎 + +正如REST web服务,你也可以使用Spring MVC提供动态HTML内容。Spring MVC支持各种各样的模板技术,包括Velocity, FreeMarker和JSPs,很多其他的模板引擎也提供它们自己的Spring MVC集成。 + +Spring Boot为以下的模板引擎提供自动配置支持: + +1. [FreeMarker](http://freemarker.org/docs/) +2. [Groovy](http://beta.groovy-lang.org/docs/groovy-2.3.0/html/documentation/markup-template-engine.html) +3. [Thymeleaf](http://www.thymeleaf.org/) +4. [Velocity](http://velocity.apache.org/)(1.4已不再支持) +5. [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.8 Error Handling.md b/IV. Spring Boot features/27.1.8 Error Handling.md new file mode 100644 index 00000000..a3c55503 --- /dev/null +++ b/IV. Spring Boot features/27.1.8 Error Handling.md @@ -0,0 +1,110 @@ +### 27.1.8 错误处理 + +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方法](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers)和[@ControllerAdvice](http://docs.spring.io/spring/docs/4.3.3.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.1.9 Spring HATEOAS.md b/IV. Spring Boot features/27.1.9 Spring HATEOAS.md new file mode 100644 index 00000000..994b1a4f --- /dev/null +++ b/IV. Spring Boot features/27.1.9 Spring HATEOAS.md @@ -0,0 +1,6 @@ +### 27.1.9 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.2 JAX-RS and Jersey.md b/IV. Spring Boot features/27.2 JAX-RS and Jersey.md new file mode 100644 index 00000000..ce5c439c --- /dev/null +++ b/IV. Spring Boot features/27.2 JAX-RS and Jersey.md @@ -0,0 +1,31 @@ +### 27.2 JAX-RS和Jersey + +如果你更喜欢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): +```java +@Component +public class JerseyConfig extends ResourceConfig { + public JerseyConfig() { + register(Endpoint.class); + } +} +``` +你也可以注册任意数量的,实现`ResourceConfigCustomizer`的beans来进一步自定义。 + +所有注册的端点都需注解`@Components`和HTTP资源annotations(比如`@GET`): +```java +@Component +@Path("/hello") +public class Endpoint { + @GET + public String message() { + return "Hello"; + } +} +``` +由于`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示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jersey),你可以查看如何设置相关事项。 diff --git a/IV. Spring Boot features/27.3 Embedded servlet container support.md b/IV. Spring Boot features/27.3 Embedded servlet container support.md new file mode 100644 index 00000000..8295dbcf --- /dev/null +++ b/IV. Spring Boot features/27.3 Embedded servlet container support.md @@ -0,0 +1,3 @@ +### 27.3 内嵌servlet容器支持 + +Spring Boot支持内嵌的Tomcat, Jetty和Undertow服务器,多数开发者只需要使用合适的'Starter'来获取一个完全配置好的实例即可,内嵌服务器默认监听8080端口的HTTP请求。 diff --git a/IV. Spring Boot features/27.3.1 Servlets, Filters, and listeners.md b/IV. Spring Boot features/27.3.1 Servlets, Filters, and listeners.md new file mode 100644 index 00000000..a3f353dd --- /dev/null +++ b/IV. Spring Boot features/27.3.1 Servlets, Filters, and listeners.md @@ -0,0 +1,9 @@ +### 27.3.1 Servlets, Filters和listeners + +使用内嵌servlet容器时,你可以通过使用Spring beans或扫描Servlet组件的方式注册Servlets,Filters及特定Servlet相关的所有listeners(比如`HttpSessionListener`)。 + +**将Servlets,Filters和listeners注册为Spring beans** + +所有`Servlet`,`Filter`或Servlet `*Listener`实例,只要是Spring bean,都会注册到内嵌容器中。如果想在配置期间引用`application.properties`的属性,这是非常方便的。默认情况下,如果上下文只包含单个Servlet,那它将被映射到`/`。如果存在多个Servlet beans,那么bean的名称将被用作路径的前缀,过滤器将映射到`/*`。 + +如果基于约定(convention-based)的映射不够灵活,你可以使用`ServletRegistrationBean`,`FilterRegistrationBean`,`ServletListenerRegistrationBean`实现完全的控制。 diff --git a/IV. Spring Boot features/27.3.2 Servlet Context Initialization.md b/IV. Spring Boot features/27.3.2 Servlet Context Initialization.md new file mode 100644 index 00000000..24cf2aed --- /dev/null +++ b/IV. Spring Boot features/27.3.2 Servlet Context Initialization.md @@ -0,0 +1,10 @@ +### 27.3.2 Servlet上下文初始化 +内嵌servlet容器不会直接执行Servlet 3.0+的`javax.servlet.ServletContainerInitializer`接口,或Spring的`org.springframework.web.WebApplicationInitializer`接口,这样设计的目的是降低war包内运行的第三方库破坏Spring Boot应用的风险。 + +如果需要在Spring Boot应用中执行servlet上下文初始化,你需要注册一个实现`org.springframework.boot.context.embedded.ServletContextInitializer`接口的bean。`onStartup`方法可以获取`ServletContext`,如果需要的话可以轻松用来适配一个已存在的`WebApplicationInitializer`。 + +**扫描Servlets, Filters和listeners** + +当使用一个内嵌容器时,通过`@ServletComponentScan`可以启用对注解`@WebServlet`,`@WebFilter`和`@WebListener`类的自动注册。 + +**注** 在独立的容器(非内嵌)中`@ServletComponentScan`不起作用,取为代之的是容器内建的discovery机制。 diff --git a/IV. Spring Boot features/27.3.3 The EmbeddedWebApplicationContext.md b/IV. Spring Boot features/27.3.3 The EmbeddedWebApplicationContext.md new file mode 100644 index 00000000..a74efcc8 --- /dev/null +++ b/IV. Spring Boot features/27.3.3 The EmbeddedWebApplicationContext.md @@ -0,0 +1,5 @@ +### 27.3.3 EmbeddedWebApplicationContext + +Spring Boot底层使用一种新的`ApplicationContext`类型,用于对内嵌servlet容器的支持。`EmbeddedWebApplicationContext`是一种特殊类型的`WebApplicationContext`,它通过搜索到的单个`EmbeddedServletContainerFactory` bean来启动自己,通常`TomcatEmbeddedServletContainerFactory`,`JettyEmbeddedServletContainerFactory`或`UndertowEmbeddedServletContainerFactory`将被自动配置。 + +**注** 你不需要关心这些实现类,大部分应用都能被自动配置,并根据你的行为创建合适的`ApplicationContext`和`EmbeddedServletContainerFactory`。 diff --git a/IV. Spring Boot features/27.3.4 Customizing embedded servlet containers.md b/IV. Spring Boot features/27.3.4 Customizing embedded servlet containers.md new file mode 100644 index 00000000..39589c46 --- /dev/null +++ b/IV. Spring Boot features/27.3.4 Customizing embedded servlet containers.md @@ -0,0 +1,46 @@ +### 27.3.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](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto-configure-ssl)。 +5. [HTTP压缩](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#how-to-enable-http-response-compression) + +Spring Boot会尽量暴露常用设置,但这并不总是可能的。对于不可能的情况,可以使用专用的命名空间提供server-specific配置(查看`server.tomcat`,`server.undertow`)。例如,可以根据内嵌servlet容器的特性对[access logs](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto-configure-accesslogs)进行不同的设置。 + +**注** 具体参考[ServerProperties](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)。 + +**编程方式的自定义** + +如果需要以编程方式配置内嵌servlet容器,你可以注册一个实现`EmbeddedServletContainerCustomizer`接口的Spring bean。`EmbeddedServletContainerCustomizer`能够获取到包含很多自定义setter方法的`ConfigurableEmbeddedServletContainer`,你可以通过这些setter方法对内嵌容器自定义。 +```java +import org.springframework.boot.context.embedded.*; +import org.springframework.stereotype.Component; + +@Component +public class CustomizationBean implements EmbeddedServletContainerCustomizer { + @Override + public void customize(ConfigurableEmbeddedServletContainer container) { + container.setPort(9000); + } +} +``` + +**直接自定义ConfigurableEmbeddedServletContainer** + +如果以上自定义手法过于受限,你可以自己注册`TomcatEmbeddedServletContainerFactory`,`JettyEmbeddedServletContainerFactory`或`UndertowEmbeddedServletContainerFactory`。 +```java +@Bean +public EmbeddedServletContainerFactory servletContainer() { + TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); + 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.3.5 JSP limitations.md b/IV. Spring Boot features/27.3.5 JSP limitations.md new file mode 100644 index 00000000..145104ba --- /dev/null +++ b/IV. Spring Boot features/27.3.5 JSP limitations.md @@ -0,0 +1,10 @@ +### 27.3.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/1.4.1.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/28. Security.md b/IV. Spring Boot features/28. Security.md new file mode 100644 index 00000000..d9b74f94 --- /dev/null +++ b/IV. Spring Boot features/28. Security.md @@ -0,0 +1,25 @@ +### 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)。 + +默认的`AuthenticationManager`只有一个用户('user'的用户名和随机密码会在应用启动时以INFO日志级别打印出来),如下: +```java +Using default 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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java)(以"security"为前缀的属性)被外部化了。 + +默认的安全配置是通过`SecurityAutoConfiguration`,`SpringBootWebSecurityConfiguration`(用于web安全),`AuthenticationManagerConfiguration`(可用于非web应用的认证配置)进行管理的。你可以添加一个`@EnableWebSecurity` bean来彻底关掉Spring Boot的默认配置。为了对它进行自定义,你需要使用外部的属性配置和`WebSecurityConfigurerAdapter`类型的beans(比如,添加基于表单的登陆)。 +想要关闭认证管理的配置,你可以添加一个`AuthenticationManager`类型的bean,或在`@Configuration`类的某个方法里注入`AuthenticationManagerBuilder`来配置全局的`AuthenticationManager`。这里有一些安全相关的[Spring Boot应用示例](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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自动配置的访问规则,你可以精确的配置想要覆盖的路径。 diff --git a/IV. Spring Boot features/28. Working with SQL databases.md b/IV. Spring Boot features/28. Working with SQL databases.md deleted file mode 100644 index a2bffed5..00000000 --- a/IV. Spring Boot features/28. Working with SQL databases.md +++ /dev/null @@ -1,2 +0,0 @@ -### 28. 使用SQL数据库 -Spring框架为使用SQL数据库提供了广泛的支持。从使用JdbcTemplate直接访问JDBC到完全的对象关系映射技术,比如Hibernate。Spring Data提供一个额外的功能,直接从接口创建Repository实现,并使用约定从你的方法名生成查询。 diff --git a/IV. Spring Boot features/28.1 OAuth2.md b/IV. Spring Boot features/28.1 OAuth2.md new file mode 100644 index 00000000..80792651 --- /dev/null +++ b/IV. Spring Boot features/28.1 OAuth2.md @@ -0,0 +1,3 @@ +###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. Configure a DataSource.md b/IV. Spring Boot features/28.1. Configure a DataSource.md deleted file mode 100644 index 01bb31ee..00000000 --- a/IV. Spring Boot features/28.1. Configure a DataSource.md +++ /dev/null @@ -1,3 +0,0 @@ -### 28.1. 配置DataSource - -Java的javax.sql.DataSource接口提供了一个标准的使用数据库连接的方法。传统做法是,一个DataSource使用一个URL连同相应的证书去初始化一个数据库连接。 diff --git a/IV. Spring Boot features/28.1.1 Authorization Server.md b/IV. Spring Boot features/28.1.1 Authorization Server.md new file mode 100644 index 00000000..d864b965 --- /dev/null +++ b/IV. Spring Boot features/28.1.1 Authorization Server.md @@ -0,0 +1,11 @@ +### 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.1. Embedded Database Support.md b/IV. Spring Boot features/28.1.1. Embedded Database Support.md deleted file mode 100644 index e880def4..00000000 --- a/IV. Spring Boot features/28.1.1. Embedded Database Support.md +++ /dev/null @@ -1,19 +0,0 @@ -### 28.1.1. 对内嵌数据库的支持 - -开发应用时使用内存数据库是很实用的。显而易见地,内存数据库不需要提供持久化存储。你不需要在应用启动时填充数据库,也不需要在应用结束时丢弃数据。 - -Spring Boot可以自动配置的内嵌数据库包括[H2](http://www.h2database.com/), [HSQL](http://hsqldb.org/)和[Derby](http://db.apache.org/derby/)。你不需要提供任何连接URLs,只需要简单的添加你想使用的内嵌数据库依赖。 - -示例:典型的POM依赖如下: -```xml - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - -``` -**注**:对于自动配置的内嵌数据库,你需要依赖spring-jdbc。在示例中,它通过`spring-boot-starter-data-jpa`被传递地拉过来了。 diff --git a/IV. Spring Boot features/28.1.2 Resource Server.md b/IV. Spring Boot features/28.1.2 Resource Server.md new file mode 100644 index 00000000..e72df8ea --- /dev/null +++ b/IV. Spring Boot features/28.1.2 Resource Server.md @@ -0,0 +1,14 @@ +### 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,并告诉你如何解决。 diff --git a/IV. Spring Boot features/28.1.2. Connection to a production database.md b/IV. Spring Boot features/28.1.2. Connection to a production database.md deleted file mode 100644 index faf50bfd..00000000 --- a/IV. Spring Boot features/28.1.2. Connection to a production database.md +++ /dev/null @@ -1,23 +0,0 @@ -### 28.1.2. 连接到一个生产环境数据库 - -在生产环境中,数据库连接可以使用DataSource池进行自动配置。下面是选取一个特定实现的算法: - -- 由于Tomcat数据源连接池的性能和并发,在tomcat可用时,我们总是优先使用它。 -- 如果HikariCP可用,我们将使用它。 -- 如果Commons DBCP可用,我们将使用它,但在生产环境不推荐使用它。 -- 最后,如果Commons DBCP2可用,我们将使用它。 - -如果你使用spring-boot-starter-jdbc或spring-boot-starter-data-jpa 'starter POMs',你将会自动获取对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 -``` -其他可选的配置可以查看[DataSourceProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java)。同时注意你可以通过spring.datasource.*配置任何DataSource实现相关的特定属性:具体参考你使用的连接池实现的文档。 - -**注**:既然Spring Boot能够从大多数数据库的url上推断出driver-class-name,那么你就不需要再指定它了。对于一个将要创建的DataSource连接池,我们需要能够验证Driver是否可用,所以我们会在做任何事情之前检查它。比如,如果你设置spring.datasource.driverClassName=com.mysql.jdbc.Driver,然后这个类就会被加载。 diff --git a/IV. Spring Boot features/28.1.3. Connection to a JNDI DataSource.md b/IV. Spring Boot features/28.1.3. Connection to a JNDI DataSource.md deleted file mode 100644 index 1b854663..00000000 --- a/IV. Spring Boot features/28.1.3. Connection to a JNDI DataSource.md +++ /dev/null @@ -1,8 +0,0 @@ -### 28.1.3. 连接到一个JNDI数据库 - -如果正在将Spring Boot应用部署到一个应用服务器,你可能想要用应用服务器内建的特性来配置和管理你的DataSource,并使用JNDI访问它。 - -spring.datasource.jndi-name属性可以用来替代spring.datasource.url,spring.datasource.username和spring.datasource.password去从一个特定的JNDI路径访问DataSource。比如,下面application.properties中的片段展示了如何获取JBoss定义的DataSource: -```java -spring.datasource.jndi-name=java:jboss/datasources/customers -``` 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 new file mode 100644 index 00000000..df8aded9 --- /dev/null +++ b/IV. Spring Boot features/28.2 Token Type in User Info.md @@ -0,0 +1,3 @@ +###28.2 User Info中的Token类型 + +Google和其他一些第三方身份(identity)提供商对发送给user info端点的请求头中设置的token类型名有严格要求。默认的`Bearer`满足大多数提供商要求,如果需要你可以设置`security.oauth2.resource.token-type`来改变它。 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 new file mode 100644 index 00000000..f6861d59 --- /dev/null +++ b/IV. Spring Boot features/28.3 Customizing the User Info RestTemplate.md @@ -0,0 +1,14 @@ +### 28.3 自定义User Info RestTemplate +如果设置了`user-info-uri`,资源服务器在内部将使用一个`OAuth2RestTemplate`抓取用于认证的用户信息,这是一个id为`userInfoRestTemplate`的`@Bean`提供的,但你不需要了解这些,只需要用它即可。默认适用于大多数提供商,但偶尔你可能需要添加其他interceptors,或改变request的验证器(authenticator)。想要添加自定义,只需创建一个`UserInfoRestTemplateCustomizer`类型的bean —— 它只有单个方法,在bean创建后,初始化前会调用该方法。此处自定义的rest template仅用于内部执行认证。 + +**注** 在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. JPA and \342\200\230Spring Data\342\200\231.md" "b/IV. Spring Boot features/28.3. JPA and \342\200\230Spring Data\342\200\231.md" deleted file mode 100644 index a74e3fdd..00000000 --- "a/IV. Spring Boot features/28.3. JPA and \342\200\230Spring Data\342\200\231.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 28.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/28.3.1 Client.md b/IV. Spring Boot features/28.3.1 Client.md new file mode 100644 index 00000000..2a5a6380 --- /dev/null +++ b/IV. Spring Boot features/28.3.1 Client.md @@ -0,0 +1,30 @@ +### 28.3.1 客户端 + +为了将web-app放入一个OAuth2客户端,你只需注解`@EnableOAuth2Client`,Spring Boot会创建`OAuth2ClientContext`和`OAuth2ProtectedResourceDetails`,这些是创建`OAuth2RestOperations`必需的。Spring Boot不会自动创建该bean,但你自己创建也不费力: +```java +@Bean +public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, + OAuth2ProtectedResourceDetails details) { + return new OAuth2RestTemplate(details, oauth2ClientContext); +} +``` +**注** 你可能想添加一个限定名(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)。 + +在客户端获取access token时,你可以设置`security.oauth2.client.scope`(逗号分隔或一个YAML数组)来限制它请求的作用域(scope)。作用域默认是空的,默认值取决于授权服务器,通常依赖于它拥有的客户端在注册时的设置。 + +**注** 对`security.oauth2.client.client-authentication-scheme`也有设置,默认为"header"(如果你的OAuth2提供商不喜欢header认证,例如Github,你可能需要将它设置为“form”)。实际上,`security.oauth2.client.*`属性绑定到一个`AuthorizationCodeResourceDetails`实例,所以它的所有属性都可以指定。 + +**注** 在一个非web应用中,你仍旧可以创建一个`OAuth2RestOperations`,并且跟`security.oauth2.client.*`配置关联。在这种情况下,它是一个“client credentials token grant”,如果你使用它的话就需要获取(此处不需要注解`@EnableOAuth2Client`或`@EnableOAuth2Sso`)。为了防止基础设施定义,只需要将`security.oauth2.client.client-id`从配置中移除(或将它设为空字符串)。 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 new file mode 100644 index 00000000..438869b7 --- /dev/null +++ b/IV. Spring Boot features/28.3.2 Single Sign On.md @@ -0,0 +1,29 @@ +### 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 +public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + public void init(WebSecurity web) { + web.ignore("/"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**").authorizeRequests().anyRequest().authenticated(); + } + +} +``` diff --git a/IV. Spring Boot features/28.3.2. Spring Data JPA Repositories.md b/IV. Spring Boot features/28.3.2. Spring Data JPA Repositories.md deleted file mode 100644 index 75f6554c..00000000 --- a/IV. Spring Boot features/28.3.2. Spring Data JPA Repositories.md +++ /dev/null @@ -1,23 +0,0 @@ -### 28.3.2. Spring Data JPA仓库 - -Spring Data JPA仓库(repositories)是用来定义访问数据的接口。根据你的方法名,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仓库通常继承自[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)接口。如果你使用自动配置,包括在你的主配置类(被@EnableAutoConfiguration或@SpringBootApplication注解的类)的包下的仓库将会被搜索。 - -下面是一个传统的Spring Data仓库: -```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 JPA的表面。具体查看它的[参考指南](http://projects.spring.io/spring-data-jpa/)。 diff --git a/IV. Spring Boot features/28.3.3. Creating and dropping JPA databases.md b/IV. Spring Boot features/28.3.3. Creating and dropping JPA databases.md deleted file mode 100644 index 19eaf4f4..00000000 --- a/IV. Spring Boot features/28.3.3. Creating and dropping JPA databases.md +++ /dev/null @@ -1,9 +0,0 @@ -### 28.3.3. 创建和删除JPA数据库 - -默认情况下,只有在你使用内嵌数据库(H2, HSQL或Derby)时,JPA数据库才会被自动创建。你可以使用spring.jpa.*属性显示的设置JPA。比如,为了创建和删除表你可以将下面的配置添加到application.properties中: -```java -spring.jpa.hibernate.ddl-auto=create-drop -``` -**注**:Hibernate自己内部对创建,删除表支持(如果你恰好记得这回事更好)的属性是hibernate.hbm2ddl.auto。使用spring.jpa.properties.*(前缀在被添加到实体管理器之前会被剥离掉),你可以设置Hibernate本身的属性,比如hibernate.hbm2ddl.auto。示例:`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/28.4 Actuator Security.md b/IV. Spring Boot features/28.4 Actuator Security.md new file mode 100644 index 00000000..411a5532 --- /dev/null +++ b/IV. Spring Boot features/28.4 Actuator Security.md @@ -0,0 +1,10 @@ +### 28.4 Actuator安全 +如果Actuator处于使用中,你会发现: + +* 管理的端点是安全的,即使应用端点不安全。 +* Security事件转换为`AuditEvents`,并发布到`AuditService`。 +* 默认用户有`ADMIN`,`USER`角色。 + +Actuator的安全特性可以通过外部配置属性(`management.security.*`)进行修改。为了覆盖应用访问规则但不覆盖actuator的访问规则,你可以添加一个`WebSecurityConfigurerAdapter`类型的`@Bean`,并注解`@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)`,如果想覆盖actuator访问规则,则注解`@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)`。 + + 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..01a6d2ac --- /dev/null +++ b/IV. Spring Boot features/29. Working with SQL databases.md @@ -0,0 +1,2 @@ +### 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 new file mode 100644 index 00000000..c7c94370 --- /dev/null +++ b/IV. Spring Boot features/29.1. Configure a DataSource.md @@ -0,0 +1,3 @@ +### 29.1. 配置DataSource + +Java的`javax.sql.DataSource`接口提供了一个标准的使用数据库连接的方法。通常,DataSource使用`URL`和相应的凭证去初始化数据库连接。 diff --git a/IV. Spring Boot features/29.1. Redis.md b/IV. Spring Boot features/29.1. Redis.md deleted file mode 100644 index a698d33e..00000000 --- a/IV. Spring Boot features/29.1. Redis.md +++ /dev/null @@ -1,3 +0,0 @@ -### 29.1. Redis - -[Redis](http://redis.io/)是一个缓存,消息中间件及具有丰富特性的键值存储系统。Spring Boot为[Jedis](https://github.com/xetorthio/jedis/)客户端库和由[Spring Data Redis](https://github.com/spring-projects/spring-data-redis)提供的基于Jedis客户端的抽象提供自动配置。`spring-boot-starter-redis`'Starter POM'为收集依赖提供一种便利的方式。 diff --git a/IV. Spring Boot features/29.1.1. Connecting to Redis.md b/IV. Spring Boot features/29.1.1. Connecting to Redis.md deleted file mode 100644 index 855472c8..00000000 --- a/IV. Spring Boot features/29.1.1. Connecting to Redis.md +++ /dev/null @@ -1,17 +0,0 @@ -### 29.1.1. 连接Redis - -你可以注入一个自动配置的RedisConnectionFactory,StringRedisTemplate或普通的跟其他Spring Bean相同的RedisTemplate实例。默认情况下,这个实例将尝试使用localhost:6379连接Redis服务器。 -```java -@Component -public class MyBean { - - private StringRedisTemplate template; - - @Autowired - public MyBean(StringRedisTemplate template) { - this.template = template; - } - // ... -} -``` -如果你添加一个你自己的任何自动配置类型的@Bean,它将替换默认的(除了RedisTemplate的情况,它是根据bean的名称'redisTemplate'而不是它的类型进行排除的)。如果在classpath路径下存在commons-pool2,默认你会获得一个连接池工厂。 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 new file mode 100644 index 00000000..341c113d --- /dev/null +++ b/IV. Spring Boot features/29.1.1. Embedded Database Support.md @@ -0,0 +1,21 @@ +### 29.1.1. 对内嵌数据库的支持 + +开发应用时使用内存数据库是很方便的。显然,内存数据库不提供持久化存储;你只需要在应用启动时填充数据库,在应用结束前预先清除数据。 + +Spring Boot可以自动配置的内嵌数据库包括[H2](http://www.h2database.com/), [HSQL](http://hsqldb.org/)和[Derby](http://db.apache.org/derby/)。你不需要提供任何连接URLs,只需要添加你想使用的内嵌数据库依赖。 + +示例:典型的POM依赖如下: +```xml + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hsqldb + hsqldb + runtime + +``` +**注** 对于自动配置的内嵌数据库,你需要添加`spring-jdbc`依赖,在本示例中,`spring-boot-starter-data-jpa`已包含该依赖了。 + +**注** 无论出于什么原因,你需要配置内嵌数据库的连接URL,一定要确保数据库的自动关闭是禁用的。如果使用H2,你需要设置`DB_CLOSE_ON_EXIT=FALSE`。如果使用HSQLDB,你需要确保没使用`shutdown=true`。禁用数据库的自动关闭可以让Spring 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..f0066ffa --- /dev/null +++ b/IV. Spring Boot features/29.1.2. Connection to a production database.md @@ -0,0 +1,41 @@ +### 29.1.2. 连接生产环境数据库 + +生产环境的数据库连接可以通过池化的`DataSource`进行自动配置,下面是选取特定实现的算法: + +- 出于tomcat数据源连接池的优秀性能和并发,如果可用总会优先使用它。 +- 如果HikariCP可用,我们将使用它。 +- 如果Commons DBCP可用,我们将使用它,但生产环境不推荐。 +- 最后,如果Commons DBCP2可用,我们将使用它。 + +如果使用`spring-boot-starter-jdbc`或`spring-boot-starter-data-jpa` 'starters',你会自动添加`tomcat-jdbc`依赖。 + +**注** 通过指定`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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java),有些标准配置是跟实现无关的,对于实现相关的配置可以通过相应前缀进行设置(`spring.datasource.tomcat.*`,`spring.datasource.hikari.*`,`spring.datasource.dbcp.*`和`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 new file mode 100644 index 00000000..044fc32a --- /dev/null +++ b/IV. Spring Boot features/29.1.3. Connection to a JNDI DataSource.md @@ -0,0 +1,8 @@ +### 29.1.3. 连接JNDI数据库 + +如果正在将Spring Boot应用部署到一个应用服务器,你可能想要用应用服务器内建的特性来配置和管理你的DataSource,并使用JNDI访问它。 + +`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. MongoDB.md b/IV. Spring Boot features/29.2. MongoDB.md deleted file mode 100644 index 5db8d6bf..00000000 --- a/IV. Spring Boot features/29.2. MongoDB.md +++ /dev/null @@ -1,3 +0,0 @@ -### 29.2. MongoDB - -[MongoDB](http://www.mongodb.com/)是一个开源的NoSQL文档数据库,它使用一个JSON格式的模式(schema)替换了传统的基于表的关系数据。Spring Boot为使用MongoDB提供了很多便利,包括`spring-boot-starter-data-mongodb`'Starter POM'。 diff --git a/IV. Spring Boot features/28.2. Using JdbcTemplate.md b/IV. Spring Boot features/29.2. Using JdbcTemplate.md similarity index 66% rename from IV. Spring Boot features/28.2. Using JdbcTemplate.md rename to IV. Spring Boot features/29.2. Using JdbcTemplate.md index f318d5bd..d8e3ae35 100644 --- a/IV. Spring Boot features/28.2. Using JdbcTemplate.md +++ b/IV. Spring Boot features/29.2. Using JdbcTemplate.md @@ -1,6 +1,6 @@ -### 28.2. 使用JdbcTemplate +### 29.2. 使用JdbcTemplate -Spring的JdbcTemplate和NamedParameterJdbcTemplate类是被自动配置的,你可以在自己的beans中通过@Autowire直接注入它们。 +Spring的`JdbcTemplate`和`NamedParameterJdbcTemplate`类会被自动配置,你可以将它们直接`@Autowire`到自己的beans: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; diff --git a/IV. Spring Boot features/29.2.1. Connecting to a MongoDB database.md b/IV. Spring Boot features/29.2.1. Connecting to a MongoDB database.md deleted file mode 100644 index e6f18100..00000000 --- a/IV. Spring Boot features/29.2.1. Connecting to a MongoDB database.md +++ /dev/null @@ -1,32 +0,0 @@ -### 29.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,或指定一个host/port。比如,你可能会在你的application.properties中设置如下的属性: -```java -spring.data.mongodb.host=mongoserver -spring.data.mongodb.port=27017 -``` -**注**:如果没有指定`spring.data.mongodb.port`,那将使用默认的端口27017。你可以简单的从上面的示例中删除这一行。如果不使用Spring Data Mongo,你可以注入com.mongodb.Mongo beans而不是使用MongoDbFactory。 - -如果想全面控制MongoDB连接的建立,你也可以声明自己的MongoDbFactory或Mongo,@Beans。 diff --git a/IV. Spring Boot features/29.2.3. Spring Data MongoDB repositories.md b/IV. Spring Boot features/29.2.3. Spring Data MongoDB repositories.md deleted file mode 100644 index d47e741c..00000000 --- a/IV. Spring Boot features/29.2.3. Spring Data MongoDB repositories.md +++ /dev/null @@ -1,19 +0,0 @@ -### 29.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); - -} -``` diff --git a/IV. Spring Boot features/29.3. Gemfire.md b/IV. Spring Boot features/29.3. Gemfire.md deleted file mode 100644 index 443c1aca..00000000 --- a/IV. Spring Boot features/29.3. Gemfire.md +++ /dev/null @@ -1,3 +0,0 @@ -### 29.3. 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 POM'。目前不支持Gemfire的自动配置,但你可以使用一个[单一的注解](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/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" new file mode 100644 index 00000000..06622870 --- /dev/null +++ "b/IV. Spring Boot features/29.3. JPA and \342\200\230Spring Data\342\200\231.md" @@ -0,0 +1,11 @@ +### 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/)的参考文档。 + +**注** Spring Boot默认使用Hibernate 5.0.x,如果你希望的话也可以使用4.3.x或5.2.x,具体参考[Hibernate 4](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-hibernate4)和[Hibernate 5.2](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-hibernate52)示例。 diff --git a/IV. Spring Boot features/28.3.1. Entity Classes.md b/IV. Spring Boot features/29.3.1. Entity Classes.md similarity index 55% rename from IV. Spring Boot features/28.3.1. Entity Classes.md rename to IV. Spring Boot features/29.3.1. Entity Classes.md index 5c59cbd4..1f05badc 100644 --- a/IV. Spring Boot features/28.3.1. Entity Classes.md +++ b/IV. Spring Boot features/29.3.1. Entity Classes.md @@ -1,8 +1,8 @@ -### 28.3.1. 实体类 +### 29.3.1. 实体类 -传统上,JPA实体类被定义到一个persistence.xml文件中。在Spring Boot中,这个文件不是必需的,并被'实体扫描'替代。默认情况下,在你主(main)配置类(被@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注解自定义实体扫描路径。具体参考[Section 67.4, “Separate @Entity definitions from Spring configuration”](../IX. ‘How-to’ guides/67.4. Separate @Entity definitions from Spring configuration.md)。 +**注** 你可以使用`@EntityScan`注解自定义实体扫描路径,具体参考[Section 74.4, “Separate @Entity definitions from Spring configuration”](../IX. ‘How-to’ guides/74.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 new file mode 100644 index 00000000..ca0267d2 --- /dev/null +++ b/IV. Spring Boot features/29.3.2. Spring Data JPA Repositories.md @@ -0,0 +1,23 @@ +### 29.3.2. Spring Data JPA仓库 + +Spring Data JPA仓库(repositories)是用来定义访问数据的接口。根据你的方法名,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仓库通常继承自[`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仓库: +```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 JPA的表面,具体查看它的[参考指南](http://projects.spring.io/spring-data-jpa/)。 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..b84c847f --- /dev/null +++ b/IV. Spring Boot features/29.3.3. Creating and dropping JPA databases.md @@ -0,0 +1,9 @@ +### 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..256ac4a9 --- /dev/null +++ "b/IV. Spring Boot features/29.4 Using H2\342\200\231s web console.md" @@ -0,0 +1,8 @@ +### 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/1.4.1.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. Solr.md b/IV. Spring Boot features/29.4. Solr.md deleted file mode 100644 index 7df3d6cb..00000000 --- a/IV. Spring Boot features/29.4. Solr.md +++ /dev/null @@ -1,3 +0,0 @@ -### 29.4. Solr - -[Apache Solr](http://lucene.apache.org/solr/)是一个搜索引擎。Spring Boot为solr客户端库及[Spring Data Solr](https://github.com/spring-projects/spring-data-solr)提供的基于solr客户端库的抽象提供了基本的配置。Spring Boot提供了一个用于聚集依赖的`spring-boot-starter-data-solr`'Starter POM'。 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..80a31dc7 --- /dev/null +++ "b/IV. Spring Boot features/29.4.1 Changing the H2 console\342\200\231s path.md" @@ -0,0 +1,2 @@ +### 29.4.1 改变H2控制台路径 +H2控制台路径默认为`/h2-console`,你可以通过设置`spring.h2.console.path`属性自定义该路径。 diff --git a/IV. Spring Boot features/29.4.1. Connecting to Solr.md b/IV. Spring Boot features/29.4.1. Connecting to Solr.md deleted file mode 100644 index 45906f0d..00000000 --- a/IV. Spring Boot features/29.4.1. Connecting to Solr.md +++ /dev/null @@ -1,17 +0,0 @@ -### 29.4.1. 连接Solr - -你可以像其他Spring beans一样注入一个自动配置的SolrServer实例。默认情况下,该实例将尝试使用`localhost:8983/solr`连接一个服务器。 -```java -@Component -public class MyBean { - - private SolrServer solr; - - @Autowired - public MyBean(SolrServer solr) { - this.solr = solr; - } - // ... -} -``` -如果你添加一个自己的SolrServer类型的@Bean,它将会替换默认的。 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 new file mode 100644 index 00000000..3a044d41 --- /dev/null +++ b/IV. Spring Boot features/29.4.2 Securing the H2 console.md @@ -0,0 +1,6 @@ +### 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.4.2. Spring Data Solr repositories.md b/IV. Spring Boot features/29.4.2. Spring Data Solr repositories.md deleted file mode 100644 index 51d8a1ea..00000000 --- a/IV. Spring Boot features/29.4.2. Spring Data Solr repositories.md +++ /dev/null @@ -1,8 +0,0 @@ - -### 29.4.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/29.5 Using jOOQ.md b/IV. Spring Boot features/29.5 Using jOOQ.md new file mode 100644 index 00000000..4b4dacf5 --- /dev/null +++ b/IV. Spring Boot features/29.5 Using jOOQ.md @@ -0,0 +1,4 @@ +### 29.5 使用jOOQ +Java面向对象查询([jOOQ](http://www.jooq.org/))是[Data Geekery](http://www.datageekery.com/)的一个明星产品,可以从数据库生成Java代码,让你通过它的流式API构建类型安全的SQL查询。不管是商业版,还是开源版本都能跟Spring Boot一块使用。 + + diff --git a/IV. Spring Boot features/29.5. Elasticsearch.md b/IV. Spring Boot features/29.5. Elasticsearch.md deleted file mode 100644 index 41e7e1d0..00000000 --- a/IV. Spring Boot features/29.5. Elasticsearch.md +++ /dev/null @@ -1,3 +0,0 @@ -### 29.5. Elasticsearch - -[Elastic Search](http://www.elasticsearch.org/)是一个开源的,分布式,实时搜索和分析引擎。Spring Boot为Elasticsearch及[Spring Data Elasticsearch](https://github.com/spring-projects/spring-data-elasticsearch)提供的基于它的抽象提供了基本的配置。Spring Boot提供了一个用于聚集依赖的`spring-boot-starter-data-elasticsearch`'Starter POM'。 diff --git a/IV. Spring Boot features/29.5.1 Code Generation.md b/IV. Spring Boot features/29.5.1 Code Generation.md new file mode 100644 index 00000000..ed5b4f47 --- /dev/null +++ b/IV. Spring Boot features/29.5.1 Code Generation.md @@ -0,0 +1,27 @@ +### 29.5.1 代码生成 +为了使用jOOQ类型安全的查询,你需要从数据库schema生成Java类,具体可参考[jOOQ用户指南](http://www.jooq.org/doc/3.6/manual-single-page/#jooq-in-7-steps-step3)。如果正在使用`jooq-codegen-maven`插件(也使用`spring-boot-starter-parent` “parent POM”),你可以安全的省略插件的``标签,也可以使用Spring Boot定义的版本变量(比如`h2.version`)来声明插件的数据库依赖,示例如下: +```xml + + org.jooq + jooq-codegen-maven + + ... + + + + com.h2database + h2 + ${h2.version} + + + + + org.h2.Driver + jdbc:h2:~/yourdatabase + + + ... + + + +``` diff --git a/IV. Spring Boot features/29.5.1. Connecting to Elasticsearch.md b/IV. Spring Boot features/29.5.1. Connecting to Elasticsearch.md deleted file mode 100644 index 48f1149a..00000000 --- a/IV. Spring Boot features/29.5.1. Connecting to Elasticsearch.md +++ /dev/null @@ -1,17 +0,0 @@ -### 29.5.1. 连接Elasticsearch - -你可以像其他Spring beans那样注入一个自动配置的ElasticsearchTemplate或Elasticsearch客户端实例。默认情况下,该实例将尝试连接到一个本地内存服务器(在Elasticsearch项目中的一个NodeClient),但你可以通过设置`spring.data.elasticsearch.clusterNodes`为一个以逗号分割的host:port列表来将其切换到一个远程服务器(比如,TransportClient)。 -```java -@Component -public class MyBean { - - private ElasticsearchTemplate template; - - @Autowired - public MyBean(ElasticsearchTemplate template) { - this.template = template; - } - // ... -} -``` -如果你添加一个你自己的ElasticsearchTemplate类型的@Bean,它将替换默认的。 diff --git a/IV. Spring Boot features/29.5.2 Using DSLContext.md b/IV. Spring Boot features/29.5.2 Using DSLContext.md new file mode 100644 index 00000000..48b56696 --- /dev/null +++ b/IV. Spring Boot features/29.5.2 Using DSLContext.md @@ -0,0 +1,25 @@ +### 29.5.2 使用DSLContext +jOOQ提供的流式(fluent)API是通过`org.jooq.DSLContext`接口初始化的,Spring Boot将自动配置一个`DSLContext`为Spring Bean,并将它跟应用的`DataSource`连接起来。想要使用`DSLContext`,只需`@Autowire`注入它: +```java +@Component +public class JooqExample implements CommandLineRunner { + + private final DSLContext create; + + @Autowired + public JooqExample(DSLContext dslContext) { + this.create = dslContext; + } + +} +``` +**注** jOOQ手册倾向于使用一个名为`create`的变量持有`DSLContext`,示例中也是这样做的。 + +然后你就可以使用`DSLContext`构造查询: +```java +public List authorsBornAfter1980() { + return this.create.selectFrom(AUTHOR) + .where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1))) + .fetch(AUTHOR.DATE_OF_BIRTH); +} +``` diff --git a/IV. Spring Boot features/29.5.2. Spring Data Elasticsearch repositories.md b/IV. Spring Boot features/29.5.2. Spring Data Elasticsearch repositories.md deleted file mode 100644 index 6c3ba148..00000000 --- a/IV. Spring Boot features/29.5.2. Spring Data Elasticsearch repositories.md +++ /dev/null @@ -1,7 +0,0 @@ -### 29.5.2. 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/29.5.3 Customizing jOOQ.md b/IV. Spring Boot features/29.5.3 Customizing jOOQ.md new file mode 100644 index 00000000..ded95b8c --- /dev/null +++ b/IV. Spring Boot features/29.5.3 Customizing jOOQ.md @@ -0,0 +1,15 @@ +### 29.5.3 自定义jOOQ +通过在`application.properties`中设置`spring.jooq.sql-dialect`属性,你可以自定义jOOQ使用的SQL方言(dialect)。例如,设置方言为Postgres: +```properties +spring.jooq.sql-dialect=Postgres +``` +定义自己的`@Bean`,在jOOQ`Configuration`创建时使用,可以实现更高级的定制。你可以为以下jOOQ类型定义beans: + +* `ConnectionProvider` +* `TransactionProvider` +* `RecordMapperProvider` +* `RecordListenerProvider` +* `ExecuteListenerProvider` +* `VisitListenerProvider` + +如果想全面控制jOOQ配置,你甚至可以创建自己的`org.jooq.Configuration` `@Bean`。 diff --git a/IV. Spring Boot features/30. Messaging.md b/IV. Spring Boot features/30. Messaging.md deleted file mode 100644 index f5293e3c..00000000 --- a/IV. Spring Boot features/30. Messaging.md +++ /dev/null @@ -1,7 +0,0 @@ -### 30. 消息 - -Spring Framework框架为集成消息系统提供了扩展(extensive)支持:从使用JmsTemplate简化JMS API,到实现一个完整异步消息接收的底层设施。 - -Spring AMQP提供一个相似的用于'高级消息队列协议'的特征集,并且Spring Boot也为RabbitTemplate和RabbitMQ提供了自动配置选项。 - -Spring Websocket提供原生的STOMP消息支持,并且Spring Boot通过starters和一些自动配置也提供了对它的支持。 diff --git a/IV. Spring Boot features/29. Working with NoSQL technologies.md b/IV. Spring Boot features/30. Working with NoSQL technologies.md similarity index 66% rename from IV. Spring Boot features/29. Working with NoSQL technologies.md rename to IV. Spring Boot features/30. Working with NoSQL technologies.md index a80cd089..ebc11c97 100644 --- a/IV. Spring Boot features/29. Working with NoSQL technologies.md +++ b/IV. Spring Boot features/30. Working with NoSQL technologies.md @@ -1,2 +1,2 @@ -### 29. 使用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/), [Couchbase](http://projects.spring.io/spring-data-couchbase/)和[Cassandra](http://projects.spring.io/spring-data-cassandra/)。Spring Boot为Redis, MongoDB, Elasticsearch, Solr和Gemfire提供自动配置。你可以充分利用其他项目,但你需要自己配置它们。具体查看[projects.spring.io/spring-data](http://projects.spring.io/spring-data/)中合适的参考文档。 +### 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/), [Couchbase](http://projects.spring.io/spring-data-couchbase/)和[Cassandra](http://projects.spring.io/spring-data-cassandra/)。Spring Boot为Redis, MongoDB, Elasticsearch, Solr和Cassandra提供自动配置。你也可以充分利用其他项目,但需要自己配置它们,具体查看[projects.spring.io/spring-data](http://projects.spring.io/spring-data/)中相应的参考文档。 diff --git a/IV. Spring Boot features/30.1. JMS.md b/IV. Spring Boot features/30.1. JMS.md deleted file mode 100644 index 09e66313..00000000 --- a/IV. Spring Boot features/30.1. JMS.md +++ /dev/null @@ -1,5 +0,0 @@ -### 30.1. JMS - -javax.jms.ConnectionFactory接口提供了一个标准的用于创建一个javax.jms.Connection的方法,javax.jms.Connection用于和JMS代理(broker)交互。 - -尽管为了使用JMS,Spring需要一个ConnectionFactory,但通常你不需要直接使用它,而是依赖于上层消息抽象(具体参考Spring框架的[相关章节](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#jms))。Spring Boot也会自动配置发送和接收消息需要的设施(infrastructure)。 diff --git a/IV. Spring Boot features/30.1. Redis.md b/IV. Spring Boot features/30.1. Redis.md new file mode 100644 index 00000000..d066fed9 --- /dev/null +++ b/IV. Spring Boot features/30.1. Redis.md @@ -0,0 +1,3 @@ +### 30.1. Redis + +[Redis](http://redis.io/)是一个缓存,消息中间件及具有丰富特性的键值存储系统。Spring Boot为[Jedis](https://github.com/xetorthio/jedis/)客户端library提供基本的自动配置,[Spring Data Redis](https://github.com/spring-projects/spring-data-redis)提供了在它之上的抽象,`spring-boot-starter-redis`'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 new file mode 100644 index 00000000..ca79c414 --- /dev/null +++ b/IV. Spring Boot features/30.1.1. Connecting to Redis.md @@ -0,0 +1,17 @@ +### 30.1.1. 连接Redis + +你可以注入一个自动配置的`RedisConnectionFactory`,`StringRedisTemplate`或普通的`RedisTemplate`实例,或任何其他Spring Bean只要你愿意。默认情况下,这个实例将尝试使用`localhost:6379`连接Redis服务器: +```java +@Component +public class MyBean { + + private StringRedisTemplate template; + + @Autowired + public MyBean(StringRedisTemplate template) { + this.template = template; + } + // ... +} +``` +如果你添加一个自己的,或任何自动配置类型的`@Bean`,它将替换默认实例(除了`RedisTemplate`的情况,它是根据`bean`的name 'redisTemplate'而不是类型进行排除的)。如果在classpath路径下存在`commons-pool2`,默认你会获得一个连接池工厂。 diff --git a/IV. Spring Boot features/30.1.1. HornetQ support.md b/IV. Spring Boot features/30.1.1. HornetQ support.md deleted file mode 100644 index a0cc745f..00000000 --- a/IV. Spring Boot features/30.1.1. HornetQ support.md +++ /dev/null @@ -1,15 +0,0 @@ -### 30.1.1. HornetQ支持 - -如果在classpath下发现HornetQ,Spring Boot会自动配置ConnectionFactory。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(除非显式设置mode属性)。支持的modes有:embedded(显式声明使用一个内嵌的代理,如果该代理在classpath下不可用将导致一个错误),native(使用netty传输协议连接代理)。当后者被配置,Spring Boot配置一个连接到一个代理的ConnectionFactory,该代理运行在使用默认配置的本地机器上。 - -**注**:如果使用spring-boot-starter-hornetq,连接到一个已存在的HornetQ实例所需的依赖都会被提供,同时还有用于集成JMS的Spring基础设施。将org.hornetq:hornetq-jms-server添加到你的应用中,你就可以使用embedded模式。 - -HornetQ配置被spring.hornetq.*中的外部配置属性所控制。例如,你可能在application.properties声明以下片段: -```java -spring.hornetq.mode=native -spring.hornetq.host=192.168.1.210 -spring.hornetq.port=9876 -``` -当内嵌代理时,你可以选择是否启用持久化,并且列表中的目标都应该是可用的。这些可以通过一个以逗号分割的列表来指定一些默认的配置项,或定义org.hornetq.jms.server.config.JMSQueueConfiguration或org.hornetq.jms.server.config.TopicConfiguration类型的bean(s)来配置更高级的队列和主题。具体参考[HornetQProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQProperties.java)。 - -没有涉及JNDI查找,目标是通过名字解析的,名字即可以使用HornetQ配置中的name属性,也可以是配置中提供的names。 diff --git a/IV. Spring Boot features/30.1.2. ActiveMQ support.md b/IV. Spring Boot features/30.1.2. ActiveMQ support.md deleted file mode 100644 index fdbcaaac..00000000 --- a/IV. Spring Boot features/30.1.2. ActiveMQ support.md +++ /dev/null @@ -1,13 +0,0 @@ -### 30.1.2. ActiveQ支持 - -如果发现ActiveMQ在classpath下可用,Spring Boot会配置一个ConnectionFactory。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(只要配置中没有指定代理URL)。 - -ActiveMQ配置是通过spring.activemq.*中的外部配置来控制的。例如,你可能在application.properties中声明下面的片段: -```java -spring.activemq.broker-url=tcp://192.168.1.210:9876 -spring.activemq.user=admin -spring.activemq.password=secret -``` -具体参考[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/30.1.3. Using a JNDI ConnectionFactory.md b/IV. Spring Boot features/30.1.3. Using a JNDI ConnectionFactory.md deleted file mode 100644 index b1bcd1c6..00000000 --- a/IV. Spring Boot features/30.1.3. Using a JNDI ConnectionFactory.md +++ /dev/null @@ -1,7 +0,0 @@ -### 30.1.3. 使用JNDI ConnectionFactory - -如果你在一个应用服务器中运行你的应用,Spring Boot将尝试使用JNDI定位一个JMS ConnectionFactory。默认情况会检查java:/JmsXA和java:/ -XAConnectionFactory。如果需要的话,你可以使用spring.jms.jndi-name属性来指定一个替代位置。 -```java -spring.jms.jndi-name=java:/MyConnectionFactory -``` diff --git a/IV. Spring Boot features/30.1.4. Sending a message.md b/IV. Spring Boot features/30.1.4. Sending a message.md deleted file mode 100644 index 56b883ab..00000000 --- a/IV. Spring Boot features/30.1.4. Sending a message.md +++ /dev/null @@ -1,19 +0,0 @@ -### 30.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](http://docs.spring.io/spring/docs/4.1.4.RELEASE/javadoc-api/org/springframework/jms/core/JmsMessagingTemplate.html)(Spring4.1新增的)也可以使用相同的方式注入 diff --git a/IV. Spring Boot features/30.1.5. Receiving a message.md b/IV. Spring Boot features/30.1.5. Receiving a message.md deleted file mode 100644 index c8811da8..00000000 --- a/IV. Spring Boot features/30.1.5. Receiving a message.md +++ /dev/null @@ -1,13 +0,0 @@ -### 30.1.5. 接收消息 - -当JMS基础设施能够使用时,任何bean都能够被@JmsListener注解,以创建一个监听者端点。如果没有定义JmsListenerContainerFactory,一个默认的将会被自动配置。下面的组件在someQueue目标上创建一个监听者端点。 -```java -@Component -public class MyBean { -@JmsListener(destination = "someQueue") -public void processMessage(String content) { -// ... -} -} -``` -具体查看[@EnableJms javadoc](http://docs.spring.io/spring/docs/4.1.4.RELEASE/javadoc-api/org/springframework/jms/annotation/EnableJms.html)。 diff --git a/IV. Spring Boot features/30.2. MongoDB.md b/IV. Spring Boot features/30.2. MongoDB.md new file mode 100644 index 00000000..849e5921 --- /dev/null +++ b/IV. Spring Boot features/30.2. MongoDB.md @@ -0,0 +1,3 @@ +### 30.2. MongoDB + +[MongoDB](http://www.mongodb.com/)是一个开源的NoSQL文档数据库,它使用类JSON格式的模式(schema)替换了传统的基于表的关系数据。Spring Boot为使用MongoDB提供了很多便利,包括`spring-boot-starter-data-mongodb`'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..7f0cd1b1 --- /dev/null +++ b/IV. Spring Boot features/30.2.1. Connecting to a MongoDB database.md @@ -0,0 +1,41 @@ +### 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/29.2.2. MongoTemplate.md b/IV. Spring Boot features/30.2.2. MongoTemplate.md similarity index 72% rename from IV. Spring Boot features/29.2.2. MongoTemplate.md rename to IV. Spring Boot features/30.2.2. MongoTemplate.md index 750282d7..1ffdbcab 100644 --- a/IV. Spring Boot features/29.2.2. MongoTemplate.md +++ b/IV. Spring Boot features/30.2.2. MongoTemplate.md @@ -1,6 +1,6 @@ -### 29.2.2. MongoDBTemplate +### 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 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,你只需简单的注入即可: ```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。 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..c3b0ac54 --- /dev/null +++ b/IV. Spring Boot features/30.2.3. Spring Data MongoDB repositories.md @@ -0,0 +1,20 @@ +### 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.2.4 Embedded Mongo.md b/IV. Spring Boot features/30.2.4 Embedded Mongo.md new file mode 100644 index 00000000..b08ed306 --- /dev/null +++ b/IV. Spring Boot features/30.2.4 Embedded Mongo.md @@ -0,0 +1,8 @@ +### 30.2.4 内嵌的Mongo +Spring Boot为[内嵌Mongo](https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo)提供自动配置,你需要添加`de.flapdoodle.embed:de.flapdoodle.embed.mongo`依赖才能使用它。 + +`spring.data.mongodb.port`属性可用来配置Mongo监听的端口,将该属性值设为0,表示使用一个随机分配的可用端口。通过`MongoAutoConfiguration`创建的`MongoClient`将自动配置为使用随机分配的端口。 + +如果classpath下存在SLF4J依赖,Mongo产生的输出将自动路由到一个名为`org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo`的logger。 + +想要完全控制Mongo实例的配置和日志路由,你可以声明自己的`IMongodConfig`和`IRuntimeConfig` beans。 diff --git a/IV. Spring Boot features/30.3 Neo4j.md b/IV. Spring Boot features/30.3 Neo4j.md new file mode 100644 index 00000000..54284ad7 --- /dev/null +++ b/IV. Spring Boot features/30.3 Neo4j.md @@ -0,0 +1,2 @@ +### 30.3 Neo4j +[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..d4483dca --- /dev/null +++ b/IV. Spring Boot features/30.3.1 Connecting to a Neo4j database.md @@ -0,0 +1,25 @@ +### 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..2747dc23 --- /dev/null +++ b/IV. Spring Boot features/30.3.2 Using the embedded mode.md @@ -0,0 +1,8 @@ +### 30.3.2 使用内嵌模式 + +**注** Neo4j的内嵌模式从属于不同的许可,在将它集成到应用之前确保复查下。 + +如果将`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 +``` diff --git a/IV. Spring Boot features/30.3.3 Neo4jSession.md b/IV. Spring Boot features/30.3.3 Neo4jSession.md new file mode 100644 index 00000000..fc8f1628 --- /dev/null +++ b/IV. Spring Boot features/30.3.3 Neo4jSession.md @@ -0,0 +1,5 @@ +### 30.3.3 Neo4jSession +Neo4jSession默认的生命周期是应用程序范围,如果运行的是web应用,你可以很轻松的改变它的scope: +```properties +spring.data.neo4j.session.scope=session +``` 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..8763a8c7 --- /dev/null +++ b/IV. Spring Boot features/30.3.4 Spring Data Neo4j repositories.md @@ -0,0 +1,10 @@ +### 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..25081a54 --- /dev/null +++ b/IV. Spring Boot features/30.3.5 Repository example.md @@ -0,0 +1,16 @@ +### 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 new file mode 100644 index 00000000..ad893b9c --- /dev/null +++ b/IV. Spring Boot features/30.4 Gemfire.md @@ -0,0 +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仓库支持它。 diff --git a/IV. Spring Boot features/30.5 Solr.md b/IV. Spring Boot features/30.5 Solr.md new file mode 100644 index 00000000..0da856b0 --- /dev/null +++ b/IV. Spring Boot features/30.5 Solr.md @@ -0,0 +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'。 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 new file mode 100644 index 00000000..25d2bda6 --- /dev/null +++ b/IV. Spring Boot features/30.5.1 Connecting to Solr.md @@ -0,0 +1,19 @@ +### 30.5.1 连接Solr + +你可以注入一个自动配置的`SolrClient`实例,就像其他Spring beans那样,该实例默认使用`localhost:8983/solr`连接Solr服务器: +```java +@Component +public class MyBean { + + private SolrClient solr; + + @Autowired + public MyBean(SolrClient solr) { + this.solr = solr; + } + + // ... + +} +``` +如果你添加自己的`SolrClient`类型的`@Bean`,它将会替换默认实例。 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..8548f3c5 --- /dev/null +++ b/IV. Spring Boot features/30.5.2 Spring Data Solr repositories.md @@ -0,0 +1,8 @@ + +### 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 new file mode 100644 index 00000000..7f035f96 --- /dev/null +++ b/IV. Spring Boot features/30.6 Elasticsearch.md @@ -0,0 +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'。 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 new file mode 100644 index 00000000..faaab9f9 --- /dev/null +++ b/IV. Spring Boot features/30.6.1 Connecting to Elasticsearch using Jest.md @@ -0,0 +1,9 @@ +### 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 +``` +定义一个`JestClient` 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 new file mode 100644 index 00000000..f0ea2fe3 --- /dev/null +++ b/IV. Spring Boot features/30.6.2 Connecting to Elasticsearch using Spring Data.md @@ -0,0 +1,25 @@ +### 30.6.2 使用Spring Data连接Elasticsearch +你可以注入一个自动配置的`ElasticsearchTemplate`或Elasticsearch `Client`实例,就想其他Spring Bean那样。该实例默认内嵌一个本地,内存型服务器(在Elasticsearch中被称为`Node`),并使用当前工作目录作为服务器的home目录。在这个步骤中,首先要做的是告诉Elasticsearch将文件存放到什么地方: +```properties +spring.data.elasticsearch.properties.path.home=/foo/bar +``` +另外,你可以通过设置`spring.data.elasticsearch.cluster-nodes`(逗号分隔的‘host:port’列表)来切换为远程服务器: +```properties +spring.data.elasticsearch.cluster-nodes=localhost:9300 +``` +```java +@Component +public class MyBean { + + private ElasticsearchTemplate template; + + @Autowired + public MyBean(ElasticsearchTemplate template) { + this.template = template; + } + + // ... + +} +``` +如果添加自己的`ElasticsearchTemplate`类型的`@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..f4a90366 --- /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文档](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 new file mode 100644 index 00000000..b226b205 --- /dev/null +++ b/IV. Spring Boot features/30.7 Cassandra.md @@ -0,0 +1,2 @@ +###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’。 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 new file mode 100644 index 00000000..8a53906f --- /dev/null +++ b/IV. Spring Boot features/30.7.1 Connecting to Cassandra.md @@ -0,0 +1,22 @@ +### 30.7.1 连接Cassandra +你可以注入一个自动配置的`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 +``` +```java +@Component +public class MyBean { + + private CassandraTemplate template; + + @Autowired + public MyBean(CassandraTemplate template) { + this.template = template; + } + + // ... + +} +``` +如果添加自己的`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..e6a80513 --- /dev/null +++ b/IV. Spring Boot features/30.7.2 Spring Data Cassandra repositories.md @@ -0,0 +1,4 @@ +###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 new file mode 100644 index 00000000..4b071d8a --- /dev/null +++ b/IV. Spring Boot features/30.8 Couchbase.md @@ -0,0 +1,2 @@ +###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’。 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 new file mode 100644 index 00000000..54174055 --- /dev/null +++ b/IV. Spring Boot features/30.8.1 Connecting to Couchbase.md @@ -0,0 +1,16 @@ +###30.8.1 连接Couchbase +通过添加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..55b09fad --- /dev/null +++ b/IV. Spring Boot features/30.8.2 Spring Data Couchbase repositories.md @@ -0,0 +1,20 @@ +###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`可以使用。如果想关闭Spring Data Couchbase的自动配置,你可以提供自己的`org.springframework.data.couchbase.config.AbstractCouchbaseDataConfiguration`实现。 +```java +@Component +public class MyBean { + + private final CouchbaseTemplate template; + + @Autowired + public MyBean(CouchbaseTemplate template) { + this.template = template; + } + + // ... + +} +``` +如果添加你自己的`CouchbaseTemplate`类型的`@Bean`,且名称为`couchbaseTemplate`,那它将替换默认实例。 diff --git a/IV. Spring Boot features/31. Caching.md b/IV. Spring Boot features/31. Caching.md new file mode 100644 index 00000000..4955ab27 --- /dev/null +++ b/IV. Spring Boot features/31. Caching.md @@ -0,0 +1,24 @@ +###31. 缓存 +Spring框架提供为应用透明添加缓存的支持,核心思想是,将抽象应用到缓存方法,基于缓存中可用信息减少方法的执行。缓存逻辑的应用是透明的,不会干扰调用者。 + +**注** 具体参考Spring框架指南的[相应章节](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#cache)。 + +简而言之,为服务的某个操作添加缓存跟为方法添加相应注解那样简单: +```java +import javax.cache.annotation.CacheResult; + +import org.springframework.stereotype.Component; + +@Component +public class MathService { + + @CacheResult + public int computePiDecimal(int i) { + // ... + } + +} +``` +**注** 你既可以使用标准的JSR-107 (JCache)注解,也可以使用Spring自己的缓存注解,这是透明的,我们强烈建议你不要混淆使用。 + +**注** 透明的[更新](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#cache-annotations-put)或[驱除](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#cache-annotations-evict)缓存数据是可以的。 diff --git a/IV. Spring Boot features/31. Sending email.md b/IV. Spring Boot features/31. Sending email.md deleted file mode 100644 index 70d450be..00000000 --- a/IV. Spring Boot features/31. Sending email.md +++ /dev/null @@ -1,6 +0,0 @@ -### 31. 发送邮件 - -Spring框架使用JavaMailSender接口为发送邮件提供了一个简单的抽象,并且Spring Boot也为它提供了自动配置和一个starter模块。 -具体查看[JavaMailSender参考文档](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#mail)。 - -如果spring.mail.host和相关的库(通过spring-boot-starter-mail定义)都存在,一个默认的JavaMailSender将被创建。该sender可以通过spring.mail命名空间下的配置项进一步自定义,具体参考[MailProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailProperties.java)。 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..eea01751 --- /dev/null +++ b/IV. Spring Boot features/31.1 Supported cache providers.md @@ -0,0 +1,35 @@ +###31.1 支持的缓存提供商 +缓存抽象不提供实际的存储,而是依赖于`org.springframework.cache.Cache`和`org.springframework.cache.CacheManager`接口的实现。只要通过`@EnableCaching`注解开启缓存支持,Spring Boot就会根据实现自动配置一个合适的`CacheManager`。 + +**注** 如果你使用的缓存设施beans不是基于接口的,确保启用`proxyTargetClass`,并设置其属性为`@EnableCaching`。 + +**注** 使用`spring-boot-starter-cache`‘Starter’可以快速添加所需缓存依赖,如果你是手动添加依赖,需要注意一些实现只有`spring-context-support` jar才提供。 + +如果你还没有定义一个`CacheManager`类型的bean,或一个名为`cacheResolver`的`CacheResolver`(查看`CachingConfigurer`),Spring Boot将尝试以下提供商(按这个顺序): + + * [Generic](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-generic) + * [JCache (JSR-107)](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-jcache)(EhCache 3, Hazelcast, Infinispan, etc) + * [EhCache 2.x](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-ehcache2) + * [Hazelcast](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-hazelcast) + * [Infinispan](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-infinispan) + * [Couchbase](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-couchbase) + * [Redis](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-redis) + * [Caffeine](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-caffeine) + * [Guava](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-guava) + * [Simple](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-simple) + + **注** `spring.cache.type`属性可强制指定使用的缓存提供商,如果需要在一些环境(比如,测试)中[禁用全部缓存](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-caching-provider-none)也可以使用该属性。 + + 如果`CacheManager`是Spring Boot自动配置的,你可以在它完全初始化前,通过实现`CacheManagerCustomizer`接口进一步配置,以下设置使用的缓存name: + ```java + @Bean +public CacheManagerCustomizer cacheManagerCustomizer() { + return new CacheManagerCustomizer() { + @Override + public void customize(ConcurrentMapCacheManager cacheManager) { + cacheManager.setCacheNames(Arrays.asList("one", "two")); + } + }; +} + ``` + **注** 在以上示例中,需要配置一个`ConcurrentMapCacheManager`,如果没有配置,则自定义器(customizer)将不会被调用。自定义器你添加多少都可以,并可以使用`@Order`或`Ordered`对它们进行排序。 diff --git a/IV. Spring Boot features/31.1.1 Generic.md b/IV. Spring Boot features/31.1.1 Generic.md new file mode 100644 index 00000000..07c41807 --- /dev/null +++ b/IV. Spring Boot features/31.1.1 Generic.md @@ -0,0 +1,2 @@ +###31.1.1 Generic +如果上下文定义至少一个`org.springframework.cache.Cache` bean,一个配置好的`CacheManager`包装着它们,那么将使用通用(Generic)缓存。 diff --git a/IV. Spring Boot features/31.1.10 Simple.md b/IV. Spring Boot features/31.1.10 Simple.md new file mode 100644 index 00000000..2bb3ebb6 --- /dev/null +++ b/IV. Spring Boot features/31.1.10 Simple.md @@ -0,0 +1,2 @@ +###31.1.10 Simple +如果以上选项都没有采用,一个使用`ConcurrentHashMap`作为缓存存储的简单实现将被配置,这是应用没有添加缓存library的默认设置。 diff --git a/IV. Spring Boot features/31.1.11 None.md b/IV. Spring Boot features/31.1.11 None.md new file mode 100644 index 00000000..6f12bac3 --- /dev/null +++ b/IV. Spring Boot features/31.1.11 None.md @@ -0,0 +1,5 @@ +###31.1.11 None +如果配置类中出现`@EnableCaching`,一个合适的缓存配置也同样被期待。如果在某些环境需要禁用全部缓存,强制将缓存类型设为`none`将会使用一个no-op实现(没有任何实现的实现): +```properties +spring.cache.type=none +``` diff --git a/IV. Spring Boot features/31.1.2 JCache (JSR-107).md b/IV. Spring Boot features/31.1.2 JCache (JSR-107).md new file mode 100644 index 00000000..2b4db12b --- /dev/null +++ b/IV. Spring Boot features/31.1.2 JCache (JSR-107).md @@ -0,0 +1,18 @@ +###31.1.2 JCache (JSR-107) +classpath下存在`javax.cache.spi.CachingProvider`(比如,一个遵循JSR-107的缓存library),则JCache将启动。这里有很多遵循JSR-107的libraries,Spring Boot为Ehcache 3, Hazelcast和Infinispan提供依赖管理,其他library也可以像这样添加。 + +如果出现多个提供商,你需要明确指定使用哪个(提供商)。尽管JSR-107标准没有强制定义配置文件的位置,Spring Boot会尽量配合各实现情况: +```properties +# Only necessary if more than one provider is present +spring.cache.jcache.provider=com.acme.MyCachingProvider +spring.cache.jcache.config=classpath:acme.xml +``` +**注** 由于一个缓存library可能提供的既有native实现,也有JSR-107支持,Spring Boot将优先使用JSR-107支持,这样如果你切换到不同的JSR-107实现,相同特性依旧可以使用。 + +以下方式可以自定义底层的`javax.cache.cacheManager`: + +* 通过设置`spring.cache.cache-names`属性,缓存可以在启动时就被创建。如果定义一个`javax.cache.configuration.Configuration` bean,它将用于自定义缓存。 + +* 使用`CacheManager`的引用调用`org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer` beans可完成全部配置。 + +**注** 如果定义标准的`javax.cache.CacheManager`,它将自动包装进`org.springframework.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 new file mode 100644 index 00000000..89718a9a --- /dev/null +++ b/IV. Spring Boot features/31.1.3 EhCache 2.x.md @@ -0,0 +1,5 @@ +###31.1.3 EhCache 2.x +如果在classpath下的根目录可以找到一个名为`ehcache.xml`的文件,则缓存将使用EhCache 2.x。如果EhCache 2.x和这样的文件出现,那它们将用于启动缓存管理器,使用以下配置可提供替换的配置文件: +```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 new file mode 100644 index 00000000..9b5e20c7 --- /dev/null +++ b/IV. Spring Boot features/31.1.4 Hazelcast.md @@ -0,0 +1,8 @@ +###31.1.4 Hazelcast +Spring Boot为Hazelcast提供[通常的支持](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-hazelcast),如果`HazelcastInstance`被自动配置,那它将自动包装进一个`CacheManager`。 + +如果出于某些原因,需要使用另一个不同的`HazelcastInstance`,你可以请求Spring Boot创建一个单独的实例,并只用于该`CacheManager`: +```properties +spring.cache.hazelcast.config=classpath:config/my-cache-hazelcast.xml +``` +**注** 如果以这种方式创建一个单独的`HazelcastInstance`,它将不会注册到应用上下文中。 diff --git a/IV. Spring Boot features/31.1.5 Infinispan.md b/IV. Spring Boot features/31.1.5 Infinispan.md new file mode 100644 index 00000000..e3df0c3c --- /dev/null +++ b/IV. Spring Boot features/31.1.5 Infinispan.md @@ -0,0 +1,6 @@ +###31.1.5 Infinispan +Infinispan没有默认的配置文件位置,所以需要显式指定: +```properties +spring.cache.infinispan.config=infinispan.xml +``` +通过设置`spring.cache.cache-names`属性可以让缓存在启动时就被创建,如果定义了`ConfigurationBuilder` bean,它将用来定义该实例。 diff --git a/IV. Spring Boot features/31.1.6 Couchbase.md b/IV. Spring Boot features/31.1.6 Couchbase.md new file mode 100644 index 00000000..8ecfe215 --- /dev/null +++ b/IV. Spring Boot features/31.1.6 Couchbase.md @@ -0,0 +1,32 @@ +###31.1.6 Couchbase +如果Couchbase可用,并配置好了,`CouchbaseCacheManager`将会自动配置,使用`spring.cache.cache-names`属性可以在启动时创建其他缓存。对`Bucket`的操作也是自动配置的,你可以使用customizer在另一个`Bucket`上创建其他缓存:假设你需要在“main” `Bucket`上存放两个缓存(`foo`和`bar`),在另一个`Bucket`上存放一个存活时间为2秒的`biz`缓存。首先,你通过配置创建两个缓存: +```properties +spring.cache.cache-names=foo,bar +``` +然后定义其他`@Configuration`来配置另一个`Bucket`和`biz`缓存: +```java +@Configuration +public class CouchbaseCacheConfiguration { + + private final Cluster cluster; + + public CouchbaseCacheConfiguration(Cluster cluster) { + this.cluster = cluster; + } + + @Bean + public Bucket anotherBucket() { + return this.cluster.openBucket("another", "secret"); + } + + @Bean + public CacheManagerCustomizer cacheManagerCustomizer() { + return c -> { + c.prepareCache("biz", CacheBuilder.newInstance(anotherBucket()) + .withExpirationInMillis(2000)); + }; + } + +} +``` +这个示例配置重用了通过自动配置的`Cluster`。 diff --git a/IV. Spring Boot features/31.1.7 Redis.md b/IV. Spring Boot features/31.1.7 Redis.md new file mode 100644 index 00000000..6e221589 --- /dev/null +++ b/IV. Spring Boot features/31.1.7 Redis.md @@ -0,0 +1,4 @@ +###31.1.7 Redis +如果Redis可用,并配置好了,`RedisCacheManager`将被自动配置,使用`spring.cache.cache-names`可以在启动时创建其他缓存。 + +**注** 默认会添加key前缀以防止两个单独的缓存使用相同的key,否则Redis将存在重复的key,有可能返回不可用的值。如果创建自己的`RedisCacheManager`,强烈建议你保留该配置处于启用状态。 diff --git a/IV. Spring Boot features/31.1.8 Caffeine.md b/IV. Spring Boot features/31.1.8 Caffeine.md new file mode 100644 index 00000000..43b97b30 --- /dev/null +++ b/IV. Spring Boot features/31.1.8 Caffeine.md @@ -0,0 +1,13 @@ +###31.1.8 Caffeine +Caffeine是Java8对Guava缓存的重写版本,在Spring Boot 2.0中将取代Guava。如果出现Caffeine,`CaffeineCacheManager`将会自动配置。使用`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分钟: +```properties +spring.cache.cache-names=foo,bar +spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s +``` +除此之外,如果定义了`com.github.benmanes.caffeine.cache.CacheLoader`,它会自动关联到`CaffeineCacheManager`。由于该`CacheLoader`将关联被该缓存管理器管理的所有缓存,所以它必须定义为`CacheLoader`,自动配置将忽略所有泛型类型。 diff --git a/IV. Spring Boot features/31.1.9 Guava.md b/IV. Spring Boot features/31.1.9 Guava.md new file mode 100644 index 00000000..49278020 --- /dev/null +++ b/IV. Spring Boot features/31.1.9 Guava.md @@ -0,0 +1,13 @@ +###31.1.9 Guava +如果存在Guava,`GuavaCacheManager`会自动配置。使用`spring.cache.cache-names`属性可以在启动时创建缓存,并通过以下方式之一自定义(按此顺序): + +1. `spring.cache.guava.spec`定义的特殊缓存 +2. `com.google.common.cache.CacheBuilderSpec` bean定义的 +3. `com.google.common.cache.CacheBuilder` bean定义的 + +例如,以下配置创建了一个`foo`和`bar`缓存,该缓存最大数量为500,存活时间为10分钟: +```properties +spring.cache.cache-names=foo,bar +spring.cache.guava.spec=maximumSize=500,expireAfterAccess=600s +``` +此外,如果定义`com.google.common.cache.CacheLoader` bean,它会自动关联到`GuavaCacheManager`。由于该`CacheLoader`将关联该缓存管理器管理的所有缓存,它必须定义为`CacheLoader`,自动配置会忽略所有泛型类型。 diff --git a/IV. Spring Boot features/32. Distributed Transactions with JTA.md b/IV. Spring Boot features/32. Distributed Transactions with JTA.md deleted file mode 100644 index 003ab02d..00000000 --- a/IV. Spring Boot features/32. Distributed Transactions with JTA.md +++ /dev/null @@ -1,5 +0,0 @@ -### 32. 使用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/32. Messaging.md b/IV. Spring Boot features/32. Messaging.md new file mode 100644 index 00000000..b3591a31 --- /dev/null +++ b/IV. Spring Boot features/32. Messaging.md @@ -0,0 +1,3 @@ +### 32. 消息 + +Spring Framework框架为集成消息系统提供了扩展(extensive)支持:从使用`JmsTemplate`简化JMS API,到实现一个能够异步接收消息的完整的底层设施。Spring AMQP提供一个相似的用于'高级消息队列协议'的特征集,并且Spring Boot也为`RabbitTemplate`和RabbitMQ提供了自动配置选项。Spring Websocket提供原生的STOMP消息支持,并且Spring Boot也提供了starters和自动配置支持。 diff --git a/IV. Spring Boot features/32.1. JMS.md b/IV. Spring Boot features/32.1. JMS.md new file mode 100644 index 00000000..99dbf563 --- /dev/null +++ b/IV. Spring Boot features/32.1. JMS.md @@ -0,0 +1,3 @@ +### 32.1. JMS +`javax.jms.ConnectionFactory`接口提供标准的用于创建`javax.jms.Connection`的方法,`javax.jms.Connection`用于和JMS代理(broker)交互。 +尽管Spring需要一个`ConnectionFactory`才能使用JMS,通常你不需要直接使用它,而是依赖于上层消息抽象(具体参考Spring框架的[相关章节](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#jms)),Spring Boot会自动配置发送和接收消息需要的设施(infrastructure)。 diff --git a/IV. Spring Boot features/32.1. Using an Atomikos transaction manager.md b/IV. Spring Boot features/32.1. Using an Atomikos transaction manager.md deleted file mode 100644 index 5a0df8bd..00000000 --- a/IV. Spring Boot features/32.1. Using an Atomikos transaction manager.md +++ /dev/null @@ -1,7 +0,0 @@ -### 32.1. 使用一个Atomikos事务管理器 - -Atomikos是一个非常流行的开源事务管理器,它可以嵌入到你的Spring Boot应用中。你可以使用`spring-boot-starter-jta-atomikos`Starter POM去获取正确的Atomikos库。Spring Boot会自动配置Atomikos,并将合适的depends-on应用到你的Spring Beans上,确保它们以正确的顺序启动和关闭。 - -默认情况下,Atomikos事务日志将被记录在应用home目录(你的应用jar文件放置的目录)下的transaction-logs文件夹中。你可以在application.properties文件中通过设置spring.jta.log-dir属性来自定义该目录。以spring.jta.开头的属性能用来自定义Atomikos的UserTransactionServiceIml实现。具体参考[AtomikosProperties javadoc](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/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/32.1.1 ActiveMQ support.md b/IV. Spring Boot features/32.1.1 ActiveMQ support.md new file mode 100644 index 00000000..f4a9583a --- /dev/null +++ b/IV. Spring Boot features/32.1.1 ActiveMQ support.md @@ -0,0 +1,13 @@ +### 32.1.1 ActiveQ支持 + +如果发现ActiveMQ在classpath下可用,Spring Boot会配置一个`ConnectionFactory`。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(只要配置中没有指定代理URL)。 + +ActiveMQ是通过`spring.activemq.*`外部配置来控制的,例如,你可能在`application.properties`中声明以下片段: +```java +spring.activemq.broker-url=tcp://192.168.1.210:9876 +spring.activemq.user=admin +spring.activemq.password=secret +``` +具体参考[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..9188c665 --- /dev/null +++ b/IV. Spring Boot features/32.1.2 Artemis support.md @@ -0,0 +1,16 @@ +###32.1.2 Artemis支持 +Apache Artemis成立于2015年,那时HornetQ刚捐给Apache基金会,确保别使用了过期的HornetQ支持。 +**注** 不要尝试同时使用Artemis和HornetQ。 + +如果发现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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisProperties.java)。 diff --git a/IV. Spring Boot features/32.1.3 HornetQ support.md b/IV. Spring Boot features/32.1.3 HornetQ support.md new file mode 100644 index 00000000..f51a196c --- /dev/null +++ b/IV. Spring Boot features/32.1.3 HornetQ support.md @@ -0,0 +1,17 @@ +### 32.1.3 HornetQ支持 + +**注** HornetQ在1.4版本已过期,可以考虑迁移到[artemis](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-artemis)。 + +如果在classpath下发现HornetQ,Spring Boot会自动配置`ConnectionFactory`。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(除非显式设置mode属性)。支持的modes有:`embedded`(显式声明使用内嵌的代理,如果该代理在classpath下不可用将出错),`native`(使用`netty`传输协议连接代理)。当后者被配置,Spring Boot配置一个连接到代理的`ConnectionFactory`,该代理运行在使用默认配置的本地机器上。 + +**注**:如果使用`spring-boot-starter-hornetq`,连接到一个已存在的HornetQ实例所需的依赖都会被提供,同时还有用于集成JMS的Spring基础设施。将`org.hornetq:hornetq-jms-server`添加到应用中,你就可以使用`embedded`模式。 + +HornetQ配置被`spring.hornetq.*`中的外部配置属性所控制,例如,在`application.properties`声明以下片段: +```java +spring.hornetq.mode=native +spring.hornetq.host=192.168.1.210 +spring.hornetq.port=9876 +``` +当内嵌代理时,你可以选择是否启用持久化,并且列表中的目标都应该是可用的。这些可以通过一个以逗号分割的列表来指定一些默认的配置项,或定义`org.hornetq.jms.server.config.JMSQueueConfiguration`或`org.hornetq.jms.server.config.TopicConfiguration`类型的bean(s)来配置更高级的队列和主题,具体参考[HornetQProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQProperties.java)。 + +没有涉及JNDI查找,目标是通过名字解析的,名字即可以使用HornetQ配置中的name属性,也可以是配置中提供的names。 diff --git a/IV. Spring Boot features/32.1.4 Using a JNDI ConnectionFactory.md b/IV. Spring Boot features/32.1.4 Using a JNDI ConnectionFactory.md new file mode 100644 index 00000000..41f0a54c --- /dev/null +++ b/IV. Spring Boot features/32.1.4 Using a JNDI ConnectionFactory.md @@ -0,0 +1,7 @@ +### 32.1.4 使用JNDI ConnectionFactory + +如果你的App运行在应用服务器中,Spring Boot将尝试使用JNDI定位一个JMS `ConnectionFactory`,默认会检查`java:/JmsXA`和`java:/ +XAConnectionFactory`两个地址。如果需要指定替换位置,可以使用`spring.jms.jndi-name`属性: +```java +spring.jms.jndi-name=java:/MyConnectionFactory +``` diff --git a/IV. Spring Boot features/32.1.5 Sending a message.md b/IV. Spring Boot features/32.1.5 Sending a message.md new file mode 100644 index 00000000..cfad42cd --- /dev/null +++ b/IV. Spring Boot features/32.1.5 Sending a message.md @@ -0,0 +1,19 @@ +###32.1.5 发送消息 + +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](http://docs.spring.io/spring/docs/4.3.3.RELEASE/javadoc-api/org/springframework/jms/core/JmsMessagingTemplate.html)。如果定义了`DestinationResolver`或`MessageConverter` beans,它们将自动关联到自动配置的`JmsTemplate`。 diff --git a/IV. Spring Boot features/32.1.6 Receiving a message.md b/IV. Spring Boot features/32.1.6 Receiving a message.md new file mode 100644 index 00000000..a1486816 --- /dev/null +++ b/IV. Spring Boot features/32.1.6 Receiving a message.md @@ -0,0 +1,49 @@ +###32.1.6 接收消息 + +当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](http://docs.spring.io/spring/docs/4.3.3.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 AMQP.md b/IV. Spring Boot features/32.2 AMQP.md new file mode 100644 index 00000000..0cafbe46 --- /dev/null +++ b/IV. Spring Boot features/32.2 AMQP.md @@ -0,0 +1,2 @@ +###32.2 AMQP +高级消息队列协议(AMQP)是一个用于消息中间件的,平台无关的,线路级(wire-level)协议。Spring AMQP项目使用Spring的核心概念开发基于AMQP的消息解决方案,Spring Boot为通过RabbitMQ使用AMQP提供了一些便利,包括`spring-boot-starter-amqp`‘Starter’。 diff --git a/IV. Spring Boot features/32.2. Using a Bitronix transaction manager.md b/IV. Spring Boot features/32.2. Using a Bitronix transaction manager.md deleted file mode 100644 index 7650311f..00000000 --- a/IV. Spring Boot features/32.2. Using a Bitronix transaction manager.md +++ /dev/null @@ -1,7 +0,0 @@ -### 32.2. 使用一个Bitronix事务管理器 - -Bitronix是另一个流行的开源JTA事务管理器实现。你可以使用`spring-boot-starter-jta-bitronix`starter POM为项目添加合适的Birtronix依赖。和Atomikos类似,Spring Boot将自动配置Bitronix,并对beans进行后处理(post-process)以确保它们以正确的顺序启动和关闭。 - -默认情况下,Bitronix事务日志将被记录到应用home目录下的transaction-logs文件夹中。通过设置spring.jta.log-dir属性,你可以自定义该目录。以spring.jta.开头的属性将被绑定到bitronix.tm.Configuration bean,你可以通过这完成进一步的自定义。具体参考[Bitronix文档](http://btm.codehaus.org/api/2.0.1/bitronix/tm/Configuration.html)。 - -**注**:为了确保多个事务管理器能够安全地和相应的资源管理器配合,每个Bitronix实例必须设置一个唯一的ID。默认情况下,该ID是Bitronix实例运行的机器上的IP地址。为了确保生产环境中该ID的唯一性,你需要为应用的每个实例设置不同的spring.jta.transaction-manager-id属性值。 diff --git a/IV. Spring Boot features/32.2.1 RabbitMQ support.md b/IV. Spring Boot features/32.2.1 RabbitMQ support.md new file mode 100644 index 00000000..b62ec5fd --- /dev/null +++ b/IV. Spring Boot features/32.2.1 RabbitMQ support.md @@ -0,0 +1,9 @@ +###32.2.1 RabbitMQ支持 +RabbitMQ是一个基于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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitProperties.java)。 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..dcdcc247 --- /dev/null +++ b/IV. Spring Boot features/32.2.2 Sending a message.md @@ -0,0 +1,27 @@ +###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..e25b8def --- /dev/null +++ b/IV. Spring Boot features/32.2.3 Receiving a message.md @@ -0,0 +1,51 @@ +###32.2.3 接收消息 +当Rabbit设施出现时,所有bean都可以注解`@RabbitListener`来创建一个监听器端点。如果没有定义`RabbitListenerContainerFactory`,Spring Boot将自动配置一个默认的。如果定义`MessageConverter` 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`,通过它可以使用跟自动配置实例相同的配置初始化`SimpleRabbitListenerContainerFactory`。 + +例如,下面使用一个特殊的`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) { + // ... + } + +} +``` +你可以启动重试处理那些监听器抛出异常的情况,当重试次数达到限制时,该消息将被拒绝,要不被丢弃,要不路由到一个dead-letter交换器,如果broker这样配置的话,默认禁用重试。 + +**重要** 如果没启用重试,且监听器抛出异常,则Rabbit会不定期进行重试。你可以采用两种方式修改该行为:设置`defaultRequeueRejected`属性为`false`,这样就不会重试;或抛出一个`AmqpRejectAndDontRequeueException`异常表示该消息应该被拒绝,这是开启重试,且达到最大重试次数时使用的策略。 diff --git a/IV. Spring Boot features/32.3. Using a Java EE managed transaction manager.md b/IV. Spring Boot features/32.3. Using a Java EE managed transaction manager.md deleted file mode 100644 index d6eba064..00000000 --- a/IV. Spring Boot features/32.3. Using a Java EE managed transaction manager.md +++ /dev/null @@ -1,3 +0,0 @@ -### 32.3. 使用一个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/32.5. Supporting an alternative embedded transaction manager.md b/IV. Spring Boot features/32.5. Supporting an alternative embedded transaction manager.md deleted file mode 100644 index f2752c2c..00000000 --- a/IV. Spring Boot features/32.5. Supporting an alternative embedded transaction manager.md +++ /dev/null @@ -1,3 +0,0 @@ -### 32.5. 支持可替代的内嵌事务管理器 - -[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,这样在分布式事务中可以透明使用。 diff --git a/IV. Spring Boot features/33. Calling REST services.md b/IV. Spring Boot features/33. Calling REST services.md new file mode 100644 index 00000000..c972aed1 --- /dev/null +++ b/IV. Spring Boot features/33. Calling REST services.md @@ -0,0 +1,21 @@ +###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. Spring Integration.md b/IV. Spring Boot features/33. Spring Integration.md deleted file mode 100644 index b8e3bfe2..00000000 --- a/IV. Spring Boot features/33. Spring Integration.md +++ /dev/null @@ -1,3 +0,0 @@ -### 33. Spring集成 - -Spring集成提供基于消息和其他协议的,比如HTTP,TCP等的抽象。如果Spring集成在classpath下可用,它将会通过@EnableIntegration注解被初始化。如果classpath下'spring-integration-jmx'可用,则消息处理统计分析将被通过JMX发布出去。具体参考[IntegrationAutoConfiguration类](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java)。 diff --git a/IV. Spring Boot features/33.1 RestTemplate customization.md b/IV. Spring Boot features/33.1 RestTemplate customization.md new file mode 100644 index 00000000..88c71a53 --- /dev/null +++ b/IV. Spring Boot features/33.1 RestTemplate customization.md @@ -0,0 +1,30 @@ +###33.1 自定义RestTemplate +当使用`RestTemplateBuilder`构建`RestTemplate`时,可以通过`RestTemplateCustomizer`进行更高级的定制,所有`RestTemplateCustomizer` beans将自动添加到自动配置的`RestTemplateBuilder`。此外,调用`additionalCustomizers(RestTemplateCustomizer…)`方法可以创建一个新的,具有其他customizers的`RestTemplateBuilder`。 + +以下示例演示使用自定义器(customizer)配置所有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/IV. Spring Boot features/34. Monitoring and management over JMX.md b/IV. Spring Boot features/34. Monitoring and management over JMX.md deleted file mode 100644 index 801a09b3..00000000 --- a/IV. Spring Boot features/34. Monitoring and management over JMX.md +++ /dev/null @@ -1,3 +0,0 @@ -### 34. 基于JMX的监控和管理 - -Java管理扩展(JMX)提供了一个标准的用于监控和管理应用的机制。默认情况下,Spring Boot将创建一个id为‘mbeanServer’的MBeanServer,并导出任何被Spring JMX注解(@ManagedResource,@ManagedAttribute,@ManagedOperation)的beans。具体参考[JmxAutoConfiguration类](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java)。 diff --git a/IV. Spring Boot features/34. Sending email.md b/IV. Spring Boot features/34. Sending email.md new file mode 100644 index 00000000..f1de1ccc --- /dev/null +++ b/IV. Spring Boot features/34. Sending email.md @@ -0,0 +1,5 @@ +### 34. 发送邮件 +Spring框架通过`JavaMailSender`接口为发送邮件提供了一个简单的抽象,并且Spring Boot也为它提供了自动配置和一个starter模块。 +具体查看[JavaMailSender参考文档](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#mail)。 + +如果`spring.mail.host`和相关的libraries(通过`spring-boot-starter-mail`定义的)都可用,Spring Boot将创建一个默认的`JavaMailSender`,该sender可以通过`spring.mail`命名空间下的配置项进一步自定义,具体参考[MailProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailProperties.java)。 diff --git a/IV. Spring Boot features/35. Distributed Transactions with JTA.md b/IV. Spring Boot features/35. Distributed Transactions with JTA.md new file mode 100644 index 00000000..711fc5fa --- /dev/null +++ b/IV. Spring Boot features/35. Distributed Transactions with JTA.md @@ -0,0 +1,5 @@ +### 35. 使用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/35. Testing.md b/IV. Spring Boot features/35. Testing.md deleted file mode 100644 index 855164c9..00000000 --- a/IV. Spring Boot features/35. Testing.md +++ /dev/null @@ -1,3 +0,0 @@ -### 35. 测试 - -Spring Boot提供很多有用的测试应用的工具。spring-boot-starter-test POM提供Spring Test,JUnit,Hamcrest和Mockito的依赖。在spring-boot核心模块org.springframework.boot.test包下也有很多有用的测试工具。 diff --git a/IV. Spring Boot features/35.1 Using an Atomikos transaction manager.md b/IV. Spring Boot features/35.1 Using an Atomikos transaction manager.md new file mode 100644 index 00000000..d8a3b4b3 --- /dev/null +++ b/IV. Spring Boot features/35.1 Using an Atomikos transaction manager.md @@ -0,0 +1,7 @@ +###35.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/1.4.1.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/35.1. Test scope dependencies.md b/IV. Spring Boot features/35.1. Test scope dependencies.md deleted file mode 100644 index 0c86528d..00000000 --- a/IV. Spring Boot features/35.1. Test scope dependencies.md +++ /dev/null @@ -1,9 +0,0 @@ -### 35.1. 测试作用域依赖 - -如果使用spring-boot-starter-test ‘Starter POM’(在test作用域内),你将发现下列被提供的库: -- Spring Test - 对Spring应用的集成测试支持 -- JUnit - 事实上的(de-facto)标准,用于Java应用的单元测试。 -- Hamcrest - 一个匹配对象的库(也称为约束或前置条件),它允许assertThat等JUnit类型的断言。 -- Mockito - 一个Java模拟框架。 - -这也有一些我们写测试用例时经常用到的库。如果它们不能满足你的要求,你可以随意添加其他的测试用的依赖库。 diff --git a/IV. Spring Boot features/35.2 Using a Bitronix transaction manager.md b/IV. Spring Boot features/35.2 Using a Bitronix transaction manager.md new file mode 100644 index 00000000..1ec70521 --- /dev/null +++ b/IV. Spring Boot features/35.2 Using a Bitronix transaction manager.md @@ -0,0 +1,7 @@ +###35.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/35.2. Testing Spring applications.md b/IV. Spring Boot features/35.2. Testing Spring applications.md deleted file mode 100644 index 1ab7f9b6..00000000 --- a/IV. Spring Boot features/35.2. Testing Spring applications.md +++ /dev/null @@ -1,9 +0,0 @@ -### 35.2. 测试Spring应用 - -依赖注入最大的优点就是它能够让你的代码更容易进行单元测试。你只需简单的通过new操作符实例化对象,而不需要涉及Spring。你也可以使用模拟对象替换真正的依赖。 - -你常常需要在进行单元测试后,开始集成测试(在这个过程中只需要涉及到Spring的ApplicationContext)。在执行集成测试时,不需要部署应用或连接到其他基础设施是非常有用的。 - -Spring框架包含一个dedicated测试模块,用于这样的集成测试。你可以直接声明对org.springframework:spring-test的依赖,或使用spring-boot-starter-test ‘Starter POM’以透明的方式拉取它。 - -如果你以前没有使用过spring-test模块,可以查看Spring框架参考文档中的[相关章节](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#testing)。 diff --git a/IV. Spring Boot features/35.3 Using a Narayana transaction manager.md b/IV. Spring Boot features/35.3 Using a Narayana transaction manager.md new file mode 100644 index 00000000..dadea4b8 --- /dev/null +++ b/IV. Spring Boot features/35.3 Using a Narayana transaction manager.md @@ -0,0 +1,6 @@ +###35.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/1.4.1.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/35.3. Testing Spring Boot applications.md b/IV. Spring Boot features/35.3. Testing Spring Boot applications.md deleted file mode 100644 index 011e0463..00000000 --- a/IV. Spring Boot features/35.3. Testing Spring Boot applications.md +++ /dev/null @@ -1,44 +0,0 @@ -### 35.3. 测试Spring Boot应用 - -一个Spring Boot应用只是一个Spring ApplicationContext,所以在测试它时除了正常情况下处理一个vanilla Spring context外不需要做其他特别事情。唯一需要注意的是,如果你使用SpringApplication创建上下文,外部配置,日志和Spring Boot的其他特性只会在默认的上下文中起作用。 - -Spring Boot提供一个@SpringApplicationConfiguration注解用来替换标准的spring-test @ContextConfiguration注解。如果使用@SpringApplicationConfiguration来设置你的测试中使用的ApplicationContext,它最终将通过SpringApplication创建,并且你将获取到Spring Boot的其他特性。 - -示例如下: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class) -public class CityRepositoryIntegrationTests { -@Autowired -CityRepository repository; -// ... -} -``` -**提示**:上下文加载器会通过查找@WebIntegrationTest或@WebAppConfiguration注解来猜测你想测试的是否是web应用(例如,是否使用MockMVC,MockMVC和@WebAppConfiguration是spring-test的一部分)。 - -如果想让一个web应用启动,并监听它的正常的端口,你可以使用HTTP来测试它(比如,使用RestTemplate),并使用@WebIntegrationTest注解你的测试类(或它的一个父类)。这很有用,因为它意味着你可以对你的应用进行全栈测试,但在一次HTTP交互后,你需要在你的测试类中注入相应的组件并使用它们断言应用的内部状态。 - -示例: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class) -@WebIntegrationTest -public class CityRepositoryIntegrationTests { -@Autowired -CityRepository repository; -RestTemplate restTemplate = new TestRestTemplate(); -// ... interact with the running server -} -``` -**注**:Spring测试框架在每次测试时会缓存应用上下文。因此,只要你的测试共享相同的配置,不管你实际运行多少测试,开启和停止服务器只会发生一次。 - -你可以为@WebIntegrationTest添加环境变量属性来改变应用服务器端口号,比如@WebIntegrationTest("server.port:9000")。此外,你可以将server.port和management.port属性设置为0来让你的集成测试使用随机的端口号,例如: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = MyApplication.class) -@WebIntegrationTest({"server.port=0", "management.port=0"}) -public class SomeIntegrationTests { -// ... -} -``` -可以查看[Section 64.4, “Discover the HTTP port at runtime”](../IX. ‘How-to’ guides/64.4. Discover the HTTP port at runtime.md),它描述了如何在测试期间发现分配的实际端口。 diff --git a/IV. Spring Boot features/35.3.1. Using Spock to test Spring Boot applications.md b/IV. Spring Boot features/35.3.1. Using Spock to test Spring Boot applications.md deleted file mode 100644 index dd11547a..00000000 --- a/IV. Spring Boot features/35.3.1. Using Spock to test Spring Boot applications.md +++ /dev/null @@ -1,12 +0,0 @@ -### 35.3.1. 使用Spock测试Spring Boot应用 - -如果期望使用Spock测试一个Spring Boot应用,你应该将Spock的spock-spring模块依赖添加到应用的构建中。spock-spring将Spring的测试框架集成到了Spock里。 - -注意你不能使用上述提到的@SpringApplicationConfiguration注解,因为[Spock找不到@ContextConfiguration元注解](https://code.google.com/p/spock/issues/detail?id=349)。为了绕过该限制,你应该直接使用@ContextConfiguration注解,并使用Spring Boot特定的上下文加载器来配置它。 -```java -@ContextConfiguration(loader = SpringApplicationContextLoader.class) -class ExampleSpec extends Specification { -// ... -} -``` -**注**:上面描述的注解在Spock中可以使用,比如,你可以使用@WebIntegrationTest注解你的Specification以满足测试需要。 diff --git a/IV. Spring Boot features/35.4 Using a Java EE managed transaction manager.md b/IV. Spring Boot features/35.4 Using a Java EE managed transaction manager.md new file mode 100644 index 00000000..a0ec0a24 --- /dev/null +++ b/IV. Spring Boot features/35.4 Using a Java EE managed transaction manager.md @@ -0,0 +1,3 @@ +###35.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/35.4. Test utilities.md b/IV. Spring Boot features/35.4. Test utilities.md deleted file mode 100644 index a6beb647..00000000 --- a/IV. Spring Boot features/35.4. Test utilities.md +++ /dev/null @@ -1,3 +0,0 @@ -### 35.4. 测试工具 - -打包进spring-boot的一些有用的测试工具类。 diff --git a/IV. Spring Boot features/35.4.1. ConfigFileApplicationContextInitializer.md b/IV. Spring Boot features/35.4.1. ConfigFileApplicationContextInitializer.md deleted file mode 100644 index e412ff9f..00000000 --- a/IV. Spring Boot features/35.4.1. ConfigFileApplicationContextInitializer.md +++ /dev/null @@ -1,8 +0,0 @@ -### 35.4.1. ConfigFileApplicationContextInitializer - -ConfigFileApplicationContextInitializer是一个ApplicationContextInitializer,可以用来测试加载Spring Boot的application.properties文件。当不需要使用@SpringApplicationConfiguration提供的全部特性时,你可以使用它。 - -```java -@ContextConfiguration(classes = Config.class,initializers = ConfigFileApplicationContextInitializer.class) -``` -   diff --git a/IV. Spring Boot features/35.4.2. EnvironmentTestUtils.md b/IV. Spring Boot features/35.4.2. EnvironmentTestUtils.md deleted file mode 100644 index 3e6f1979..00000000 --- a/IV. Spring Boot features/35.4.2. EnvironmentTestUtils.md +++ /dev/null @@ -1,5 +0,0 @@ -### 35.4.2. EnvironmentTestUtils - -EnvironmentTestUtils允许你快速添加属性到一个ConfigurableEnvironment或ConfigurableApplicationContext。只需简单的使用key=value字符串调用它: -```java -EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot"); diff --git a/IV. Spring Boot features/35.4.4. TestRestTemplate.md b/IV. Spring Boot features/35.4.4. TestRestTemplate.md deleted file mode 100644 index 6849f38c..00000000 --- a/IV. Spring Boot features/35.4.4. TestRestTemplate.md +++ /dev/null @@ -1,13 +0,0 @@ -### 35.4.4. TestRestTemplate - -TestRestTemplate是一个方便进行集成测试的Spring RestTemplate子类。你会获取到一个普通的模板或一个发送基本HTTP认证(使用用户名和密码)的模板。在任何情况下,这些模板都表现出对测试友好:不允许重定向(这样你可以对响应地址进行断言),忽略cookies(这样模板就是无状态的),对于服务端错误不会抛出异常。推荐使用Apache HTTP Client(4.3.2或更好的版本),但不强制这样做。如果在classpath下存在Apache HTTP Client,TestRestTemplate将以正确配置的client进行响应。 -```java -public class MyTest { -RestTemplate template = new TestRestTemplate(); -@Test -public void testRequest() throws Exception { -HttpHeaders headers = template.getForEntity("http://myhost.com", String.class).getHeaders(); -assertThat(headers.getLocation().toString(), containsString("myotherhost")); -} -} -``` diff --git a/IV. Spring Boot features/32.4. Mixing XA and non-XA JMS connections.md b/IV. Spring Boot features/35.5 Mixing XA and non-XA JMS connections.md similarity index 51% rename from IV. Spring Boot features/32.4. Mixing XA and non-XA JMS connections.md rename to IV. Spring Boot features/35.5 Mixing XA and non-XA JMS connections.md index 71e279bb..8ac99eaf 100644 --- a/IV. Spring Boot features/32.4. Mixing XA and non-XA JMS connections.md +++ b/IV. Spring Boot features/35.5 Mixing XA and non-XA JMS connections.md @@ -1,8 +1,8 @@ -### 32.4. 混合XA和non-XA的JMS连接 +###35.5 混合XA和non-XA的JMS连接 -当使用JTA时,主要的JMS ConnectionFactory bean将是XA aware,并参与到分布式事务中。有些情况下,你可能需要使用non-XA的ConnectionFactory去处理一些JMS消息。例如,你的JMS处理逻辑可能比XA超时时间长。 +当使用JTA时,primary JMS `ConnectionFactory`bean将能识别XA,并参与到分布式事务中。有些情况下,你可能需要使用non-XA的`ConnectionFactory`去处理一些JMS消息。例如,你的JMS处理逻辑可能比XA超时时间长。 -如果想使用一个non-XA的ConnectionFactory,你可以注入nonXaJmsConnectionFactory bean而不是@Primary jmsConnectionFactory bean。为了保持一致,jmsConnectionFactory bean将以别名xaJmsConnectionFactor来被使用。 +如果想使用一个non-XA的`ConnectionFactory`,你可以注入`nonXaJmsConnectionFactory` bean而不是`@Primary` `jmsConnectionFactory` bean。为了保持一致,`jmsConnectionFactory` bean将以别名`xaJmsConnectionFactor`来被使用。 示例如下: ```java diff --git a/IV. Spring Boot features/35.6 Supporting an alternative embedded transaction manager.md b/IV. Spring Boot features/35.6 Supporting an alternative embedded transaction manager.md new file mode 100644 index 00000000..91a23034 --- /dev/null +++ b/IV. Spring Boot features/35.6 Supporting an alternative embedded transaction manager.md @@ -0,0 +1,5 @@ +###35.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/v1.4.1.RELEASE/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapper.java)和[BitronixXADataSourceWrapper](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapper.java)提供很好的示例用于演示怎么编写XA包装器。 diff --git a/IV. Spring Boot features/36. Developing auto-configuration and using conditions.md b/IV. Spring Boot features/36. Developing auto-configuration and using conditions.md deleted file mode 100644 index 72185f05..00000000 --- a/IV. Spring Boot features/36. Developing auto-configuration and using conditions.md +++ /dev/null @@ -1,3 +0,0 @@ -### 36. 开发自动配置和使用条件 - -如果你在一个开发者共享库的公司工作,或你在从事一个开源或商业型的库,你可能想要开发自己的auto-configuration。Auto-configuration类能够在外部的jars中绑定,并仍能被Spring Boot发现。 diff --git a/IV. Spring Boot features/36. Hazelcast.md b/IV. Spring Boot features/36. Hazelcast.md new file mode 100644 index 00000000..ce992240 --- /dev/null +++ b/IV. Spring Boot features/36. Hazelcast.md @@ -0,0 +1,9 @@ +###36. Hazelcast +如果添加hazelcast依赖,Spring Boot将自动配置一个`HazelcastInstance`,你可以注入到应用中,`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/)。 + +**注** Spring Boot为Hazelcast提供了缓存支持,如果开启缓存的话,`HazelcastInstance`实例将自动包装进一个`CacheManager`实现中。 diff --git a/IV. Spring Boot features/36.1. Understanding auto-configured beans.md b/IV. Spring Boot features/36.1. Understanding auto-configured beans.md deleted file mode 100644 index 3667cfd0..00000000 --- a/IV. Spring Boot features/36.1. Understanding auto-configured beans.md +++ /dev/null @@ -1,5 +0,0 @@ -### 36.1. 理解auto-configured beans - -从底层来讲,auto-configured是使用标准的@Configuration实现的类,另外的@Conditional注解用来约束在什么情况下使用auto-configuration。通常auto-configuration类使用@ConditionalOnClass和@ConditionalOnMissingBean注解。这是为了确保只有在相关的类被发现,和你没有声明自己的@Configuration时才应用auto-configuration。 - -你可以浏览spring-boot-autoconfigure的源码,查看我们提供的@Configuration类(查看META-INF/spring.factories文件)。 diff --git a/IV. Spring Boot features/36.2. Locating auto-configuration candidates.md b/IV. Spring Boot features/36.2. Locating auto-configuration candidates.md deleted file mode 100644 index de9f16f4..00000000 --- a/IV. Spring Boot features/36.2. Locating auto-configuration candidates.md +++ /dev/null @@ -1,9 +0,0 @@ -### 36.2. 定位auto-configuration候选者 - -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后面。 diff --git a/IV. Spring Boot features/36.3. Condition annotations.md b/IV. Spring Boot features/36.3. Condition annotations.md deleted file mode 100644 index 7e257cd2..00000000 --- a/IV. Spring Boot features/36.3. Condition annotations.md +++ /dev/null @@ -1,5 +0,0 @@ -### 36.3. Condition注解 - -你几乎总是需要在你的auto-configuration类里添加一个或更多的@Condition注解。@ConditionalOnMissingBean注解是一个常见的示例,它经常用于允许开发者覆盖auto-configuration,如果他们不喜欢你提供的默认行为。 - -Spring Boot包含很多@Conditional注解,你可以在自己的代码中通过注解@Configuration类或单独的@Bean方法来重用它们。 diff --git a/IV. Spring Boot features/36.3.1. Class conditions.md b/IV. Spring Boot features/36.3.1. Class conditions.md deleted file mode 100644 index 8738e703..00000000 --- a/IV. Spring Boot features/36.3.1. Class conditions.md +++ /dev/null @@ -1,3 +0,0 @@ -### 36.3.1. Class条件 - -@ConditionalOnClass和@ConditionalOnMissingClass注解允许根据特定类是否出现来跳过配置。由于注解元数据是使用[ASM](http://asm.ow2.org/)来解析的,你实际上可以使用value属性来引用真正的类,即使该类可能实际上并没有出现在运行应用的classpath下。如果你倾向于使用一个String值来指定类名,你也可以使用name属性。 diff --git a/IV. Spring Boot features/36.3.2. Bean conditions.md b/IV. Spring Boot features/36.3.2. Bean conditions.md deleted file mode 100644 index 3e51982a..00000000 --- a/IV. Spring Boot features/36.3.2. Bean conditions.md +++ /dev/null @@ -1,5 +0,0 @@ -### 36.3.2. Bean条件 - -@ConditionalOnBean和@ConditionalOnMissingBean注解允许根据特定beans是否出现来跳过配置。你可以使用value属性来指定beans(by type),也可以使用name来指定beans(by name)。search属性允许你限制搜索beans时需要考虑的ApplicationContext的层次。 - -**注**:当@Configuration类被解析时@Conditional注解会被处理。Auto-configure @Configuration总是最后被解析(在所有用户定义beans后面),然而,如果你将那些注解用到常规的@Configuration类,需要注意不能引用那些还没有创建好的bean定义。 diff --git a/IV. Spring Boot features/36.3.3. Property conditions.md b/IV. Spring Boot features/36.3.3. Property conditions.md deleted file mode 100644 index 4193f5df..00000000 --- a/IV. Spring Boot features/36.3.3. Property conditions.md +++ /dev/null @@ -1,3 +0,0 @@ -### 36.3.3. Property条件 - -@ConditionalOnProperty注解允许根据一个Spring Environment属性来决定是否包含配置。可以使用prefix和name属性指定要检查的配置属性。默认情况下,任何存在的只要不是false的属性都会匹配。你也可以使用havingValue和matchIfMissing属性创建更高级的检测。 diff --git a/IV. Spring Boot features/36.3.4. Resource conditions.md b/IV. Spring Boot features/36.3.4. Resource conditions.md deleted file mode 100644 index 1b09cbf8..00000000 --- a/IV. Spring Boot features/36.3.4. Resource conditions.md +++ /dev/null @@ -1,3 +0,0 @@ -### 36.3.4. Resource条件 - -@ConditionalOnResource注解允许只有在特定资源出现时配置才会被包含。资源可以使用常见的Spring约定命名,例如file:/home/user/test.dat。 diff --git a/IV. Spring Boot features/36.3.5. Web Application Conditions.md b/IV. Spring Boot features/36.3.5. Web Application Conditions.md deleted file mode 100644 index 26775219..00000000 --- a/IV. Spring Boot features/36.3.5. Web Application Conditions.md +++ /dev/null @@ -1,3 +0,0 @@ -### 36.3.5. Web Application条件 - -@ConditionalOnWebApplication和@ConditionalOnNotWebApplication注解允许根据应用是否为一个'web应用'来决定是否包含配置。一个web应用是任何使用Spring WebApplicationContext,定义一个session作用域或有一个StandardServletEnvironment的应用。 diff --git a/IV. Spring Boot features/36.3.6. SpEL expression conditions.md b/IV. Spring Boot features/36.3.6. SpEL expression conditions.md deleted file mode 100644 index 28dd5a64..00000000 --- a/IV. Spring Boot features/36.3.6. SpEL expression conditions.md +++ /dev/null @@ -1,3 +0,0 @@ -### 36.3.6. SpEL表达式条件 - -@ConditionalOnExpression注解允许根据[SpEL表达式](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#expressions)结果来跳过配置。 diff --git a/IV. Spring Boot features/37. Spring Integration.md b/IV. Spring Boot features/37. Spring Integration.md new file mode 100644 index 00000000..ae2c35da --- /dev/null +++ b/IV. Spring Boot features/37. Spring Integration.md @@ -0,0 +1,3 @@ +###37. Spring集成 +Spring Boot为Spring集成提供了一些便利,包括`spring-boot-starter-integration` ‘Starter’。 +Spring集成提供基于消息和其他传输协议的抽象,比如HTTP,TCP等。如果添加Spring集成依赖,使用`@EnableIntegration`注解可以初始化它。如果classpath下存在'spring-integration-jmx'依赖,则消息处理统计分析将被通过JMX发布出去,具体参考[IntegrationAutoConfiguration类](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java)。 diff --git a/IV. Spring Boot features/37. WebSockets.md b/IV. Spring Boot features/37. WebSockets.md deleted file mode 100644 index 594d14fe..00000000 --- a/IV. Spring Boot features/37. WebSockets.md +++ /dev/null @@ -1,5 +0,0 @@ -### 37. WebSockets - -Spring Boot为内嵌的Tomcat(8和7),Jetty 9和Undertow提供WebSockets自动配置。如果你正在将一个war包部署到一个单独的容器,Spring Boot会假设该容器会对它的WebSocket支持相关的配置负责。 - -Spring框架提供[丰富的WebSocket支持](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#websocket),通过spring-boot-starter-websocket模块可以轻易获取到。 diff --git a/IV. Spring Boot features/38. Spring Session.md b/IV. Spring Boot features/38. Spring Session.md new file mode 100644 index 00000000..c639d08e --- /dev/null +++ b/IV. Spring Boot features/38. Spring Session.md @@ -0,0 +1,21 @@ +###38. Spring Session +Spring Boot为Spring Session自动配置了各种存储: + +* JDBC +* MongoDB +* Redis +* Hazelcast +* HashMap + +如果Spring Session可用,你只需选择想要的存储sessions的存储类型[StoreType](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/StoreType.java)。例如,按如下配置将使用JDBC作为后端存储: +```properties +spring.session.store-type=jdbc +``` +**注** 出于向后兼容,如果Redis可用,Spring Session将自动配置使用Redis存储。 + +**注** 设置`store-type`为`none`可以禁用Spring Session。 + +每个存储都有特殊设置,例如,对于jdbc存储可自定义表名: +```properties +spring.session.jdbc.table-name=SESSIONS +``` diff --git a/IV. Spring Boot features/38. What to read next.md b/IV. Spring Boot features/38. What to read next.md deleted file mode 100644 index 1168b863..00000000 --- a/IV. Spring Boot features/38. What to read next.md +++ /dev/null @@ -1 +0,0 @@ -### 38. 接下来阅读什么 diff --git a/IV. Spring Boot features/39. Monitoring and management over JMX.md b/IV. Spring Boot features/39. Monitoring and management over JMX.md new file mode 100644 index 00000000..d529c3e8 --- /dev/null +++ b/IV. Spring Boot features/39. Monitoring and management over JMX.md @@ -0,0 +1,3 @@ +###39. 基于JMX的监控和管理 + +Java管理扩展(JMX)提供了一个标准的用于监控和管理应用的机制。默认情况下,Spring Boot将创建一个id为‘mbeanServer’的`MBeanServer`,并导出任何被Spring JMX注解(`@ManagedResource`,`@ManagedAttribute`,`@ManagedOperation`)的beans,具体参考[JmxAutoConfiguration类](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java)。 diff --git a/IV. Spring Boot features/40. Testing.md b/IV. Spring Boot features/40. Testing.md new file mode 100644 index 00000000..601e1f09 --- /dev/null +++ b/IV. Spring Boot features/40. Testing.md @@ -0,0 +1,5 @@ +###40. 测试 + +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/40.1 Test scope dependencies.md b/IV. Spring Boot features/40.1 Test scope dependencies.md new file mode 100644 index 00000000..41db549c --- /dev/null +++ b/IV. Spring Boot features/40.1 Test scope dependencies.md @@ -0,0 +1,13 @@ +###40.1 测试作用域依赖 + +如果使用`spring-boot-starter-test` ‘Starter’(在`test``scope`内),你将发现下列被提供的库: + +- [JUnit](http://junit.org/) - 事实上的(de-facto)标准,用于Java应用的单元测试。 +- [Spring Test](http://docs.spring.io/spring/docs/4.3.3.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/40.2 Testing Spring applications.md b/IV. Spring Boot features/40.2 Testing Spring applications.md new file mode 100644 index 00000000..f45420bd --- /dev/null +++ b/IV. Spring Boot features/40.2 Testing Spring applications.md @@ -0,0 +1,7 @@ +###40.2 测试Spring应用 + +依赖注入主要优势之一就是它能够让你的代码更容易进行单元测试。你只需简单的通过`new`操作符实例化对象,甚至不需要涉及Spring,也可以使用模拟对象替换真正的依赖。 + +你常常需要在进行单元测试后,开始集成测试(在这个过程中只需要涉及到Spring的`ApplicationContext`)。在执行集成测试时,不需要部署应用或连接到其他基础设施是非常有用的,Spring框架为实现这样的集成测试提供了一个专用的测试模块,通过声明`org.springframework:spring-test`的依赖,或使用`spring-boot-starter-test` ‘Starter’就可以使用它了。 + +如果以前没有使用过`spring-test`模块,可以查看Spring框架参考文档中的[相关章节](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#testing)。 diff --git a/IV. Spring Boot features/40.3 Testing Spring Boot applications.md b/IV. Spring Boot features/40.3 Testing Spring Boot applications.md new file mode 100644 index 00000000..648f0ac5 --- /dev/null +++ b/IV. Spring Boot features/40.3 Testing Spring Boot applications.md @@ -0,0 +1,17 @@ +###40.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`。 + +* `RANDOM_PORT` - 加载`EmbeddedWebApplicationContext`,并提供一个真实的servlet环境。使用该模式内嵌容器将启动,并监听在一个随机端口。 + +* `DEFINED_PORT` - 加载`EmbeddedWebApplicationContext`,并提供一个真实的servlet环境。使用该模式内嵌容器将启动,并监听一个定义好的端口(比如`application.properties`中定义的或默认的`8080`端口)。 + +* `NONE` - 使用`SpringApplication`加载一个`ApplicationContext`,但不提供任何servlet环境(不管是mock还是其他)。 + +**注** 不要忘记在测试用例上添加`@RunWith(SpringRunner.class)`,否则该注解将被忽略。 diff --git a/IV. Spring Boot features/40.3.1 Detecting test configuration.md b/IV. Spring Boot features/40.3.1 Detecting test configuration.md new file mode 100644 index 00000000..7543b4ea --- /dev/null +++ b/IV. Spring Boot features/40.3.1 Detecting test configuration.md @@ -0,0 +1,8 @@ +###40.3.1 发现测试配置 +如果熟悉Spring测试框架,你可能经常通过`@ContextConfiguration(classes=…)`指定加载哪些Spring `@Configuration`,也可能经常在测试类中使用内嵌`@Configuration`类。当测试Spring Boot应用时这些就不需要了,Spring Boot的`@*Test`注解会自动搜索主配置类,即使你没有显式定义它。 + +搜索算法是从包含测试类的package开始搜索,直到发现`@SpringBootApplication`或`@SpringBootConfiguration`注解的类,只要按[恰当的方式组织代码](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#using-boot-structuring-your-code),通常都会发现主配置类。 + +如果想自定义主配置类,你可以使用一个内嵌的`@TestConfiguration`类。不像内嵌的`@Configuration`类(会替换应用主配置类),内嵌的`@TestConfiguration`类是可以跟应用主配置类一块使用的。 + +**注** Spring测试框架在测试过程中会缓存应用上下文,因此,只要你的测试共享相同的配置(不管是怎么发现的),加载上下文的潜在时间消耗都只会发生一次。 diff --git a/IV. Spring Boot features/40.3.10 Auto-configured Spring REST Docs tests.md b/IV. Spring Boot features/40.3.10 Auto-configured Spring REST Docs tests.md new file mode 100644 index 00000000..2089f390 --- /dev/null +++ b/IV. Spring Boot features/40.3.10 Auto-configured Spring REST Docs tests.md @@ -0,0 +1,58 @@ +###40.3.10 自动配置的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("target/generated-snippets") +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`也能配置将出现在任何文档化的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/40.3.11 Using Spock to test Spring Boot applications.md b/IV. Spring Boot features/40.3.11 Using Spock to test Spring Boot applications.md new file mode 100644 index 00000000..17528299 --- /dev/null +++ b/IV. Spring Boot features/40.3.11 Using Spock to test Spring Boot applications.md @@ -0,0 +1,27 @@ +###40.3.11 使用Spock测试Spring Boot应用 + +如果想使用Spock测试Spring Boot应用,你需要为应用添加Spock的`spock-spring`依赖,该依赖已将Spring测试框架集成进Spock,怎么使用Spock测试Spring Boot应用取决于你使用的Spock版本。 + +**注** Spring Boot为Spock 1.0提供依赖管理,如果希望使用Spock 1.1,你需要覆盖`build.gradle`或`pom.xml`文件中的`spock.version`属性。 + +当使用Spock 1.1时,只能使用[上述注解](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications),你可以使用`@SpringBootTest`注解你的`Specification`以满足测试需求。 + +当使用Spock 1.0时,`@SpringBootTest`将不能用于web项目,你需要使用`@SpringApplicationConfiguration`和`@WebIntegrationTest(randomPort = true)`。 +不能使用`@SpringBootTest`也就意味着你失去了自动配置的`TestRestTemplate` bean,不过可以通过以下配置创建一个等价的bean: +```java +@Configuration +static class TestRestTemplateConfiguration { + + @Bean + public TestRestTemplate testRestTemplate( + ObjectProvider builderProvider, + Environment environment) { + RestTemplateBuilder builder = builderProvider.getIfAvailable(); + TestRestTemplate template = builder == null ? new TestRestTemplate() + : new TestRestTemplate(builder.build()); + template.setUriTemplateHandler(new LocalHostUriTemplateHandler(environment)); + return template; + } + +} +``` diff --git a/IV. Spring Boot features/40.3.2 Excluding test configuration.md b/IV. Spring Boot features/40.3.2 Excluding test configuration.md new file mode 100644 index 00000000..2fb1bbc4 --- /dev/null +++ b/IV. Spring Boot features/40.3.2 Excluding test configuration.md @@ -0,0 +1,6 @@ +###40.3.2 排除测试配置 +如果应用使用组件扫描,比如`@SpringBootApplication`或`@ComponentScan`,你可能发现为测试类创建的组件或配置在任何地方都可能偶然扫描到。为了防止这种情况,Spring Boot提供了`@TestComponent`和`@TestConfiguration`注解,可用在`src/test/java`目录下的类,以暗示它们不应该被扫描。 + +**注** 只有上层类需要`@TestComponent`和`@TestConfiguration`注解,如果你在测试类(任何有`@Test`方法或`@RunWith`注解的类)中定义`@Configuration`或`@Component`内部类,它们将被自动过滤。 + +**注** 如果直接使用`@ComponentScan`(比如不通过`@SpringBootApplication`),你需要为它注册`TypeExcludeFilter`,具体参考[Javadoc](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/api/org/springframework/boot/context/TypeExcludeFilter.html)。 diff --git a/IV. Spring Boot features/40.3.3 Working with random ports.md b/IV. Spring Boot features/40.3.3 Working with random ports.md new file mode 100644 index 00000000..49104ade --- /dev/null +++ b/IV. Spring Boot features/40.3.3 Working with random ports.md @@ -0,0 +1,28 @@ +###40.3.3 使用随机端口 +如果你需要为测试启动一个完整运行的服务器,我们建议你使用随机端口。如果你使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`,每次运行测试都会为你分配一个可用的随机端口。 + +`@LocalServerPort`注解用于[注入测试用例实际使用的端口](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto-discover-the-http-port-at-runtime),简单起见,需要发起REST调用到启动服务器的测试可以额外`@Autowire`一个`TestRestTemplate`,它可以解析到运行服务器的相关链接: +```java +import org.junit.*; +import org.junit.runner.*; +import org.springframework.boot.test.context.web.*; +import org.springframework.boot.test.web.client.*; +import org.springframework.test.context.junit4.*; + +import static org.assertj.core.api.Assertions.* + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) +public class MyWebIntegrationTests { + + @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/40.3.4 Mocking and spying beans.md b/IV. Spring Boot features/40.3.4 Mocking and spying beans.md new file mode 100644 index 00000000..b62fdfb1 --- /dev/null +++ b/IV. Spring Boot features/40.3.4 Mocking and spying beans.md @@ -0,0 +1,38 @@ +###40.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/40.3.5 Auto-configured tests.md b/IV. Spring Boot features/40.3.5 Auto-configured tests.md new file mode 100644 index 00000000..2e767eb5 --- /dev/null +++ b/IV. Spring Boot features/40.3.5 Auto-configured tests.md @@ -0,0 +1,6 @@ +###40.3.5 自动配置测试 +Spring Boot的自动配置系统对应用来说很合适,但用于测试就有点杀鸡用牛刀了,测试时只加载需要的应用片段(slice)通常是有好处的。例如,你可能想测试Spring MVC控制器映射URLs是否正确,且不想在这些测试中涉及到数据库调用;或者你想测试JPA实体,那测试运行时你可能对web层不感兴趣。 + +`spring-boot-test-autoconfigure`模块包含很多用来自动配置这些片段(slices)的注解,每个工作方式都相似,都是提供一个`@…Test`注解,然后加载`ApplicationContext`,使用一个或多个`@AutoConfigure…`注解自定义设置。 + +**注** `@AutoConfigure…`注解也可以跟标准的`@SpringBootTest`注解一块使用,如果对应用片段不感兴趣,只是想获取自动配置的一些测试beans,你可以使用该组合。 diff --git a/IV. Spring Boot features/40.3.6 Auto-configured JSON tests.md b/IV. Spring Boot features/40.3.6 Auto-configured JSON tests.md new file mode 100644 index 00000000..95560b80 --- /dev/null +++ b/IV. Spring Boot features/40.3.6 Auto-configured JSON tests.md @@ -0,0 +1,46 @@ +###40.3.6 自动配置的JSON测试 +你可以使用`@JsonTest`测试对象JSON序列化和反序列化是否工作正常,该注解将自动配置Jackson `ObjectMapper`,`@JsonComponent`和Jackson `Modules`。如果碰巧使用gson代替Jackson,该注解将配置`Gson`。使用`@AutoConfigureJsonTesters`可以配置auto-configuration的元素。 + +Spring Boot提供基于AssertJ的帮助类(helpers),可用来配合JSONassert和JsonPath libraries检测JSON是否为期望的,`JacksonHelper`,`GsonHelper`,`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/1.4.1.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@JsonTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/40.3.7 Auto-configured Spring MVC tests.md b/IV. Spring Boot features/40.3.7 Auto-configured Spring MVC tests.md new file mode 100644 index 00000000..33251f1b --- /dev/null +++ b/IV. Spring Boot features/40.3.7 Auto-configured Spring MVC tests.md @@ -0,0 +1,74 @@ +###40.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"); + } + +} +``` +在[附录](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@WebMvcTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/40.3.8 Auto-configured Data JPA tests.md b/IV. Spring Boot features/40.3.8 Auto-configured Data JPA tests.md new file mode 100644 index 00000000..6e72a47e --- /dev/null +++ b/IV. Spring Boot features/40.3.8 Auto-configured Data JPA tests.md @@ -0,0 +1,59 @@ +###40.3.8 自动配置的Data JPA测试 +你可以使用`@DataJpaTest`测试JPA应用,它默认配置一个内存型的内嵌数据库,扫描`@Entity`类,并配置Spring Data JPA仓库,其他常规的`@Component` beans不会加载进`ApplicationContext`。 + +Data JPA测试类是事务型的,默认在每个测试结束后回滚,具体查看Spring参考文档的[相关章节](http://docs.spring.io/spring/docs/4.3.3.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/v1.4.1.RELEASE/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 { + + // ... + +} +``` +在[附录](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@DataJpaTest`开启的自动配置列表。 diff --git a/IV. Spring Boot features/40.3.9 Auto-configured REST clients.md b/IV. Spring Boot features/40.3.9 Auto-configured REST clients.md new file mode 100644 index 00000000..51808426 --- /dev/null +++ b/IV. Spring Boot features/40.3.9 Auto-configured REST clients.md @@ -0,0 +1,25 @@ +###40.3.9 自动配置的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/1.4.1.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@RestClientTest`启用的自动配置列表。 diff --git a/IV. Spring Boot features/40.4 Test utilities.md b/IV. Spring Boot features/40.4 Test utilities.md new file mode 100644 index 00000000..f8cc29df --- /dev/null +++ b/IV. Spring Boot features/40.4 Test utilities.md @@ -0,0 +1,2 @@ +### 40.4 测试工具类 +一些测试工具类也打包进了`spring-boot`,在测试时使用它们会有很大帮助。 diff --git a/IV. Spring Boot features/40.4.1 ConfigFileApplicationContextInitializer.md b/IV. Spring Boot features/40.4.1 ConfigFileApplicationContextInitializer.md new file mode 100644 index 00000000..81052d5e --- /dev/null +++ b/IV. Spring Boot features/40.4.1 ConfigFileApplicationContextInitializer.md @@ -0,0 +1,8 @@ +###40.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/40.4.2 EnvironmentTestUtils.md b/IV. Spring Boot features/40.4.2 EnvironmentTestUtils.md new file mode 100644 index 00000000..6433367e --- /dev/null +++ b/IV. Spring Boot features/40.4.2 EnvironmentTestUtils.md @@ -0,0 +1,4 @@ +###40.4.2 EnvironmentTestUtils +使用简单的`key=value`字符串调用`EnvironmentTestUtils`就可以快速添加属性到`ConfigurableEnvironment`或`ConfigurableApplicationContext`: +```java +EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot"); diff --git a/IV. Spring Boot features/35.4.3. OutputCapture.md b/IV. Spring Boot features/40.4.3 OutputCapture.md similarity index 65% rename from IV. Spring Boot features/35.4.3. OutputCapture.md rename to IV. Spring Boot features/40.4.3 OutputCapture.md index 48887519..04544738 100644 --- a/IV. Spring Boot features/35.4.3. OutputCapture.md +++ b/IV. Spring Boot features/40.4.3 OutputCapture.md @@ -1,6 +1,6 @@ -### 35.4.3. OutputCapture +###40.4.3 OutputCapture -OutputCapture是一个JUnit Rule,用于捕获System.out和System.err输出。只需简单的将捕获声明为一个@Rule,并使用toString()断言: +`OutputCapture`是JUnit的一个`Rule`,用于捕获`System.out`和`System.err`输出,只需简单的将`@Rule`注解capture,然后在断言中调用`toString()`: ```java import org.junit.Rule; import org.junit.Test; diff --git a/IV. Spring Boot features/40.4.4 TestRestTemplate.md b/IV. Spring Boot features/40.4.4 TestRestTemplate.md new file mode 100644 index 00000000..2225cf06 --- /dev/null +++ b/IV. Spring Boot features/40.4.4 TestRestTemplate.md @@ -0,0 +1,42 @@ +###40.4.4 TestRestTemplate +在集成测试中,`TestRestTemplate`是Spring `RestTemplate`的便利替代。你可以获取一个普通的或发送基本HTTP认证(使用用户名和密码)的模板,不管哪种情况, +这些模板都有益于测试:不允许重定向(这样你可以对响应地址进行断言),忽略cookies(这样模板就是无状态的),对于服务端错误不会抛出异常。推荐使用Apache HTTP Client(4.3.2或更高版本),但不强制这样做,如果相关库在classpath下存在,`TestRestTemplate`将以正确配置的client进行响应。 +```java +public class MyTest { +RestTemplate template = new TestRestTemplate(); +@Test +public void testRequest() throws Exception { +HttpHeaders headers = template.getForEntity("http://myhost.com", String.class).getHeaders(); +assertThat(headers.getLocation().toString(), containsString("myotherhost")); +} +} +``` +如果正在使用`@SpringBootTest`,且设置了`WebEnvironment.RANDOM_PORT`或`WebEnvironment.DEFINED_PORT`属性,你可以注入一个配置完全的`TestRestTemplate`,并开始使用它。如果有需要,你还可以通过`RestTemplateBuilder` bean进行额外的自定义: +```java +@RunWith(SpringRunner.class) +@SpringBootTest +public class MyTest { + + @Autowired + private TestRestTemplate template; + + @Test + public void testRequest() throws Exception { + HttpHeaders headers = template.getForEntity("http://myhost.com", 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/41. WebSockets.md b/IV. Spring Boot features/41. WebSockets.md new file mode 100644 index 00000000..b2b6553d --- /dev/null +++ b/IV. Spring Boot features/41. WebSockets.md @@ -0,0 +1,2 @@ +### 41. WebSockets +Spring Boot为内嵌的Tomcat(8和7),Jetty 9和Undertow提供WebSockets自动配置。如果你正在将war包部署到独立容器中,Spring Boot将假设该容器会负责配置WebSocket。Spring框架提供[丰富的WebSocket支持](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#websocket),只需要添加`spring-boot-starter-websocket`模块即可。 diff --git a/IV. Spring Boot features/42. Web Services.md b/IV. Spring Boot features/42. Web Services.md new file mode 100644 index 00000000..621d4a00 --- /dev/null +++ b/IV. Spring Boot features/42. Web Services.md @@ -0,0 +1,2 @@ +###42. 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/43. Creating your own auto-configuration.md b/IV. Spring Boot features/43. Creating your own auto-configuration.md new file mode 100644 index 00000000..6f349769 --- /dev/null +++ b/IV. Spring Boot features/43. Creating your own auto-configuration.md @@ -0,0 +1,4 @@ +###43. 创建自己的auto-configuration +如果你在公司里开发共享libraries,或者正在开发一个开源或商业library,你可能想开发自己的自动配置(auto-configuration)。自动配置类可以打包到外部jars,并且依旧可以被Spring Boot识别。自动配置可以关联一个"starter",用于提供auto-configuration的代码及需要引用的libraries。我们首先讲解构建自己的auto-configuration需要知道哪些内容,然后讲解[创建自定义starter的常见步骤](http://docs.spring.io/spring-boot/docs/1.4.1.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/43.1 Understanding auto-configured beans.md b/IV. Spring Boot features/43.1 Understanding auto-configured beans.md new file mode 100644 index 00000000..b09d4a62 --- /dev/null +++ b/IV. Spring Boot features/43.1 Understanding auto-configured beans.md @@ -0,0 +1,2 @@ +###43.1 理解自动配置的beans +从底层来讲,自动配置(auto-configuration)是通过标准的`@Configuration`类实现的。此外,`@Conditional`注解用来约束自动配置生效的条件。通常自动配置类需要使用`@ConditionalOnClass`和`@ConditionalOnMissingBean`注解,这是为了确保只有在相关的类被发现及没有声明自定义的`@Configuration`时才应用自动配置,具体查看[`spring-boot-autoconfigure`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure)源码中的`@Configuration`类(`META-INF/spring.factories`文件)。 diff --git a/IV. Spring Boot features/43.2 Locating auto-configuration candidates.md b/IV. Spring Boot features/43.2 Locating auto-configuration candidates.md new file mode 100644 index 00000000..daf5fca0 --- /dev/null +++ b/IV. Spring Boot features/43.2 Locating auto-configuration candidates.md @@ -0,0 +1,12 @@ +###43.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/43.3 Condition annotations.md b/IV. Spring Boot features/43.3 Condition annotations.md new file mode 100644 index 00000000..3a9dbe49 --- /dev/null +++ b/IV. Spring Boot features/43.3 Condition annotations.md @@ -0,0 +1,4 @@ +###43.3 条件注解 +你几乎总是需要在自己的自动配置类里添加一个或更多的`@Conditional`注解。`@ConditionalOnMissingBean`注解是一个常见的示例,开发者可以用它覆盖自动配置类提供的默认行为。 + +Spring Boot包含很多`@Conditional`注解,你可以在自己的代码中通过注解`@Configuration`类或单独的`@Bean`方法来重用它们。 diff --git a/IV. Spring Boot features/43.3.1 Class conditions.md b/IV. Spring Boot features/43.3.1 Class conditions.md new file mode 100644 index 00000000..c85522a2 --- /dev/null +++ b/IV. Spring Boot features/43.3.1 Class conditions.md @@ -0,0 +1,2 @@ +###43.3.1 Class条件 +`@ConditionalOnClass`和`@ConditionalOnMissingClass`注解可以根据特定类是否出现来决定配置的包含,由于注解元数据是使用[ASM](http://asm.ow2.org/)来解析的,所以你可以使用`value`属性来引用真正的类,即使该类没有出现在运行应用的classpath下,也可以使用`name`属性如果你倾向于使用字符串作为类名。 diff --git a/IV. Spring Boot features/43.3.2 Bean conditions.md b/IV. Spring Boot features/43.3.2 Bean conditions.md new file mode 100644 index 00000000..6ee2e0b7 --- /dev/null +++ b/IV. Spring Boot features/43.3.2 Bean conditions.md @@ -0,0 +1,6 @@ +###43.3.2 Bean条件 +`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解可以根据特定类是否存在决定bean的包含,你可以使用`value`属性指定beans(by type),也可以使用`name`定义beans(by name),`search`属性用于限制搜索beans时需要考虑的`ApplicationContext`层次。 + +**注** 你需要注意bean定义添加的顺序,因为这些条件的计算是基于目前处理内容的。出于这个原因,我们推荐在自动配置类上只使用`@ConditionalOnBean`和`@ConditionalOnMissingBean`注解(即使保证它们在其他用户定义的beans后加载)。 + +**注** `@ConditionalOnBean`和`@ConditionalOnMissingBean`不会阻止`@Configuration`类的创建,在类级别使用那些conditions跟使用注解标记每个`@Bean`方法是等价的。 diff --git a/IV. Spring Boot features/43.3.3 Property conditions.md b/IV. Spring Boot features/43.3.3 Property conditions.md new file mode 100644 index 00000000..93fca0e7 --- /dev/null +++ b/IV. Spring Boot features/43.3.3 Property conditions.md @@ -0,0 +1,2 @@ +###43.3.3 Property条件 +`@ConditionalOnProperty`注解可以根据一个Spring `Environment`属性来决定是否包含配置,使用`prefix`和`name`属性指定要检查的配置。默认情况下,任何存在的只要不是`false`的属性都会匹配,你也可以使用`havingValue`和`matchIfMissing`属性创建更高级的检测。 diff --git a/IV. Spring Boot features/43.3.4 Resource conditions.md b/IV. Spring Boot features/43.3.4 Resource conditions.md new file mode 100644 index 00000000..6c08ffb9 --- /dev/null +++ b/IV. Spring Boot features/43.3.4 Resource conditions.md @@ -0,0 +1,2 @@ +###43.3.4 Resource条件 +`@ConditionalOnResource`注解只在特定资源出现时才会包含配置,可以使用常见的Spring约定命名资源,例如`file:/home/user/test.dat`。 diff --git a/IV. Spring Boot features/43.3.5 Web Application Conditions.md b/IV. Spring Boot features/43.3.5 Web Application Conditions.md new file mode 100644 index 00000000..7275ab4c --- /dev/null +++ b/IV. Spring Boot features/43.3.5 Web Application Conditions.md @@ -0,0 +1,2 @@ +###43.3.5 Web Application条件 +`@ConditionalOnWebApplication`和`@ConditionalOnNotWebApplication`注解可以根据应用是否为'web应用'来决定是否包含配置,web应用是任何使用Spring `WebApplicationContext`,定义一个`session`作用域,或有一个`StandardServletEnvironment`的应用。 diff --git a/IV. Spring Boot features/43.3.6 SpEL expression conditions.md b/IV. Spring Boot features/43.3.6 SpEL expression conditions.md new file mode 100644 index 00000000..3115d804 --- /dev/null +++ b/IV. Spring Boot features/43.3.6 SpEL expression conditions.md @@ -0,0 +1,2 @@ +###43.3.6 SpEL表达式条件 +`@ConditionalOnExpression`注解可以根据[SpEL表达式](http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#expressions)结果来决定是否包含配置。 diff --git a/IV. Spring Boot features/43.4 Creating your own starter.md b/IV. Spring Boot features/43.4 Creating your own starter.md new file mode 100644 index 00000000..5ff60c4c --- /dev/null +++ b/IV. Spring Boot features/43.4 Creating your own starter.md @@ -0,0 +1,7 @@ +###43.4 创建自己的starter +一个完整的Spring Boot starter可能包含以下组件: + +* `autoconfigure`模块,包含自动配置类的代码。 +* `starter`模块,提供自动配置模块及其他有用的依赖,简而言之,添加本starter就能开始使用该library。 + +**注** 如果不需要将它们分离开来,你可以将自动配置代码和依赖管理放到一个单一模块中。 diff --git a/IV. Spring Boot features/43.4.1 Naming.md b/IV. Spring Boot features/43.4.1 Naming.md new file mode 100644 index 00000000..4001ecb5 --- /dev/null +++ b/IV. Spring Boot features/43.4.1 Naming.md @@ -0,0 +1,8 @@ +###43.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/1.4.1.RELEASE/reference/htmlsingle/#configuration-metadata-annotation-processor),这样IDE辅助也就可以用于你的keys了,你可能想检查生成的元数据(`META-INF/spring-configuration-metadata.json`)以确保keys被正确的文档化。 diff --git a/IV. Spring Boot features/43.4.2 Autoconfigure module.md b/IV. Spring Boot features/43.4.2 Autoconfigure module.md new file mode 100644 index 00000000..b91e4182 --- /dev/null +++ b/IV. Spring Boot features/43.4.2 Autoconfigure module.md @@ -0,0 +1,4 @@ +###43.4.2 自动配置模块 +自动配置模块包含了使用该library需要的任何东西,它可能还包含配置的keys定义(`@ConfigurationProperties`)和用于定义组件如何初始化的回调接口。 + +**注** 你需要将对该library的依赖标记为可选的,这样在项目中添加该自动配置模块就更容易了。如果你这样做,该library将不会提供,Spring Boot会回退到默认设置。 diff --git a/IV. Spring Boot features/43.4.3 Starter module.md b/IV. Spring Boot features/43.4.3 Starter module.md new file mode 100644 index 00000000..3a39e367 --- /dev/null +++ b/IV. Spring Boot features/43.4.3 Starter module.md @@ -0,0 +1,2 @@ +###43.4.3 Starter模块 +starter模块实际是一个空jar,它的目的是提供使用该library所需的必要依赖。不要对添加你的starter的项目做任何假设,如果你正在自动配置的library需要其他starters,一定要提到它。提供一个合适的默认依赖集可能比较困难,特别是存在大量可选依赖时,你应该避免引入任何非必需的依赖。 diff --git a/IV. Spring Boot features/44. What to read next.md b/IV. Spring Boot features/44. What to read next.md new file mode 100644 index 00000000..b0da2f90 --- /dev/null +++ b/IV. Spring Boot features/44. What to read next.md @@ -0,0 +1,4 @@ +### 44. 接下来阅读什么 +如果想了解本章节讨论类的更多内容,你可以查看[Spring Boot API文档](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/api),或直接浏览[源码](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE)。如果有特别问题,可以参考[how-to](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto)章节。 + +如果已熟悉Spring Boot的核心特性,你可以继续并查看[production-ready特性](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#production-ready)。 diff --git a/IV. Spring Boot features/README.md b/IV. Spring Boot features/README.md index 093c9d3e..14158194 100644 --- a/IV. Spring Boot features/README.md +++ b/IV. Spring Boot features/README.md @@ -1 +1,3 @@ ### Spring Boot特性 + +本章节将深入详细的介绍Spring Boot,通过阅读本节你可以了解到需要使用和定制的核心特性。如果没做好准备,你可以先阅读[Part II. Getting started](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#getting-started)和[Part III, “Using Spring Boot” ](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#using-boot)章节,以对Spring Boot有个良好的基本认识。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/62. Spring Boot application.md" "b/IX. \342\200\230How-to\342\200\231 guides/62. Spring Boot application.md" deleted file mode 100644 index 8018dbbd..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/62. Spring Boot application.md" +++ /dev/null @@ -1 +0,0 @@ -### 62. Spring Boot应用 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/62.1. Troubleshoot auto-configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/62.1. Troubleshoot auto-configuration.md" deleted file mode 100644 index 44079136..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/62.1. Troubleshoot auto-configuration.md" +++ /dev/null @@ -1,15 +0,0 @@ -### 62.1. 解决自动配置问题 - -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端点。 -* 查看使用RelaxedEnvironment明确地将配置从Environment暴露出去。它经常会使用一个前缀。 -* 查看`@Value`注解,它直接绑定到Environment。相比RelaxedEnvironment,这种方式稍微缺乏灵活性,但它也允许松散的绑定,特别是OS环境变量(所以`CAPITALS_AND_UNDERSCORES`是`period.separated`的同义词)。 -* 查看`@ConditionalOnExpression`注解,它根据SpEL表达式的结果来开启或关闭特性,通常使用解析自Environment的占位符进行计算。 - diff --git "a/IX. \342\200\230How-to\342\200\231 guides/62.2. Customize the Environment or ApplicationContext before it starts.md" "b/IX. \342\200\230How-to\342\200\231 guides/62.2. Customize the Environment or ApplicationContext before it starts.md" deleted file mode 100644 index 0c88c8ed..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/62.2. Customize the Environment or ApplicationContext before it starts.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 62.2. 启动前自定义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 22.4, “Application events and listeners” ](../IV. Spring Boot features/22.4. Application events and listeners.md)可以获取一个完整列表。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/62.3. Build an ApplicationContext hierarchy (adding a parent or root context).md" "b/IX. \342\200\230How-to\342\200\231 guides/62.3. Build an ApplicationContext hierarchy (adding a parent or root context).md" deleted file mode 100644 index 84a88b74..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/62.3. Build an ApplicationContext hierarchy (adding a parent or root context).md" +++ /dev/null @@ -1,3 +0,0 @@ -### 62.3. 构建ApplicationContext层次结构(添加父或根上下文) - -你可以使用`ApplicationBuilder`类创建父/根`ApplicationContext`层次结构。查看'Spring Boot特性'章节的[Section 22.3, “Fluent builder API” ](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-fluent-builder-api)获取更多信息。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/62.4. Create a non-web application.md" "b/IX. \342\200\230How-to\342\200\231 guides/62.4. Create a non-web application.md" deleted file mode 100644 index c913a87b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/62.4. Create a non-web application.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 62.4. 创建一个非web(non-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/63. Properties & configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/63. Properties & configuration.md" deleted file mode 100644 index 1d00fc7b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/63. Properties & configuration.md" +++ /dev/null @@ -1 +0,0 @@ -### 63. 属性&配置 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/63.1. Externalize the configuration of SpringApplication.md" "b/IX. \342\200\230How-to\342\200\231 guides/63.1. Externalize the configuration of SpringApplication.md" deleted file mode 100644 index 3eece1ac..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/63.1. Externalize the configuration of SpringApplication.md" +++ /dev/null @@ -1,8 +0,0 @@ -### 63.1. 外部化SpringApplication配置 - -SpringApplication已经被属性化(主要是setters),所以你可以在创建应用时使用它的Java API修改它的行为。或者你可以使用properties文件中的`spring.main.*`来外部化(在应用代码外配置)这些配置。比如,在`application.properties`中可能会有以下内容: -```java -spring.main.web_environment=false -spring.main.show_banner=false -``` -然后Spring Boot在启动时将不会显示banner,并且该应用也不是一个web应用。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/63.2. Change the location of external properties of an application.md" "b/IX. \342\200\230How-to\342\200\231 guides/63.2. Change the location of external properties of an application.md" deleted file mode 100644 index 71385554..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/63.2. Change the location of external properties of an application.md" +++ /dev/null @@ -1,15 +0,0 @@ - -### 63.2. 改变应用程序外部配置文件的位置 - -默认情况下,来自不同源的属性以一个定义好的顺序添加到Spring的`Environment`中(查看'Sprin Boot特性'章节的[Chapter 23, Externalized Configuration](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config)获取精确的顺序)。 - -为应用程序源添加`@PropertySource`注解是一种很好的添加和修改源顺序的方法。传递给`SpringApplication`静态便利设施(convenience)方法的类和使用`setSources()`添加的类都会被检查,以查看它们是否有`@PropertySources`,如果有,这些属性会被尽可能早的添加到`Environment`里,以确保`ApplicationContext`生命周期的所有阶段都能使用。以这种方式添加的属性优先于任何使用默认位置添加的属性,但低于系统属性,环境变量或命令行参数。 - -你也可以提供系统属性(或环境变量)来改变该行为: - -* `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/63.3. Use \342\200\230short\342\200\231 command line arguments.md" "b/IX. \342\200\230How-to\342\200\231 guides/63.3. Use \342\200\230short\342\200\231 command line arguments.md" deleted file mode 100644 index 583462f1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/63.3. Use \342\200\230short\342\200\231 command line arguments.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 63.3. 使用'short'命令行参数 - -有些人喜欢使用(例如)`--port=9000`代替`--server.port=9000`来设置命令行配置属性。你可以通过在application.properties中使用占位符来启用该功能,比如: -```java -server.port=${port:8080} -``` -**注**:如果你继承自`spring-boot-starter-parent` POM,为了防止和Spring-style的占位符产生冲突,`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/63.4. Use YAML for external properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/63.4. Use YAML for external properties.md" deleted file mode 100644 index f7b20243..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/63.4. Use YAML for external properties.md" +++ /dev/null @@ -1,23 +0,0 @@ - -### 63.4. 使用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 23.6, “Using YAML instead of Properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-yaml)可以获取更多关于YAML的信息。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/63.5. Set the active Spring profiles.md" "b/IX. \342\200\230How-to\342\200\231 guides/63.5. Set the active Spring profiles.md" deleted file mode 100644 index 62e7dcb7..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/63.5. Set the active Spring profiles.md" +++ /dev/null @@ -1,13 +0,0 @@ -### 63.5. 设置生效的Spring profiles - -Spring `Environment`有一个API可以设置生效的profiles,但通常你会设置一个系统profile(`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 24, Profiles](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-profiles)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/63.7. Discover built-in options for external properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/63.7. Discover built-in options for external properties.md" deleted file mode 100644 index 049499f4..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/63.7. Discover built-in options for external properties.md" +++ /dev/null @@ -1,8 +0,0 @@ - -### 63.7. 发现外部属性的内置选项 - -Spring Boot在运行时将来自application.properties(或.yml)的外部属性绑定进一个应用中。在一个地方不可能存在详尽的所有支持属性的列表(技术上也是不可能的),因为你的classpath下的其他jar文件也能够贡献。 - -每个运行中且有Actuator特性的应用都会有一个`configprops`端点,它能够展示所有边界和可通过`@ConfigurationProperties`绑定的属性。 - -附录中包含一个[application.properties](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties)示例,它列举了Spring Boot支持的大多数常用属性。获取权威列表可搜索`@ConfigurationProperties`和`@Value`的源码,还有不经常使用的`RelaxedEnvironment`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64. Embedded servlet containers.md" "b/IX. \342\200\230How-to\342\200\231 guides/64. Embedded servlet containers.md" deleted file mode 100644 index cb6f8fde..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64. Embedded servlet containers.md" +++ /dev/null @@ -1 +0,0 @@ -### 64. 内嵌的servlet容器 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.1. Add a Servlet, Filter or ServletContextListener to an application.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.1. Add a Servlet, Filter or ServletContextListener to an application.md" deleted file mode 100644 index dbf3e828..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.1. Add a Servlet, Filter or ServletContextListener to an application.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 64.1. 为应用添加Servlet,Filter或ServletContextListener - -Servlet规范支持的Servlet,Filter,ServletContextListener和其他监听器可以作为`@Bean`定义添加到你的应用中。需要格外小心的是,它们不会引起太多的其他beans的热初始化,因为在应用生命周期的早期它们已经被安装到容器里了(比如,让它们依赖你的DataSource或JPA配置就不是一个好主意)。你可以通过延迟初始化它们到第一次使用而不是初始化时来突破该限制。 - -在Filters和Servlets的情况下,你也可以通过添加一个`FilterRegistrationBean`或`ServletRegistrationBean`代替或以及底层的组件来添加映射(mappings)和初始化参数。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.10. Configure Jetty.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.10. Configure Jetty.md" deleted file mode 100644 index f4d5c554..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.10. Configure Jetty.md" +++ /dev/null @@ -1,4 +0,0 @@ - -### 64.10. 配置Jetty - -通常你可以遵循[Section 63.7, “Discover built-in options for external properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(此处主要是ServerProperties)的建议,但也要看下`EmbeddedServletContainerCustomizer`。Jetty API相当丰富,一旦获取到`JettyEmbeddedServletContainerFactory`,你就可以使用很多方式修改它。或更彻底地就是添加你自己的`JettyEmbeddedServletContainerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.12. Configure Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.12. Configure Undertow.md" deleted file mode 100644 index a18238c7..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.12. Configure Undertow.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 64.12. 配置Undertow - -通常你可以遵循[Section 63.7, “Discover built-in options for external properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(此处主要是ServerProperties和ServerProperties.Undertow),但也要看下`EmbeddedServletContainerCustomizer`。一旦获取到`UndertowEmbeddedServletContainerFactory`,你就可以使用一个`UndertowBuilderCustomizer`修改Undertow的配置以满足你的需求。或更彻底地就是添加你自己的`UndertowEmbeddedServletContainerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.14. Use Tomcat 7.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.14. Use Tomcat 7.md" deleted file mode 100644 index a8e44583..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.14. Use Tomcat 7.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 64.14. 使用Tomcat7 - -Tomcat7可用于Spring Boot,但默认使用的是Tomcat8。如果不能使用Tomcat8(例如,你使用的是Java1.6),你需要改变classpath去引用Tomcat7。 - - diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.14.1. Use Tomcat 7 with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.14.1. Use Tomcat 7 with Maven.md" deleted file mode 100644 index 97a0f734..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.14.1. Use Tomcat 7 with Maven.md" +++ /dev/null @@ -1,16 +0,0 @@ -### 64.14.1. 通过Maven使用Tomcat7 - -如果正在使用starter pom和parent,你只需要改变Tomcat的version属性,比如,对于一个简单的webapp或service: -```xml - - 7.0.59 - - - ... - - org.springframework.boot - spring-boot-starter-web - - ... - -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.14.2. Use Tomcat 7 with Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.14.2. Use Tomcat 7 with Gradle.md" deleted file mode 100644 index 2c2812ba..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.14.2. Use Tomcat 7 with Gradle.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 64.14.2. 通过Gradle使用Tomcat7 - -你可以通过设置`tomcat.version`属性改变Tomcat的版本: -```gradle -ext['tomcat.version'] = '7.0.59' -dependencies { - compile 'org.springframework.boot:spring-boot-starter-web' -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.15. Use Jetty 8.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.15. Use Jetty 8.md" deleted file mode 100644 index 1faddc7f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.15. Use Jetty 8.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 64.15. 使用Jetty8 - -Jetty8可用于Spring Boot,但默认使用的是Jetty9。如果不能使用Jetty9(例如,因为你使用的是Java1.6),你只需改变classpath去引用Jetty8。你也需要排除Jetty的WebSocket相关的依赖。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.16. Create WebSocket endpoints using @ServerEndpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.16. Create WebSocket endpoints using @ServerEndpoint.md" deleted file mode 100644 index bed423d7..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.16. Create WebSocket endpoints using @ServerEndpoint.md" +++ /dev/null @@ -1,10 +0,0 @@ -### 64.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/64.17. Enable HTTP response compression.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.17. Enable HTTP response compression.md" deleted file mode 100644 index 2f23ee08..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.17. Enable HTTP response compression.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 64.17. 启用HTTP响应压缩 - -Spring Boot提供两种启用HTTP压缩的机制;一种是Tomcat特有的,另一种是使用一个filter,可以配合Jetty,Tomcat和Undertow。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.17.1. Enable Tomcat\342\200\231s HTTP response compression.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.17.1. Enable Tomcat\342\200\231s HTTP response compression.md" deleted file mode 100644 index 5ae73d6b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.17.1. Enable Tomcat\342\200\231s HTTP response compression.md" +++ /dev/null @@ -1,14 +0,0 @@ -### 64.17.1. 启用Tomcat的HTTP响应压缩 - -Tomcat对HTTP响应压缩提供内建支持。默认是禁用的,但可以通过application.properties轻松的启用: -```java -server.tomcat.compression: on -``` -当设置为`on`时,Tomcat将压缩响应的长度至少为2048字节。你可以配置一个整型值来设置该限制而不只是`on`,比如: -```java -server.tomcat.compression: 4096 -``` -默认情况下,Tomcat只压缩某些MIME类型的响应(text/html,text/xml和text/plain)。你可以使用`server.tomcat.compressableMimeTypes`属性进行自定义,比如: -```java -server.tomcat.compressableMimeTypes=application/json,application/xml -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.17.2. Enable HTTP response compression using GzipFilter.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.17.2. Enable HTTP response compression using GzipFilter.md" deleted file mode 100644 index c2f6b3f9..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.17.2. Enable HTTP response compression using GzipFilter.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 64.17.2. 使用GzipFilter开启HTTP响应压缩 - -如果你正在使用Jetty或Undertow,或想要更精确的控制HTTP响应压缩,Spring Boot为Jetty的GzipFilter提供自动配置。虽然该过滤器是Jetty的一部分,但它也兼容Tomcat和Undertow。想要启用该过滤器,只需简单的为你的应用添加`org.eclipse.jetty:jetty-servlets`依赖。 - -GzipFilter可以使用`spring.http.gzip.*`属性进行配置。具体参考[GzipFilterProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/GzipFilterProperties.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.2. Change the HTTP port.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.2. Change the HTTP port.md" deleted file mode 100644 index 2b7377f0..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.2. Change the HTTP port.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 64.2. 改变HTTP端口 - -在一个单独的应用中,主HTTP端口默认为8080,但可以使用`server.port`设置(比如,在application.properties中或作为一个系统属性)。由于`Environment`值的宽松绑定,你也可以使用`SERVER_PORT`(比如,作为一个OS环境变)。 - -为了完全关闭HTTP端点,但仍创建一个WebApplicationContext,你可以设置`server.port=-1`(测试时可能有用)。 - -想获取更多详情可查看'Spring Boot特性'章节的[Section 26.3.3, “Customizing embedded servlet containers”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-customizing-embedded-containers),或[ServerProperties](http://github.com/spring-projects/spring-boot/tree/master/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/64.3. Use a random unassigned HTTP port.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.3. Use a random unassigned HTTP port.md" deleted file mode 100644 index 6978dced..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.3. Use a random unassigned HTTP port.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 64.3. 使用随机未分配的HTTP端口 - -想扫描一个未使用的端口(为了防止冲突使用OS本地端口)可以使用`server.port=0`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.4. Discover the HTTP port at runtime.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.4. Discover the HTTP port at runtime.md" deleted file mode 100644 index 8d122641..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.4. Discover the HTTP port at runtime.md" +++ /dev/null @@ -1,21 +0,0 @@ -### 64.4. 发现运行时的HTTP端口 - -你可以通过日志输出或它的EmbeddedServletContainer的EmbeddedWebApplicationContext获取服务器正在运行的端口。获取和确认服务器已经初始化的最好方式是添加一个`ApplicationListener`类型的`@Bean`,然后当事件发布时将容器pull出来。 - -使用`@WebIntegrationTests`的一个有用实践是设置`server.port=0`,然后使用`@Value`注入实际的('local')端口。例如: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class) -@WebIntegrationTest("server.port:0") -public class CityRepositoryIntegrationTests { - - @Autowired - EmbeddedWebApplicationContext server; - - @Value("${local.server.port}") - int port; - - // ... - -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.5. Configure SSL.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.5. Configure SSL.md" deleted file mode 100644 index 17bfc0bb..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.5. Configure SSL.md" +++ /dev/null @@ -1,14 +0,0 @@ -### 64.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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot/src/main/java/org/springframework/boot/context/embedded/Ssl.java)。 - -**注**:Tomcat要求key存储(如果你正在使用一个可信存储)能够直接在文件系统上访问,即它不能从一个jar文件内读取。Jetty和Undertow没有该限制。 - -使用类似于以上示例的配置意味着该应用将不在支持端口为8080的普通HTTP连接。Spring Boot不支持通过application.properties同时配置HTTP连接器和HTTPS连接器。如果你两个都想要,那就需要以编程的方式配置它们中的一个。推荐使用application.properties配置HTTPS,因为HTTP连接器是两个中最容易以编程方式进行配置的。获取示例可查看[spring-boot-sample-tomcat-multi-connectors](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors)示例项目。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.6. Configure Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.6. Configure Tomcat.md" deleted file mode 100644 index 4b685256..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.6. Configure Tomcat.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 64.6. 配置Tomcat - -通常你可以遵循[Section 63.7, “Discover built-in options for external properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(这里主要的是`ServerProperties`)的建议,但也看下`EmbeddedServletContainerCustomizer`和各种你可以添加的Tomcat-specific的`*Customizers`。 - -Tomcat APIs相当丰富,一旦获取到`TomcatEmbeddedServletContainerFactory`,你就能够以多种方式修改它。或核心选择是添加你自己的`TomcatEmbeddedServletContainerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.8. Use Tomcat behind a front-end proxy server.md" "b/IX. \342\200\230How-to\342\200\231 guides/64.8. Use Tomcat behind a front-end proxy server.md" deleted file mode 100644 index a32e788b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.8. Use Tomcat behind a front-end proxy server.md" +++ /dev/null @@ -1,19 +0,0 @@ -### 64.8. 在前端代理服务器后使用Tomcat - -Spring Boot将自动配置Tomcat的`RemoteIpValve`,如果你启用它的话。这允许你透明地使用标准的`x-forwarded-for`和`x-forwarded-proto`头,很多前端代理服务器都会添加这些头信息(headers)。通过将这些属性中的一个或全部设置为非空的内容来开启该功能(它们是大多数代理约定的值,如果你只设置其中的一个,则另一个也会被自动设置)。 -```java -server.tomcat.remote_ip_header=x-forwarded-for -server.tomcat.protocol_header=x-forwarded-proto -``` -如果你的代理使用不同的头部(headers),你可以通过向application.properties添加一些条目来自定义该值的配置,比如: -```java -server.tomcat.remote_ip_header=x-your-remote-ip-header -server.tomcat.protocol_header=x-your-protocol-header -``` -该值也可以配置为一个默认的,能够匹配信任的内部代理的正则表达式。默认情况下,受信任的IP包括 10/8, 192.168/16, 169.254/16 和 127/8。可以通过向application.properties添加一个条目来自定义该值的配置,比如: -```java -server.tomcat.internal_proxies=192\\.168\\.\\d{1,3}\\.\\d{1,3} -``` -**注**:只有在你使用一个properties文件作为配置的时候才需要双反斜杠。如果你使用YAML,单个反斜杠就足够了,`192\.168\.\d{1,3}\.\d{1,3}`和上面的等价。 - -另外,通过在一个`TomcatEmbeddedServletContainerFactory` bean中配置和添加`RemoteIpValve`,你就可以完全控制它的设置了。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65. Spring MVC.md" "b/IX. \342\200\230How-to\342\200\231 guides/65. Spring MVC.md" deleted file mode 100644 index 99201988..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65. Spring MVC.md" +++ /dev/null @@ -1 +0,0 @@ -### 65. Spring MVC diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.1. Write a JSON REST service.md" "b/IX. \342\200\230How-to\342\200\231 guides/65.1. Write a JSON REST service.md" deleted file mode 100644 index 0cd42874..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.1. Write a JSON REST service.md" +++ /dev/null @@ -1,17 +0,0 @@ - -### 65.1. 编写一个JSON REST服务 - -在Spring Boot应用中,任何Spring `@RestController`默认应该渲染为JSON响应,只要classpath下存在Jackson2。例如: -```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 -响应头。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.3. Customize the Jackson ObjectMapper.md" "b/IX. \342\200\230How-to\342\200\231 guides/65.3. Customize the Jackson ObjectMapper.md" deleted file mode 100644 index 6a9ed0e6..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.3. Customize the Jackson ObjectMapper.md" +++ /dev/null @@ -1,32 +0,0 @@ -### 65.3. 自定义Jackson ObjectMapper - -在一个HTTP交互中,Spring MVC(客户端和服务端)使用HttpMessageConverters协商内容转换。如果classpath下存在Jackson,你就已经获取到Jackson2ObjectMapperBuilder提供的默认转换器。 - -创建的ObjectMapper(或用于Jackson XML转换的XmlMapper)实例默认有以下自定义属性: - -- `MapperFeature.DEFAULT_VIEW_INCLUSION`禁用 -- `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`禁用 - -Spring Boot也有一些简化自定义该行为的特性。 - -你可以使用当前的environment配置ObjectMapper和XmlMapper实例。Jackson提供一个扩展套件,可以用来简单的关闭或开启一些特性,你可以用它们配置Jackson处理的不同方面。这些特性在Jackson中使用5个枚举进行描述的,并被映射到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`| - -例如,设置`spring.jackson.serialization.indent_output=true`可以开启漂亮打印。注意,由于[松绑定](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-relaxed-binding)的使用,`indent_output`不必匹配对应的枚举常量`INDENT_OUTPUT`。 - -如果想彻底替换默认的ObjectMapper,你需要定义一个该类型的`@Bean`并将它标记为`@Primary`。 - -定义一个Jackson2ObjectMapperBuilder类型的`@Bean`将允许你自定义默认的ObjectMapper和XmlMapper(分别用于MappingJackson2HttpMessageConverter和MappingJackson2XmlHttpMessageConverter)。 - -另一种自定义Jackson的方法是向你的上下文添加`com.fasterxml.jackson.databind.Module`类型的beans。它们会被注册入每个ObjectMapper类型的bean,当为你的应用添加新特性时,这就提供了一种全局机制来贡献自定义模块。 - -最后,如果你提供任何MappingJackson2HttpMessageConverter类型的`@Beans`,那它们将替换MVC配置中的默认值。同时,也提供一个HttpMessageConverters类型的bean,它有一些有用的方法可以获取默认的和用户增强的message转换器。 - -想要获取更多细节可查看[Section 65.4, “Customize the @ResponseBody rendering”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-responsebody-rendering)和[WebMvcAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.4. Customize the @ResponseBody rendering.md" "b/IX. \342\200\230How-to\342\200\231 guides/65.4. Customize the @ResponseBody rendering.md" deleted file mode 100644 index 64df7105..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.4. Customize the @ResponseBody rendering.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 65.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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.5. Handling Multipart File Uploads.md" "b/IX. \342\200\230How-to\342\200\231 guides/65.5. Handling Multipart File Uploads.md" deleted file mode 100644 index a6994904..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.5. Handling Multipart File Uploads.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 65.5. 处理Multipart文件上传 - -Spring Boot采用Servlet 3 `javax.servlet.http.Part` API来支持文件上传。默认情况下,Spring Boot配置Spring MVC在单个请求中每个文件最大1Mb,最多10Mb的文件数据。你可以覆盖那些值,也可以设置临时文件存储的位置(比如,存储到`/tmp`文件夹下)及传递数据刷新到磁盘的阀值(通过使用MultipartProperties类暴露的属性)。如果你需要设置文件不受限制,例如,可以设置`multipart.maxFileSize`属性值为`-1`。 - -当你想要接收部分(multipart)编码文件数据作为Spring MVC控制器(controller)处理方法中被`@RequestParam`注解的MultipartFile类型的参数时,multipart支持就非常有用了。 - -具体参考[MultipartAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.6. Switch off the Spring MVC DispatcherServlet.md" "b/IX. \342\200\230How-to\342\200\231 guides/65.6. Switch off the Spring MVC DispatcherServlet.md" deleted file mode 100644 index d978c4f7..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.6. Switch off the Spring MVC DispatcherServlet.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 65.6. 关闭Spring MVC DispatcherServlet - -Spring Boot想要服务来自应用程序root `/`下的所有内容。如果你想将自己的servlet映射到该目录下也是可以的,但当然你可能失去一些Boot MVC特性。为了添加你自己的servlet,并将它映射到root资源,你只需声明一个Servlet类型的`@Bean`,并给它特定的bean名称`dispatcherServlet`(如果只想关闭但不替换它,你可以使用该名称创建不同类型的bean)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.7. Switch off the Default MVC configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/65.7. Switch off the Default MVC configuration.md" deleted file mode 100644 index c1db458f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.7. Switch off the Default MVC configuration.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 65.7. 关闭默认的MVC配置 - -完全控制MVC配置的最简单方式是提供你自己的被`@EnableWebMvc`注解的`@Configuration`。这样所有的MVC配置都逃不出你的掌心。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.8. Customize ViewResolvers.md" "b/IX. \342\200\230How-to\342\200\231 guides/65.8. Customize ViewResolvers.md" deleted file mode 100644 index b7e80377..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.8. Customize ViewResolvers.md" +++ /dev/null @@ -1,15 +0,0 @@ -### 65.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页面)。它在视图(view name)上应用了一个前缀和后缀(默认都为空,但你可以通过`spring.view.prefix`和`spring.view.suffix`外部配置设置),然后查找在servlet上下文中具有该路径的物理资源。可以通过提供相同类型的bean覆盖它。 -- id为`beanNameViewResolver`的BeanNameViewResolver。这是视图解析器链的一个非常有用的成员,它可以在View被解析时收集任何具有相同名称的beans。 -- id为`viewResolver`的ContentNegotiatingViewResolver只会在实际View类型的beans出现时添加。这是一个'主'解析器,它的职责会代理给其他解析器,它会尝试找到客户端发送的一个匹配'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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java),[ThymeleafAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[FreeMarkerAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[GroovyTemplateAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[VelocityAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/66. Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/66. Logging.md" deleted file mode 100644 index 81108c7c..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/66. Logging.md" +++ /dev/null @@ -1,17 +0,0 @@ -### 66. 日志 - -Spring Boot除了commons-logging API外没有其他强制性的日志依赖,你有很多可选的日志实现。想要使用[Logback](http://logback.qos.ch/),你需要包含它,及一些对classpath下commons-logging的绑定。最简单的方式是通过依赖`spring-boot-starter-logging`的starter pom。对于一个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/66.1. Configure Logback for logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/66.1. Configure Logback for logging.md" deleted file mode 100644 index 8303b68c..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/66.1. Configure Logback for logging.md" +++ /dev/null @@ -1,18 +0,0 @@ -### 66.1. 配置Logback - -如果你将一个logback.xml放到classpath根目录下,那它将会被从这加载。Spring Boot提供一个默认的基本配置,如果你只是设置日志级别,那你可以包含它,比如: -```xml - - - - - -``` -如果查看spring-boot jar包中的默认logback.xml,你将会看到LoggingSystem为你创建的很多有用的系统属性,比如: -- ${PID},当前进程id -- ${LOG_FILE},如果在Boot外部配置中设置了`logging.file` -- ${LOG_PATH},如果设置了`logging.path`(表示日志文件产生的目录) - -Spring Boot也提供使用自定义的Logback转换器在控制台上输出一些漂亮的彩色ANSI日志信息(不是日志文件)。具体参考默认的`base.xml`配置。 - -如果Groovy在classpath下,你也可以使用logback.groovy配置Logback。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/66.2. Configure Log4j for logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/66.2. Configure Log4j for logging.md" deleted file mode 100644 index b4944a84..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/66.2. Configure Log4j for logging.md" +++ /dev/null @@ -1,28 +0,0 @@ -### 66.2. 配置Log4j - -Spring Boot也支持[Log4j](http://logging.apache.org/log4j/1.2)或[Log4j 2](http://logging.apache.org/log4j/2.x)作为日志配置,但只有在它们中的某个在classpath下存在的情况。如果你正在使用starter poms进行依赖装配,这意味着你需要排除Logback,然后包含你选择的Log4j版本。如果你不使用starter poms,那除了你选择的Log4j版本外还要提供commons-logging(至少)。 - -最简单的方式可能就是通过starter poms,尽管它需要排除一些依赖,比如,在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-log4j - -``` -想要使用Log4j 2,只需要依赖`spring-boot-starter-log4j2`而不是`spring-boot-starter-log4j`。 - -**注**:使用Log4j各版本的starters都会收集好依赖以满足common logging的要求(比如,Tomcat中使用`java.util.logging`,但使用Log4j或 Log4j 2作为输出)。具体查看Actuator Log4j或Log4j 2的示例,了解如何将它用于实战。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/66.2.1. Use YAML or JSON to configure Log4j 2.md" "b/IX. \342\200\230How-to\342\200\231 guides/66.2.1. Use YAML or JSON to configure Log4j 2.md" deleted file mode 100644 index d42bb00c..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/66.2.1. Use YAML or JSON to configure Log4j 2.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 66.2.1. 使用YAML或JSON配置Log4j2 - -除了它的默认XML配置格式,Log4j 2也支持YAML和JSON配置文件。想要使用其他配置文件格式来配置Log4j 2,你需要添加合适的依赖到classpath。为了使用YAML,你需要添加`com.fasterxml.jackson.dataformat:jackson-dataformat-yaml`依赖,Log4j 2将查找名称为`log4j2.yaml`或`log4j2.yml`的配置文件。为了使用JSON,你需要添加`com.fasterxml.jackson.core:jackson-databind`依赖,Log4j 2将查找名称为`log4j2.json`或`log4j2.jsn`的配置文件 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/67. Data Access.md" "b/IX. \342\200\230How-to\342\200\231 guides/67. Data Access.md" deleted file mode 100644 index b8fb1e03..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67. Data Access.md" +++ /dev/null @@ -1 +0,0 @@ -### 67. 数据访问 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/67.1. Configure a DataSource.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.1. Configure a DataSource.md" deleted file mode 100644 index 7ba21c87..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.1. Configure a DataSource.md" +++ /dev/null @@ -1,18 +0,0 @@ -### 67.1. 配置一个数据源 - -想要覆盖默认的设置只需要定义一个你自己的DataSource类型的`@Bean`。Spring Boot提供一个工具构建类DataSourceBuilder,可用来创建一个标准的DataSource(如果它处于classpath下),或者仅创建你自己的DataSource,然后将它和在[Section 23.7.1, “Third-party configuration”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-3rd-party-configuration)解释的一系列Environment属性绑定。 - -比如: -```java -@Bean -@ConfigurationProperties(prefix="datasource.mine") -public DataSource dataSource() { - return new FancyDataSource(); -} -``` -```java -datasource.mine.jdbcUrl=jdbc:h2:mem:mydb -datasource.mine.user=sa -datasource.mine.poolSize=30 -``` -具体参考'Spring Boot特性'章节中的[Section 28.1, “Configure a DataSource”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-configure-datasource)和[DataSourceAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/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/67.10. Expose Spring Data repositories as REST endpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.10. Expose Spring Data repositories as REST endpoint.md" deleted file mode 100644 index 4bafdc90..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.10. Expose Spring Data repositories as REST endpoint.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 67.10. 将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)。如果需要提供其他定制,你可以创建一个继承自SpringBootRepositoryRestMvcConfiguration的`@Configuration`类。该类功能和RepositoryRestMvcConfiguration相同,但允许你继续使用`spring.data.rest.*`属性。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/67.3. Use Spring Data repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.3. Use Spring Data repositories.md" deleted file mode 100644 index 5a450ec1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.3. Use Spring Data repositories.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 67.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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-jpa)或[Mongodb sample](http://github.com/spring-projects/spring-boot/tree/master/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/67.5. Configure JPA properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.5. Configure JPA properties.md" deleted file mode 100644 index 61034848..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.5. Configure JPA properties.md" +++ /dev/null @@ -1,12 +0,0 @@ -### 67.5. 配置JPA属性 - -Spring Data JPA已经提供了一些独立的配置选项(比如,针对SQL日志),并且Spring Boot会暴露它们,针对hibernate的外部配置属性也更多些。最常见的选项如下: -```java -spring.jpa.hibernate.ddl-auto: create-drop -spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.database: H2 -spring.jpa.show-sql: true -``` -(由于宽松的数据绑定策略,连字符或下划线作为属性keys作用应该是等效的)`ddl-auto`配置是个特殊情况,它有不同的默认设置,这取决于你是否使用一个内嵌数据库(create-drop)。当本地EntityManagerFactory被创建时,所有`spring.jpa.properties.*`属性都被作为正常的JPA属性(去掉前缀)传递进去了。 - -具体参考[HibernateJpaAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java)和[JpaBaseConfiguration](http://github.com/spring-projects/spring-boot/tree/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/67.6. Use a custom EntityManagerFactory.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.6. Use a custom EntityManagerFactory.md" deleted file mode 100644 index f5626e8b..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.6. Use a custom EntityManagerFactory.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 67.6. 使用自定义的EntityManagerFactory - -为了完全控制EntityManagerFactory的配置,你需要添加一个名为`entityManagerFactory`的`@Bean`。Spring Boot自动配置会根据是否存在该类型的bean来关闭它的实体管理器(entity manager)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/67.7. Use Two EntityManagers.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.7. Use Two EntityManagers.md" deleted file mode 100644 index 165c326a..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.7. Use Two EntityManagers.md" +++ /dev/null @@ -1,29 +0,0 @@ -### 67.7. 使用两个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事物管理器生成它两个。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/67.8. Use a traditional persistence.xml.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.8. Use a traditional persistence.xml.md" deleted file mode 100644 index ac8737f1..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.8. Use a traditional persistence.xml.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 67.8. 使用普通的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/67.9. Use Spring Data JPA and Mongo repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/67.9. Use Spring Data JPA and Mongo repositories.md" deleted file mode 100644 index 56dd7650..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.9. Use Spring Data JPA and Mongo repositories.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 67.9. 使用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/68. Spring Boot application.md" "b/IX. \342\200\230How-to\342\200\231 guides/68. Spring Boot application.md" new file mode 100644 index 00000000..64225ca5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/68. Spring Boot application.md" @@ -0,0 +1 @@ +### 68. Spring Boot应用 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/68.1 Create your own FailureAnalyzer.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.1 Create your own FailureAnalyzer.md" new file mode 100644 index 00000000..96e6f0b3 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/68.1 Create your own FailureAnalyzer.md" @@ -0,0 +1,10 @@ +###68.1 创建自己的FailureAnalyzer +[FailureAnalyzer](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/api/org/springframework/boot/diagnostics/FailureAnalyzer.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/68.1. Initialize a database using JPA.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.1. Initialize a database using JPA.md" deleted file mode 100644 index 950ddc92..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/68.1. Initialize a database using JPA.md" +++ /dev/null @@ -1,6 +0,0 @@ -### 68.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/68.2 Troubleshoot auto-configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.2 Troubleshoot auto-configuration.md" new file mode 100644 index 00000000..bd4d1c1b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/68.2 Troubleshoot auto-configuration.md" @@ -0,0 +1,15 @@ +### 68.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/68.2. Initialize a database using Hibernate.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.2. Initialize a database using Hibernate.md" deleted file mode 100644 index f6eed72f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/68.2. Initialize a database using Hibernate.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 68.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`,或使用其他机制初始化数据库。 - -此外,启动时处于classpath根目录下的import.sql文件会被执行。这在demos或测试时很有用,但在生产环境中你可能不期望这样。这是Hibernate的特性,和Spring没有一点关系。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/68.3 Customize the Environment or ApplicationContext before it starts.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.3 Customize the Environment or ApplicationContext before it starts.md" new file mode 100644 index 00000000..131324f1 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/68.3 Customize the Environment or ApplicationContext before it starts.md" @@ -0,0 +1,14 @@ +### 68.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/68.3. Initialize a database using Spring JDBC.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.3. Initialize a database using Spring JDBC.md" deleted file mode 100644 index 7719655f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/68.3. Initialize a database using Spring JDBC.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 68.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.continueOnError=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/68.4 Build an ApplicationContext hierarchy (adding a parent or root context).md" "b/IX. \342\200\230How-to\342\200\231 guides/68.4 Build an ApplicationContext hierarchy (adding a parent or root context).md" new file mode 100644 index 00000000..3c65c32b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/68.4 Build an ApplicationContext hierarchy (adding a parent or root context).md" @@ -0,0 +1,3 @@ +### 68.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/68.5 Create a non-web application.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.5 Create a non-web application.md" new file mode 100644 index 00000000..f905734d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/68.5 Create a non-web application.md" @@ -0,0 +1,3 @@ +### 68.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/68.5. Use a higher level database migration tool.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.5. Use a higher level database migration tool.md" deleted file mode 100644 index c0040faa..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/68.5. Use a higher level database migration tool.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 68.5. 使用一个高级别的数据迁移工具 - -Spring Boot跟高级别的数据迁移工具[Flyway](http://flywaydb.org/)(基于SQL)和[Liquibase](http://www.liquibase.org/)(XML)工作的很好。通常我们倾向于Flyway,因为它一眼看去好像很容易,另外它通常不需要平台独立:一般一个或至多需要两个平台。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/68.5.1. Execute Flyway database migrations on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.5.1. Execute Flyway database migrations on startup.md" deleted file mode 100644 index d68ca0c3..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/68.5.1. Execute Flyway database migrations on startup.md" +++ /dev/null @@ -1,9 +0,0 @@ -### 68.5.1. 启动时执行Flyway数据库迁移 - -想要在启动时自动运行Flyway数据库迁移,需要将`org.flywaydb:flyway-core`添加到你的classpath下。 - -迁移是一些`V__.sql`格式的脚本(``是一个下划线分割的版本号,比如'1'或'2_1')。默认情况下,它们存放在一个`classpath:db/migration`的文件夹中,但你可以使用`flyway.locations`(一个列表)来改变它。详情可参考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)中提供了一个小的属性集,可用于禁止迁移,或关闭位置检测。 - -默认情况下,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),你可以作为参考。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/68.5.2. Execute Liquibase database migrations on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/68.5.2. Execute Liquibase database migrations on startup.md" deleted file mode 100644 index 9c628601..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/68.5.2. Execute Liquibase database migrations on startup.md" +++ /dev/null @@ -1,7 +0,0 @@ -### 68.5.2. 启动时执行Liquibase数据库迁移 - -想要在启动时自动运行Liquibase数据库迁移,你需要将`org.liquibase:liquibase-core`添加到classpath下。 - -主改变日志(master change log)默认从`db/changelog/db.changelog-master.yaml`读取,但你可以使用`liquibase.change-log`进行设置。详情查看[LiquibaseProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java)以获取可用设置,比如上下文,默认的schema等。 - -这里有个[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/69. Properties & configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/69. Properties & configuration.md" new file mode 100644 index 00000000..536fd711 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69. Properties & configuration.md" @@ -0,0 +1 @@ +### 69. 属性&配置 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/69. Batch applications.md" "b/IX. \342\200\230How-to\342\200\231 guides/69. Batch applications.md" deleted file mode 100644 index 66c14450..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/69. Batch applications.md" +++ /dev/null @@ -1 +0,0 @@ -### 69. 批处理应用 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/69.1. Automatically expand properties at build time.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.1. Automatically expand properties at build time.md" new file mode 100644 index 00000000..0c5ce0ca --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.1. Automatically expand properties at build time.md" @@ -0,0 +1,3 @@ +###69.1. 运行时暴露属性 + +相对于在项目构建配置中硬编码某些配置,你可以使用已存在的构建配置自动暴露它们,Maven和Gradle都支持。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/69.1. Execute Spring Batch jobs on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.1. Execute Spring Batch jobs on startup.md" deleted file mode 100644 index 68846cef..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/69.1. Execute Spring Batch jobs on startup.md" +++ /dev/null @@ -1,10 +0,0 @@ - -### 69.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/69.1.1. Automatic property expansion using Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.1.1. Automatic property expansion using Maven.md" new file mode 100644 index 00000000..c847bf4d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.1.1. Automatic property expansion using Maven.md" @@ -0,0 +1,34 @@ +###69.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`目标进行替代,或自定义该插件的配置,具体查看[插件使用页面](http://docs.spring.io/spring-boot/docs/1.4.1.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占位符(比如`${foo}`)且没有将`useDefaultDelimiters`属性设置为`false`,那构建时这些属性将被暴露出去。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/69.1.2. Automatic property expansion using Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.1.2. Automatic property expansion using Gradle.md" new file mode 100644 index 00000000..8234b7a0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.1.2. Automatic property expansion using Gradle.md" @@ -0,0 +1,15 @@ +###69.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/69.2. Externalize the configuration of SpringApplication.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.2. Externalize the configuration of SpringApplication.md" new file mode 100644 index 00000000..7f3c3c09 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.2. Externalize the configuration of SpringApplication.md" @@ -0,0 +1,24 @@ +### 69.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/69.3 Change the location of external properties of an application.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.3 Change the location of external properties of an application.md" new file mode 100644 index 00000000..0f33fd8a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.3 Change the location of external properties of an application.md" @@ -0,0 +1,13 @@ + +### 69.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/69.4 Use \342\200\230short\342\200\231 command line arguments.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.4 Use \342\200\230short\342\200\231 command line arguments.md" new file mode 100644 index 00000000..e4bfbe3f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.4 Use \342\200\230short\342\200\231 command line arguments.md" @@ -0,0 +1,9 @@ +### 69.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/69.5 Use YAML for external properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.5 Use YAML for external properties.md" new file mode 100644 index 00000000..8463ca11 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.5 Use YAML for external properties.md" @@ -0,0 +1,23 @@ + +###69.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/69.6 Set the active Spring profiles.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.6 Set the active Spring profiles.md" new file mode 100644 index 00000000..a2f31e04 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.6 Set the active Spring profiles.md" @@ -0,0 +1,13 @@ +### 69.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/63.6. Change configuration depending on the environment.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.7 Change configuration depending on the environment.md" similarity index 71% rename from "IX. \342\200\230How-to\342\200\231 guides/63.6. Change configuration depending on the environment.md" rename to "IX. \342\200\230How-to\342\200\231 guides/69.7 Change configuration depending on the environment.md" index efdc2d2a..cf0e1608 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/63.6. Change configuration depending on the environment.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.7 Change configuration depending on the environment.md" @@ -1,4 +1,4 @@ -### 63.6. 根据环境改变配置 +### 69.7 根据环境改变配置 一个YAML文件实际上是一系列以`---`线分割的文档,每个文档都被单独解析为一个平坦的(flattened)map。 @@ -22,8 +22,8 @@ spring: server: port: 0 ``` -在这个示例中,默认的端口是9000,但如果Spring profile 'development'生效则该端口是9001,如果'production'生效则它是0。 +在这个示例中,默认的端口是`9000`,但如果Spring profile `development`生效则该端口是`9001`,如果`production`生效则它是`0`。 -YAML文档以它们遇到的顺序合并(所以后面的值会覆盖前面的值)。 +YAML文档以它们出现的顺序合并,所以后面的值会覆盖前面的值。 想要使用profiles文件完成同样的操作,你可以使用`application-${profile}.properties`指定特殊的,profile相关的值。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/69.8 Discover built-in options for external properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/69.8 Discover built-in options for external properties.md" new file mode 100644 index 00000000..8b5290c2 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/69.8 Discover built-in options for external properties.md" @@ -0,0 +1,8 @@ + +### 69.8 发现外部属性的内置选项 + +Spring Boot在运行时会将来自`application.properties`(或`.yml`)的外部属性绑定到应用,因为不可能将所有支持的属性放到一个地方,classpath下的其他jar也有支持的属性。 + +每个运行中且有Actuator特性的应用都会有一个`configprops`端点,它能够展示所有边界和可通过`@ConfigurationProperties`绑定的属性。 + +附录中包含一个[application.properties](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#common-application-properties)示例,它列举了Spring Boot支持的大多数常用属性,查看`@ConfigurationProperties`,`@Value`,还有不经常使用的`RelaxedEnvironment`的源码可获取最权威的属性列表。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70. Actuator.md" "b/IX. \342\200\230How-to\342\200\231 guides/70. Actuator.md" deleted file mode 100644 index f2aaf880..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/70. Actuator.md" +++ /dev/null @@ -1 +0,0 @@ -### 70. 执行器(Actuator) diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70. Embedded servlet containers.md" "b/IX. \342\200\230How-to\342\200\231 guides/70. Embedded servlet containers.md" new file mode 100644 index 00000000..8964dae0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70. Embedded servlet containers.md" @@ -0,0 +1 @@ +### 70. 内嵌servlet容器 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.1 Add a Servlet, Filter or ServletContextListener to an application.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.1 Add a Servlet, Filter or ServletContextListener to an application.md" new file mode 100644 index 00000000..26331a08 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.1 Add a Servlet, Filter or ServletContextListener to an application.md" @@ -0,0 +1,3 @@ +### 70.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/70.1. Change the HTTP port or address of the actuator endpoints.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.1. Change the HTTP port or address of the actuator endpoints.md" deleted file mode 100644 index 2385d8ac..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/70.1. Change the HTTP port or address of the actuator endpoints.md" +++ /dev/null @@ -1,6 +0,0 @@ - -### 70.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 41.3, “Customizing the management server port”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-customizing-management-server-port)来获取更多详情。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.1.1 Add a Servlet, Filter or Listener using a Spring bean.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.1.1 Add a Servlet, Filter or Listener using a Spring bean.md" new file mode 100644 index 00000000..c4dc36cb --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.1.1 Add a Servlet, Filter or Listener using a Spring bean.md" @@ -0,0 +1,29 @@ +###70.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/70.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md" new file mode 100644 index 00000000..35b9995e --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md" @@ -0,0 +1,3 @@ +###70.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/70.10 Use Tomcat\342\200\231s LegacyCookieProcessor.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.10 Use Tomcat\342\200\231s LegacyCookieProcessor.md" new file mode 100644 index 00000000..a4f5cf79 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.10 Use Tomcat\342\200\231s LegacyCookieProcessor.md" @@ -0,0 +1,30 @@ +###70.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`。通过向`EmbeddedServletContainerCustomizer` bean添加一个`TomcatContextCustomizer`可以开启`LegacyCookieProcessor`: +```java +@Bean +public EmbeddedServletContainerCustomizer cookieProcessorCustomizer() { + return new EmbeddedServletContainerCustomizer() { + + @Override + public void customize(ConfigurableEmbeddedServletContainer container) { + if (container instanceof TomcatEmbeddedServletContainerFactory) { + ((TomcatEmbeddedServletContainerFactory) container) + .addContextCustomizers(new TomcatContextCustomizer() { + + @Override + public void customize(Context context) { + context.setCookieProcessor(new LegacyCookieProcessor()); + } + + }); + } + } + + }; +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.9. Use Jetty instead of Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.11 Use Jetty instead of Tomcat.md" similarity index 64% rename from "IX. \342\200\230How-to\342\200\231 guides/64.9. Use Jetty instead of Tomcat.md" rename to "IX. \342\200\230How-to\342\200\231 guides/70.11 Use Jetty instead of Tomcat.md" index 696b25ef..8ac40fb8 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.9. Use Jetty instead of Tomcat.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.11 Use Jetty instead of Tomcat.md" @@ -1,6 +1,6 @@ -### 64.9. 使用Jetty替代Tomcat +### 70.11 使用Jetty替代Tomcat -Spring Boot starters(特别是spring-boot-starter-web)默认都是使用Tomcat作为内嵌容器的。你需要排除那些Tomcat的依赖并包含Jetty的依赖。为了让这种处理尽可能简单,Spring Boot将Tomcat和Jetty的依赖捆绑在一起,然后提供单独的starters。 +Spring Boot starters(特别是`spring-boot-starter-web`)默认都使用Tomcat作为内嵌容器。想使用Jetty替代Tomcat,你需要排除那些Tomcat的依赖并包含Jetty的依赖。为了简化这种事情的处理,Spring Boot将Tomcat和Jetty的依赖捆绑在一起,然后提供了单独的starters。 Maven示例: ```xml @@ -26,8 +26,8 @@ configurations { } dependencies { - compile("org.springframework.boot:spring-boot-starter-web:1.3.0.BUILD-SNAPSHOT") - compile("org.springframework.boot:spring-boot-starter-jetty:1.3.0.BUILD-SNAPSHOT") + compile("org.springframework.boot:spring-boot-starter-web:1.4.1.RELEASE") + compile("org.springframework.boot:spring-boot-starter-jetty:1.4.1.RELEASE") // ... } ``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.12 Configure Jetty.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.12 Configure Jetty.md" new file mode 100644 index 00000000..7a0bb7be --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.12 Configure Jetty.md" @@ -0,0 +1,6 @@ + +### 70.12 配置Jetty + +通常你可以遵循[Section 69.8, “Discover built-in options for external properties”](./69.8 Discover built-in options for external properties.md)关于`@ConfigurationProperties`(此处主要是`ServerProperties`)的建议,但也要看下`EmbeddedServletContainerCustomizer`。 + +Jetty API相当丰富,一旦获取到`JettyEmbeddedServletContainerFactory`,你就可以使用很多方式修改它,或更彻底地就是添加你自己的`JettyEmbeddedServletContainerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.11. Use Undertow instead of Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.13 Use Undertow instead of Tomcat.md" similarity index 73% rename from "IX. \342\200\230How-to\342\200\231 guides/64.11. Use Undertow instead of Tomcat.md" rename to "IX. \342\200\230How-to\342\200\231 guides/70.13 Use Undertow instead of Tomcat.md" index 33bd22e0..dfa12014 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.11. Use Undertow instead of Tomcat.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.13 Use Undertow instead of Tomcat.md" @@ -1,6 +1,6 @@ -### 64.11. 使用Undertow替代Tomcat +### 70.13 使用Undertow替代Tomcat -使用Undertow替代Tomcat和[使用Jetty替代Tomcat](https://github.com/qibaoguang/Spring-Boot-Reference-Guide/edit/master/How-to_%20guides.md)非常类似。你需要排除Tomat依赖,并包含Undertow starter。 +使用Undertow替代Tomcat和[使用Jetty替代Tomcat](./70.11 Use Jetty instead of Tomcat.md)非常类似。你需要排除Tomat依赖,并包含Undertow starter。 Maven示例: ```xml diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.14 Configure Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.14 Configure Undertow.md" new file mode 100644 index 00000000..010f156b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.14 Configure Undertow.md" @@ -0,0 +1,5 @@ +### 70.14 配置Undertow + +通常你可以遵循[Section 69.8, “Discover built-in options for external properties”](./69.8 Discover built-in options for external properties.md)关于`@ConfigurationProperties`(此处主要是`ServerProperties`和`ServerProperties.Undertow`),但也要看下`EmbeddedServletContainerCustomizer`。 + +一旦获取到`UndertowEmbeddedServletContainerFactory`,你就可以使用`UndertowBuilderCustomizer`修改Undertow的配置以满足你的需求,或更彻底地就是添加你自己的`UndertowEmbeddedServletContainerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.13. Enable Multiple Listeners with Undertow.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.15 Enable Multiple Listeners with Undertow.md" similarity index 67% rename from "IX. \342\200\230How-to\342\200\231 guides/64.13. Enable Multiple Listeners with Undertow.md" rename to "IX. \342\200\230How-to\342\200\231 guides/70.15 Enable Multiple Listeners with Undertow.md" index 4cba1dae..a6bd052e 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.13. Enable Multiple Listeners with Undertow.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.15 Enable Multiple Listeners with Undertow.md" @@ -1,6 +1,6 @@ -### 64.13. 启用Undertow的多监听器(Multiple Listeners) +### 70.15 启用Undertow的多监听器 -往`UndertowEmbeddedServletContainerFactory`添加一个`UndertowBuilderCustomizer`,然后添加一个监听者到`Builder`: +将`UndertowBuilderCustomizer`添加到`UndertowEmbeddedServletContainerFactory`,然后使用`Builder`添加一个listener: ```java @Bean public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() { diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.16 Use Tomcat 7.x or 8.0.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.16 Use Tomcat 7.x or 8.0.md" new file mode 100644 index 00000000..ce316260 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.16 Use Tomcat 7.x or 8.0.md" @@ -0,0 +1,3 @@ +### 70.16 使用Tomcat 7.x或8.0 + +Spring Boot可以使用Tomcat7&8.0,但默认使用的是Tomcat8.5。如果不能使用Tomcat8.5(例如,因为你使用的是Java1.6),你需要改变classpath去引用一个不同版本。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.16.1 Use Tomcat 7.x or 8.0 with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.16.1 Use Tomcat 7.x or 8.0 with Maven.md" new file mode 100644 index 00000000..3752e50d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.16.1 Use Tomcat 7.x or 8.0 with Maven.md" @@ -0,0 +1,21 @@ +### 70.16.1 通过Maven使用Tomcat 7.x或8.0 + +如果正在使用starters 和parent,你只需要改变Tomcat的`version`属性,并添加`tomcat-juli`依赖。比如,对于一个简单的webapp或service: +```xml + + 7.0.59 + + + ... + + org.springframework.boot + spring-boot-starter-web + + + org.apache.tomcat + tomcat-juli + ${tomcat.version} + + ... + +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.16.2 Use Tomcat 7.x or 8.0 with Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.16.2 Use Tomcat 7.x or 8.0 with Gradle.md" new file mode 100644 index 00000000..e9bb236d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.16.2 Use Tomcat 7.x or 8.0 with Gradle.md" @@ -0,0 +1,10 @@ +### 70.16.2 通过Gradle使用Tomcat7.x或8.0 + +对于Gradle,你可以通过设置`tomcat.version`属性改变Tomcat的版本,然后添加`tomcat-juli`依赖: +```gradle +ext['tomcat.version'] = '7.0.59' +dependencies { + compile 'org.springframework.boot:spring-boot-starter-web' + compile group:'org.apache.tomcat', name:'tomcat-juli', version:property('tomcat.version') +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.17 Use Jetty 9.2.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.17 Use Jetty 9.2.md" new file mode 100644 index 00000000..1aa0b4e0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.17 Use Jetty 9.2.md" @@ -0,0 +1,3 @@ +### 70.17 使用Jetty9.2 + +Spring Boot可以使用Jetty9.2,但默认使用的是Jetty9.3。如果不能使用Jetty9.3(例如,因为你使用的是Java7),你需要改变classpath去引用Jetty9.2。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.17.1 Use Jetty9.2 with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.17.1 Use Jetty9.2 with Maven.md" new file mode 100644 index 00000000..f3e29c76 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.17.1 Use Jetty9.2 with Maven.md" @@ -0,0 +1,24 @@ +### 70.17.1 通过Maven使用Jetty9.2 + +如果正在使用starters和parent,你只需添加Jetty starter并覆盖`jetty.version`属性: +```xml + + 9.2.17.v20160517 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + org.springframework.boot + spring-boot-starter-jetty + + +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.17.2 Use Jetty 9.2 with Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.17.2 Use Jetty 9.2 with Gradle.md" new file mode 100644 index 00000000..b8753df0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.17.2 Use Jetty 9.2 with Gradle.md" @@ -0,0 +1,12 @@ +### 70.17.2 通过Gradle使用Jetty 9.2 + +对于Gradle,你需要设置`jetty.version`属性,例如对于一个简单的webapp或service: +```gradle +ext['jetty.version'] = '9.2.17.v20160517' +dependencies { + compile ('org.springframework.boot:spring-boot-starter-web') { + exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' + } + compile ('org.springframework.boot:spring-boot-starter-jetty') +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.18 Use Jetty 8.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.18 Use Jetty 8.md" new file mode 100644 index 00000000..0c28e533 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.18 Use Jetty 8.md" @@ -0,0 +1,3 @@ +###70.18 使用Jetty 8 + +Spring Boot支持Jetty 8,但默认使用的是Jetty 9.3。如果不能使用Jetty 9.3(比如因为你使用的是Java 1.6),你需要改变classpath去引用Jetty 8,还需要排除Jetty的WebSocket相关依赖。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.15.1. Use Jetty 8 with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.18.1 Use Jetty 8 with Maven.md" similarity index 78% rename from "IX. \342\200\230How-to\342\200\231 guides/64.15.1. Use Jetty 8 with Maven.md" rename to "IX. \342\200\230How-to\342\200\231 guides/70.18.1 Use Jetty 8 with Maven.md" index 9bbe670c..9098194a 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.15.1. Use Jetty 8 with Maven.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.18.1 Use Jetty 8 with Maven.md" @@ -1,31 +1,31 @@ -### 64.15.1. 通过Maven使用Jetty8 - -如果正在使用starter pom和parent,你只需添加Jetty starter,去掉WebSocket依赖,并改变version属性,比如,对于一个简单的webapp或service: -```xml - - 8.1.15.v20140411 - 2.2.0.v201112011158 - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-starter-jetty - - - org.eclipse.jetty.websocket - * - - - - -``` +###70.18.1 通过Maven使用Jetty8 + +如果正在使用starters和parent,你只需要添加Jetty starter,排除那些需要的WebSocket,并改变version属性。比如,对于一个简单的webapp或service: +```xml + + 8.1.15.v20140411 + 2.2.0.v201112011158 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + org.springframework.boot + spring-boot-starter-jetty + + + org.eclipse.jetty.websocket + * + + + + +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.15.2. Use Jetty 8 with Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.18.2 Use Jetty 8 with Gradle.md" similarity index 90% rename from "IX. \342\200\230How-to\342\200\231 guides/64.15.2. Use Jetty 8 with Gradle.md" rename to "IX. \342\200\230How-to\342\200\231 guides/70.18.2 Use Jetty 8 with Gradle.md" index b4f08f44..197e7a31 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.15.2. Use Jetty 8 with Gradle.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.18.2 Use Jetty 8 with Gradle.md" @@ -1,4 +1,4 @@ -### 64.15.2. 通过Gradle使用Jetty8 +### 70.18.2 通过Gradle使用Jetty8 你可以设置`jetty.version`属性并排除相关的WebSocket依赖,比如对于一个简单的webapp或service: ```gradle diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.19 Create WebSocket endpoints using @ServerEndpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.19 Create WebSocket endpoints using @ServerEndpoint.md" new file mode 100644 index 00000000..91b1efab --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.19 Create WebSocket endpoints using @ServerEndpoint.md" @@ -0,0 +1,10 @@ +### 70.19 使用@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/70.2 Change the HTTP port.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.2 Change the HTTP port.md" new file mode 100644 index 00000000..53ffdf12 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.2 Change the HTTP port.md" @@ -0,0 +1,5 @@ +### 70.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/v1.4.1.RELEASE/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/70.2. Customize the \342\200\230whitelabel\342\200\231 error page.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.2. Customize the \342\200\230whitelabel\342\200\231 error page.md" deleted file mode 100644 index e6aeac64..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/70.2. Customize the \342\200\230whitelabel\342\200\231 error page.md" +++ /dev/null @@ -1,5 +0,0 @@ -### 70.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](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling)章节,了解下如何将处理器(handlers)注册到servlet容器中。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.20 Enable HTTP response compression.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.20 Enable HTTP response compression.md" new file mode 100644 index 00000000..4ef1af57 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.20 Enable HTTP response compression.md" @@ -0,0 +1,14 @@ +### 70.20 启用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/70.3 Use a random unassigned HTTP port.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.3 Use a random unassigned HTTP port.md" new file mode 100644 index 00000000..0cfc5bbf --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.3 Use a random unassigned HTTP port.md" @@ -0,0 +1,3 @@ +### 70.3 使用随机未分配的HTTP端口 + +想扫描获取一个未使用的端口(使用操作系统本地端口以防冲突)可以设置`server.port=0`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.4 Discover the HTTP port at runtime.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.4 Discover the HTTP port at runtime.md" new file mode 100644 index 00000000..a042fa4c --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.4 Discover the HTTP port at runtime.md" @@ -0,0 +1,21 @@ +### 70.4 发现运行时的HTTP端口 + +你可以通过日志输出或它的`EmbeddedServletContainer`的`EmbeddedWebApplicationContext`获取服务器正在运行的端口。获取和确认服务器已经初始化的最好方式是添加一个`ApplicationListener`类型的`@Bean`,然后当事件发布时将容器pull出来。 + +使用`@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`进行测试时,你可以通过`@LocalServerPort`注解将实际端口注入到字段中,例如: +```java +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) +public class MyWebIntegrationTests { + + @Autowired + EmbeddedWebApplicationContext server; + + @LocalServerPort + int port; + + // ... + +} +``` +**注** `@LocalServerPort`是`@Value("${local.server.port}")`的元数据,在常规的应用中不要尝试注入端口。正如我们看到的,该值只会在容器初始化后设置。相对于测试,应用代码回调处理的会更早(例如在该值实际可用之前)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.5 Configure SSL.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.5 Configure SSL.md" new file mode 100644 index 00000000..7ea95030 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.5 Configure SSL.md" @@ -0,0 +1,12 @@ +### 70.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/v1.4.1.RELEASE/spring-boot/src/main/java/org/springframework/boot/context/embedded/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/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors)可获取示例项目。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.6 Configure Access Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.6 Configure Access Logging.md" new file mode 100644 index 00000000..21029aaa --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.6 Configure Access Logging.md" @@ -0,0 +1,16 @@ +###70.6 配置访问日志 + +通过相应的命令空间可以为Tomcat和Undertow配置访问日志,例如下面是为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`自定义。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.7 Use behind a front-end proxy server.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.7 Use behind a front-end proxy server.md" new file mode 100644 index 00000000..3a7f350b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.7 Use behind a front-end proxy server.md" @@ -0,0 +1,7 @@ +###70.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/70.7.1 Customize Tomcat\342\200\231s proxy configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.7.1 Customize Tomcat\342\200\231s proxy configuration.md" new file mode 100644 index 00000000..e48961f3 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.7.1 Customize Tomcat\342\200\231s proxy configuration.md" @@ -0,0 +1,16 @@ +###70.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`)并在`TomcatEmbeddedServletContainerFactory` bean添加一个新value实例。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/70.8 Configure Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.8 Configure Tomcat.md" new file mode 100644 index 00000000..7f9d62db --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.8 Configure Tomcat.md" @@ -0,0 +1,5 @@ +### 70.8 配置Tomcat + +通常你可以遵循[Section 69.8, “Discover built-in options for external properties”](./69.8 Discover built-in options for external properties.md)关于`@ConfigurationProperties`(这里主要的是`ServerProperties`)的建议,但也看下`EmbeddedServletContainerCustomizer`和各种你可以添加的Tomcat-specific的`*Customizers`。 + +Tomcat APIs相当丰富,一旦获取到`TomcatEmbeddedServletContainerFactory`,你就能够以多种方式修改它,或更彻底地就是添加你自己的`TomcatEmbeddedServletContainerFactory`。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/64.7. Enable Multiple Connectors with Tomcat.md" "b/IX. \342\200\230How-to\342\200\231 guides/70.9 Enable Multiple Connectors with Tomcat.md" similarity index 82% rename from "IX. \342\200\230How-to\342\200\231 guides/64.7. Enable Multiple Connectors with Tomcat.md" rename to "IX. \342\200\230How-to\342\200\231 guides/70.9 Enable Multiple Connectors with Tomcat.md" index b7357cd8..d5896751 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/64.7. Enable Multiple Connectors with Tomcat.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/70.9 Enable Multiple Connectors with Tomcat.md" @@ -1,6 +1,6 @@ -### 64.7. 启用Tomcat的多连接器(Multiple Connectors) +### 70.9 启用Tomcat的多连接器 -你可以将一个`org.apache.catalina.connector.Connector`添加到`TomcatEmbeddedServletContainerFactory`,这就能够允许多连接器,比如HTTP和HTTPS连接器: +你可以将`org.apache.catalina.connector.Connector`添加到`TomcatEmbeddedServletContainerFactory`,这就能够允许多连接器,比如HTTP和HTTPS连接器: ```java @Bean public EmbeddedServletContainerFactory servletContainer() { diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71. Security.md" "b/IX. \342\200\230How-to\342\200\231 guides/71. Security.md" deleted file mode 100644 index b581f5bf..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71. Security.md" +++ /dev/null @@ -1 +0,0 @@ -### 71. 安全 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71. Spring MVC.md" "b/IX. \342\200\230How-to\342\200\231 guides/71. Spring MVC.md" new file mode 100644 index 00000000..ac4351e1 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71. Spring MVC.md" @@ -0,0 +1 @@ +### 71. Spring MVC diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.1 Write a JSON REST service.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.1 Write a JSON REST service.md" new file mode 100644 index 00000000..2d01cd3a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.1 Write a JSON REST service.md" @@ -0,0 +1,15 @@ +### 71.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/71.10 Use Thymeleaf 3.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.10 Use Thymeleaf 3.md" new file mode 100644 index 00000000..b2e0f9b6 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.10 Use Thymeleaf 3.md" @@ -0,0 +1,16 @@ +###71.10 使用Thymeleaf 3 + +默认情况下,`spring-boot-starter-thymeleaf`使用的是Thymeleaf 2.1,你可以通过覆盖`thymeleaf.version`和`thymeleaf-layout-dialect.version`属性使用Thymeleaf 3,例如: +```properties + + 3.0.0.RELEASE + 2.0.0 + +``` +为了避免关于HTML 5模板模式过期,将使用HTML模板模式的警告提醒,你需要显式配置`spring.thymeleaf.mode`为`HTML`,例如: +```properties +spring.thymeleaf.mode: HTML +``` +具体操作可查看[Thymeleaf 3示例](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-web-thymeleaf3)。 + +如果正在使用其他自动配置的Thymeleaf附加组件(Spring Security,Data Attribute或Java 8 Time),你需要使用兼容Thymeleaf 3.0的版本覆盖它们现在的版本。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/65.2. Write an XML REST service.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.2 Write an XML REST service.md" similarity index 55% rename from "IX. \342\200\230How-to\342\200\231 guides/65.2. Write an XML REST service.md" rename to "IX. \342\200\230How-to\342\200\231 guides/71.2 Write an XML REST service.md" index 6fbd531b..31c64507 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/65.2. Write an XML REST service.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.2 Write an XML REST service.md" @@ -1,20 +1,20 @@ -### 65.2. 编写一个XML REST服务 +### 71.2 编写XML REST服务 -如果classpath下存在Jackson XML扩展(jackson-dataformat-xml),它会被用来渲染XML响应,示例和JSON的非常相似。想要使用它,只需为你的项目添加以下的依赖: +如果classpath下存在Jackson XML扩展(`jackson-dataformat-xml`),它会被用来渲染XML响应,示例和JSON的非常相似。想要使用它,只需为你的项目添加以下依赖: ```xml com.fasterxml.jackson.dataformat jackson-dataformat-xml ``` -你可能也想添加对Woodstox的依赖。它比JDK提供的默认Stax实现快很多,并且支持良好的格式化输出,提高了namespace处理能力: +你可能还需要添加Woodstox的依赖,它比JDK提供的默认StAX实现快很多,并且支持良好的格式化输出,提高了namespace处理能力: ```xml org.codehaus.woodstox woodstox-core-asl ``` -如果Jackson的XML扩展不可用,Spring Boot将使用JAXB(JDK默认提供),不过你需要为MyThing添加额外的注解`@XmlRootElement`: +如果Jackson的XML扩展不可用,Spring Boot将使用JAXB(JDK默认提供),不过`MyThing`需要注解`@XmlRootElement`: ```java @XmlRootElement public class MyThing { diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.3 Customize the Jackson ObjectMapper.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.3 Customize the Jackson ObjectMapper.md" new file mode 100644 index 00000000..717f1c03 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.3 Customize the Jackson ObjectMapper.md" @@ -0,0 +1,33 @@ +### 71.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 71.4, “Customize the @ResponseBody rendering”](./71.4 Customize the @ResponseBody rendering.md)及[WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.3. Enable HTTPS when running behind a proxy server.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.3. Enable HTTPS when running behind a proxy server.md" deleted file mode 100644 index 7c6563e7..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.3. Enable HTTPS when running behind a proxy server.md" +++ /dev/null @@ -1,12 +0,0 @@ -### 71.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 -``` -(这些属性出现一个就会开启该功能,或者你可以通过添加一个TomcatEmbeddedServletContainerFactory 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/71.4 Customize the @ResponseBody rendering.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.4 Customize the @ResponseBody rendering.md" new file mode 100644 index 00000000..de8654a4 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.4 Customize the @ResponseBody rendering.md" @@ -0,0 +1,7 @@ +### 71.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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.5 Handling Multipart File Uploads.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.5 Handling Multipart File Uploads.md" new file mode 100644 index 00000000..0340ad86 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.5 Handling Multipart File Uploads.md" @@ -0,0 +1,7 @@ +### 71.5 处理Multipart文件上传 + +Spring Boot采用Servlet 3 `javax.servlet.http.Part` API来支持文件上传。默认情况下,Spring Boot配置Spring MVC在单个请求中只处理每个文件最大1Mb,最多10Mb的文件数据。你可以覆盖那些值,也可以设置临时文件存储的位置(比如,存储到`/tmp`文件夹下)及传递数据刷新到磁盘的阀值(通过使用`MultipartProperties`类暴露的属性)。如果你需要设置文件不受限制,可以设置`spring.http.multipart.max-file-size`属性值为`-1`。 + +当你想要接收multipart编码文件数据作为Spring MVC控制器(controller)处理方法中被`@RequestParam`注解的`MultipartFile`类型的参数时,multipart支持就非常有用了。 + +更多详情可参考[MultipartAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java)源码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.6 Switch off the Spring MVC DispatcherServlet.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.6 Switch off the Spring MVC DispatcherServlet.md" new file mode 100644 index 00000000..fc240cbe --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.6 Switch off the Spring MVC DispatcherServlet.md" @@ -0,0 +1,3 @@ +### 71.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/71.7 Switch off the Default MVC configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.7 Switch off the Default MVC configuration.md" new file mode 100644 index 00000000..efcb9d3f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.7 Switch off the Default MVC configuration.md" @@ -0,0 +1,3 @@ +### 71.7 关闭默认的MVC配置 + +完全控制MVC配置的最简单方式是提供你自己的被`@EnableWebMvc`注解的`@Configuration`,这样所有的MVC配置都逃不出你的掌心。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.8 Customize ViewResolvers.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.8 Customize ViewResolvers.md" new file mode 100644 index 00000000..0d76b030 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.8 Customize ViewResolvers.md" @@ -0,0 +1,15 @@ +### 71.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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java),[ThymeleafAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[FreeMarkerAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java),[GroovyTemplateAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java),[VelocityAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfiguration.java)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.9 Velocity.md" "b/IX. \342\200\230How-to\342\200\231 guides/71.9 Velocity.md" new file mode 100644 index 00000000..bd951db2 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/71.9 Velocity.md" @@ -0,0 +1,14 @@ +###71.9 Velocity + +默认情况下,Spring Boot会配置一个`VelocityViewResolver`,如果需要的是`VelocityLayoutViewResolver`,你可以自己创建一个名为`velocityViewResolver`的bean。你也可以将`VelocityProperties`实例注入到自定义视图解析器以获取基本的默认设置。 + +以下示例使用`VelocityLayoutViewResolver`替换自动配置的velocity视图解析器,并自定义`layoutUrl`及应用所有自动配置的属性: +```java +@Bean(name = "velocityViewResolver") +public VelocityLayoutViewResolver velocityViewResolver(VelocityProperties properties) { + VelocityLayoutViewResolver resolver = new VelocityLayoutViewResolver(); + properties.applyToViewResolver(resolver); + resolver.setLayoutUrl("layout/default.vm"); + return resolver; +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72. HTTP clients.md" "b/IX. \342\200\230How-to\342\200\231 guides/72. HTTP clients.md" new file mode 100644 index 00000000..73729982 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/72. HTTP clients.md" @@ -0,0 +1 @@ +###72. HTTP客户端 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72. Hot swapping.md" "b/IX. \342\200\230How-to\342\200\231 guides/72. Hot swapping.md" deleted file mode 100644 index 7840a721..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72. Hot swapping.md" +++ /dev/null @@ -1 +0,0 @@ -### 72. 热交换 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.1 Configure RestTemplate to use a proxy.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.1 Configure RestTemplate to use a proxy.md" new file mode 100644 index 00000000..3afae617 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/72.1 Configure RestTemplate to use a proxy.md" @@ -0,0 +1,30 @@ +###72.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/72.1. Reload static content.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.1. Reload static content.md" deleted file mode 100644 index e9112799..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.1. Reload static content.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 72.1. 重新加载静态内容 - -Spring Boot有很多用于热加载的选项。使用IDE开发是一个不错的方式,特别是需要调试的时候(所有的现代IDEs都允许重新加载静态资源,通常也支持对变更的Java类进行热交换)。[Maven和Gradle插件](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins)也支持命令行下的静态文件热加载。如果你使用其他高级工具编写css/js,并使用外部的css/js编译器,那你就可以充分利用该功能。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.2. Reload Thymeleaf templates without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.2. Reload Thymeleaf templates without restarting the container.md" deleted file mode 100644 index 19ed9643..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.2. Reload Thymeleaf templates without restarting the container.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 72.2. 在不重启容器的情况下重新加载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/72.3. Reload FreeMarker templates without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.3. Reload FreeMarker templates without restarting the container.md" deleted file mode 100644 index b763cd25..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.3. Reload FreeMarker templates without restarting the container.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 72.3. 在不重启容器的情况下重新加载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/72.4. Reload Groovy templates without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.4. Reload Groovy templates without restarting the container.md" deleted file mode 100644 index 29086415..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.4. Reload Groovy templates without restarting the container.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 72.4. 在不重启容器的情况下重新加载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/72.5. Reload Velocity templates without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.5. Reload Velocity templates without restarting the container.md" deleted file mode 100644 index 6ad934bb..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.5. Reload Velocity templates without restarting the container.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 72.5. 在不重启容器的情况下重新加载Velocity模板 - -如果你正在使用Velocity,那就将`spring.velocity.cache`设置为false。查看[VelocityAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfiguration.java)可以获取其他Velocity自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.6.2. Configuring Spring Loaded for use with Gradle and IntelliJ.md" "b/IX. \342\200\230How-to\342\200\231 guides/72.6.2. Configuring Spring Loaded for use with Gradle and IntelliJ.md" deleted file mode 100644 index c7351c4f..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.6.2. Configuring Spring Loaded for use with Gradle and IntelliJ.md" +++ /dev/null @@ -1,28 +0,0 @@ -### 72.6.2. 使用Gradle和IntelliJ配置Spring Loaded - -如果想将Spring Loaded和Gradle,IntelliJ结合起来,那你需要付出代价。默认情况下,IntelliJ将类编译到一个跟Gradle不同的位置,这会导致Spring Loaded监控失败。 - -为了正确配置IntelliJ,你可以使用`idea` Gradle插件: -```gradle -buildscript { - repositories { jcenter() } - dependencies { - classpath "org.springframework.boot:spring-boot-gradle-plugin:1.3.0.BUILD-SNAPSHOT" - classpath 'org.springframework:springloaded:1.2.0.RELEASE' - } -} - -apply plugin: 'idea' - -idea { - module { - inheritOutputDirs = false - outputDir = file("$buildDir/classes/main/") - } -} - -// ... -``` -**注**:IntelliJ必须配置跟命令行Gradle任务相同的Java版本,并且springloaded必须作为一个buildscript依赖被包含进去。 - -此外,你也可以启用Intellij内部的`Make Project Automatically`,这样不管什么时候只要文件被保存都会自动编译你的代码。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73. Build.md" "b/IX. \342\200\230How-to\342\200\231 guides/73. Build.md" deleted file mode 100644 index b46b2783..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73. Build.md" +++ /dev/null @@ -1 +0,0 @@ -### 73. 构建 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73. Logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/73. Logging.md" new file mode 100644 index 00000000..190311b9 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73. Logging.md" @@ -0,0 +1,17 @@ +### 73. 日志 + +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/73.1 Configure Logback for logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.1 Configure Logback for logging.md" new file mode 100644 index 00000000..cf932bd2 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.1 Configure Logback for logging.md" @@ -0,0 +1,19 @@ +### 73.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/73.1. Customize dependency versions with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.1. Customize dependency versions with Maven.md" deleted file mode 100644 index fa670f04..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.1. Customize dependency versions with Maven.md" +++ /dev/null @@ -1,11 +0,0 @@ -### 73.1. 使用Maven自定义依赖版本 - -如果你使用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发布都是基于一些特定的第三方依赖集进行设计和测试的,覆盖版本可能导致兼容性问题。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.1.1 Configure logback for file only output.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.1.1 Configure logback for file only output.md" new file mode 100644 index 00000000..f944ffe6 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.1.1 Configure logback for file only output.md" @@ -0,0 +1,18 @@ +###73.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/73.2 Configure Log4j for logging.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.2 Configure Log4j for logging.md" new file mode 100644 index 00000000..8619e48c --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.2 Configure Log4j for logging.md" @@ -0,0 +1,27 @@ +### 73.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/73.2.1 Use YAML or JSON to configure Log4j 2.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.2.1 Use YAML or JSON to configure Log4j 2.md" new file mode 100644 index 00000000..420a124b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/73.2.1 Use YAML or JSON to configure Log4j 2.md" @@ -0,0 +1,8 @@ +### 73.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/73.3. Create an additional executable JAR.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.3. Create an additional executable JAR.md" deleted file mode 100644 index c6e26724..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.3. Create an additional executable JAR.md" +++ /dev/null @@ -1,26 +0,0 @@ -### 73.3. 创建其他的可执行JAR - -如果你想将自己的项目以library jar的形式被其他项目依赖,并且需要它是一个可执行版本(例如demo),你需要使用略微不同的方式来配置该构建。 - -对于Maven来说,正常的JAR插件和Spring Boot插件都有一个'classifier',你可以添加它来创建另外的JAR。示例如下(使用Spring Boot Starter Parent管理插件版本,其他配置采用默认设置): -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - -``` -上述配置会产生两个jars,默认的一个和使用带有classifier 'exec'的Boot插件构建的可执行的一个。 - -对于Gradle用户来说,步骤类似。示例如下: -```gradle -bootRepackage { - classifier = 'exec' -} -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.6. Remote debug a Spring Boot application started with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.6. Remote debug a Spring Boot application started with Maven.md" deleted file mode 100644 index 2311674a..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.6. Remote debug a Spring Boot application started with Maven.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.6. 远程调试一个使用Maven启动的Spring Boot项目 - -想要为使用Maven启动的Spring Boot应用添加一个远程调试器,你可以使用[mave插件](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/)的jvmArguments属性。详情参考[示例](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/examples/run-debug.html)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.8. Build an executable archive with Ant.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.8. Build an executable archive with Ant.md" deleted file mode 100644 index 673b2b12..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.8. Build an executable archive with Ant.md" +++ /dev/null @@ -1,33 +0,0 @@ -### 73.8. 使用Ant构建可执行存档(archive) - -想要使用Ant进行构建,你需要抓取依赖,编译,然后像通常那样创建一个jar或war存档。为了让它可以执行: - -1. 使用合适的启动器配置`Main-Class`,比如对于jar文件使用JarLauncher,然后将其他需要的属性以manifest实体指定,主要是一个`Start-Class`。 -2. 将运行时依赖添加到一个内嵌的'lib'目录(对于jar),`provided`(内嵌容器)依赖添加到一个内嵌的`lib-provided`目录。记住***不要***压缩存档中的实体。 -3. 在存档的根目录添加`spring-boot-loader`类(这样`Main-Class`就可用了)。 - -示例: -```xml - - - - - - - - - - - - - - -``` -该Actuator示例中有一个build.xml文件,可以使用以下命令来运行: -```shell -$ ant -lib /ivy-2.2.jar -``` -在上述操作之后,你可以使用以下命令运行该应用: -```shell -$ java -jar target/*.jar -``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.9. How to use Java 6.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.9. How to use Java 6.md" deleted file mode 100644 index a46a496e..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.9. How to use Java 6.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.9. 如何使用Java6 - -如果想在Java6环境中使用Spring Boot,你需要改变一些配置。具体的变化取决于你应用的功能。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.9.1. Embedded servlet container compatibility.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.9.1. Embedded servlet container compatibility.md" deleted file mode 100644 index 88867de6..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.9.1. Embedded servlet container compatibility.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.9.1. 内嵌Servlet容器兼容性 - -如果你在使用Boot的内嵌Servlet容器,你需要使用一个兼容Java6的容器。Tomcat 7和Jetty 8都是Java 6兼容的。具体参考[Section 63.15, “Use Tomcat 7”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-tomcat-7)和[Section 63.16, “Use Jetty 8”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-jetty-8)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.9.2. JTA API compatibility.md" "b/IX. \342\200\230How-to\342\200\231 guides/73.9.2. JTA API compatibility.md" deleted file mode 100644 index 0f9a4505..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.9.2. JTA API compatibility.md" +++ /dev/null @@ -1,3 +0,0 @@ -### 73.9.2. JTA API兼容性 - -Java事务API自身并不要求Java 7,而是官方的API jar包含的已构建类要求Java 7。如果你正在使用JTA,那么你需要使用能够在Java 6工作的构建版本替换官方的JTA 1.2 API jar。为了完成该操作,你需要排除任何对`javax.transaction:javax.transaction-api`的传递依赖,并使用`org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:1.0.0.Final`依赖替换它们。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74. Data Access.md" "b/IX. \342\200\230How-to\342\200\231 guides/74. Data Access.md" new file mode 100644 index 00000000..64062f0e --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74. Data Access.md" @@ -0,0 +1 @@ +### 74. 数据访问 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74. Traditional deployment.md" "b/IX. \342\200\230How-to\342\200\231 guides/74. Traditional deployment.md" deleted file mode 100644 index 879f61e3..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74. Traditional deployment.md" +++ /dev/null @@ -1 +0,0 @@ -### 74. 传统部署 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.1 Configure a DataSource.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.1 Configure a DataSource.md" new file mode 100644 index 00000000..d097f718 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.1 Configure a DataSource.md" @@ -0,0 +1,27 @@ +### 74.1 配置数据源 + +自定义`DataSource`类型的`@Bean`可以覆盖默认设置,正如[Section 24.7.1, “Third-party configuration”](../IV. Spring Boot features/24.7.1. Third-party configuration.md)解释的那样,你可以很轻松的将它跟一系列`Environment`属性绑定: +```java +@Bean +@ConfigurationProperties(prefix="datasource.fancy") +public DataSource dataSource() { + return new FancyDataSource(); +} +``` +```properties +datasource.fancy.jdbcUrl=jdbc:h2:mem:mydb +datasource.fancy.username=sa +datasource.fancy.poolSize=30 +``` +Spring Boot也提供了一个工具类`DataSourceBuilder`用来创建标准的数据源。如果需要重用`DataSourceProperties`的配置,你可以从它初始化一个`DataSourceBuilder`: +```java +@Bean +@ConfigurationProperties(prefix="datasource.mine") +public DataSource dataSource(DataSourceProperties properties) { + return properties.initializeDataSourceBuilder() + // additional customizations + .build(); +} +``` +在此场景中,你保留了通过Spring Boot暴露的标准属性,通过添加`@ConfigurationProperties`,你可以暴露在相应的命命名空间暴露其他特定实现的配置, +具体详情可参考'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/v1.4.1.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/74.10 Expose Spring Data repositories as REST endpoint.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.10 Expose Spring Data repositories as REST endpoint.md" new file mode 100644 index 00000000..c32e0249 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.10 Expose Spring Data repositories as REST endpoint.md" @@ -0,0 +1,3 @@ +### 74.10 将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)提供其他定制。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.11 Configure a component that is used by JPA.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.11 Configure a component that is used by JPA.md" new file mode 100644 index 00000000..9a8cd4f0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.11 Configure a component that is used by JPA.md" @@ -0,0 +1,20 @@ +###74.11 配置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/67.2. Configure Two DataSources.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.2 Configure Two DataSources.md" similarity index 54% rename from "IX. \342\200\230How-to\342\200\231 guides/67.2. Configure Two DataSources.md" rename to "IX. \342\200\230How-to\342\200\231 guides/74.2 Configure Two DataSources.md" index ea1545a7..c76273aa 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.2. Configure Two DataSources.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.2 Configure Two DataSources.md" @@ -1,6 +1,6 @@ -### 67.2. 配置两个数据源 +### 74.2 配置两个数据源 -创建多个数据源和创建第一个工作都是一样的。如果使用针对JDBC或JPA的默认自动配置,你可能想要将其中一个设置为`@Primary`(然后它就能被任何`@Autowired`注入获取)。 +创建多个数据源和创建一个工作都是一样的,如果使用JDBC或JPA的默认自动配置,你需要将其中一个设置为`@Primary`(然后它就能被任何`@Autowired`注入获取)。 ```java @Bean @Primary diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.2. Create a deployable war file for older servlet containers.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.2. Create a deployable war file for older servlet containers.md" deleted file mode 100644 index 87193b3a..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.2. Create a deployable war file for older servlet containers.md" +++ /dev/null @@ -1,4 +0,0 @@ - -### 74.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/74.3 Use Spring Data repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.3 Use Spring Data repositories.md" new file mode 100644 index 00000000..a70b8d84 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.3 Use Spring Data repositories.md" @@ -0,0 +1,7 @@ +### 74.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/v1.4.1.RELEASE/spring-boot-samples/spring-boot-sample-data-jpa)或[Mongodb sample](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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/74.3. Convert an existing application to Spring Boot.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.3. Convert an existing application to Spring Boot.md" deleted file mode 100644 index 80471222..00000000 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.3. Convert an existing application to Spring Boot.md" +++ /dev/null @@ -1,49 +0,0 @@ -### 74.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的`@EnableAutoConfiguration`注解。示例: -```java -@Configuration -@EnableAutoConfiguration -@ComponentScan -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 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可以通过`@Import`添加到你的Application中。简单的情况下,大量使用注解配置可以在几行内定义`@Bean`定义。 - -一旦war可以使用,我们就通过添加一个main方法到Application来让它可以执行,比如: -```java -public static void main(String[] args) { - SpringApplication.run(Application.class, args); -} -``` -应用可以划分为多个类别: - -- 没有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/67.4. Separate @Entity definitions from Spring configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.4 Separate @Entity definitions from Spring configuration.md" similarity index 53% rename from "IX. \342\200\230How-to\342\200\231 guides/67.4. Separate @Entity definitions from Spring configuration.md" rename to "IX. \342\200\230How-to\342\200\231 guides/74.4 Separate @Entity definitions from Spring configuration.md" index b1f8140f..9e930a68 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/67.4. Separate @Entity definitions from Spring configuration.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.4 Separate @Entity definitions from Spring configuration.md" @@ -1,6 +1,6 @@ -### 67.4. 从Spring配置分离`@Entity`定义 +### 74.4 从Spring配置分离`@Entity`定义 -Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测你的`@Entity`定义的位置。想要获取更多控制,你可以使用`@EntityScan`注解,比如: +Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测`@Entity`定义的位置,想要获取更多控制可以使用`@EntityScan`注解,比如: ```java @Configuration @EnableAutoConfiguration diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.5 Configure JPA properties.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.5 Configure JPA properties.md" new file mode 100644 index 00000000..a69e2c4e --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.5 Configure JPA properties.md" @@ -0,0 +1,16 @@ +### 74.5 配置JPA属性 + +Spring Data JPA已经提供了一些独立的配置选项(比如,针对SQL日志),并且Spring Boot会暴露它们,针对hibernate的外部配置属性也更多些,最常见的选项如下: +```java +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.example.MyPhysicalNamingStrategy +spring.jpa.database=H2 +spring.jpa.show-sql=true +``` +`ddl-auto`配置是个特殊情况,它的默认设置取决于是否使用内嵌数据库(是则默认值为`create-drop`,否则为`none`)。当本地`EntityManagerFactory`被创建时,所有`spring.jpa.properties.*`属性都被作为正常的JPA属性(去掉前缀)传递进去了。 + +Spring Boot提供一致的命名策略,不管你使用什么Hibernate版本。如果使用Hibernate 4,你可以使用`spring.jpa.hibernate.naming.strategy`进行自定义;Hibernate 5定义一个`Physical`和`Implicit`命名策略:Spring Boot默认配置`SpringPhysicalNamingStrategy`,该实现提供跟Hibernate 4相同的表结构。如果你情愿使用Hibernate 5默认的,可以设置以下属性: +```properties +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl +``` +具体详情可参考[HibernateJpaAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java)和[JpaBaseConfiguration](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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/74.6 Use a custom EntityManagerFactory.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.6 Use a custom EntityManagerFactory.md" new file mode 100644 index 00000000..151d6a74 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.6 Use a custom EntityManagerFactory.md" @@ -0,0 +1,3 @@ +### 74.6 使用自定义EntityManagerFactory + +为了完全控制`EntityManagerFactory`的配置,你需要添加一个名为`entityManagerFactory`的`@Bean`,Spring Boot自动配置会根据是否存在该类型的bean来关闭它的实体管理器(entity manager)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.7 Use Two EntityManagers.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.7 Use Two EntityManagers.md" new file mode 100644 index 00000000..07287436 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.7 Use Two EntityManagers.md" @@ -0,0 +1,46 @@ +### 74.7 使用两个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/74.8 Use a traditional persistence.xml.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.8 Use a traditional persistence.xml.md" new file mode 100644 index 00000000..e527bec6 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.8 Use a traditional persistence.xml.md" @@ -0,0 +1,3 @@ +### 74.8 使用普通的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/74.9 Use Spring Data JPA and Mongo repositories.md" "b/IX. \342\200\230How-to\342\200\231 guides/74.9 Use Spring Data JPA and Mongo repositories.md" new file mode 100644 index 00000000..0348e475 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/74.9 Use Spring Data JPA and Mongo repositories.md" @@ -0,0 +1,7 @@ +### 74.9 使用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/68. Database initialization.md" "b/IX. \342\200\230How-to\342\200\231 guides/75. Database initialization.md" similarity index 84% rename from "IX. \342\200\230How-to\342\200\231 guides/68. Database initialization.md" rename to "IX. \342\200\230How-to\342\200\231 guides/75. Database initialization.md" index b1271a09..5b809638 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/68. Database initialization.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/75. Database initialization.md" @@ -1,3 +1,3 @@ -### 68. 数据库初始化 +### 75. 数据库初始化 一个数据库可以使用不同的方式进行初始化,这取决于你的技术栈。或者你可以手动完成该任务,只要数据库是单独的过程。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.1 Initialize a database using JPA.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.1 Initialize a database using JPA.md" new file mode 100644 index 00000000..bb57052c --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.1 Initialize a database using JPA.md" @@ -0,0 +1,6 @@ +### 75.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/75.2 Initialize a database using Hibernate.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.2 Initialize a database using Hibernate.md" new file mode 100644 index 00000000..d9533007 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.2 Initialize a database using Hibernate.md" @@ -0,0 +1,5 @@ +### 75.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`,或使用其他机制初始化数据库。 + +此外,启动时处于classpath根目录下的`import.sql`文件会被执行。这在demos或测试时很有用,但在生产环境中你可能不期望这样。这是Hibernate的特性,和Spring没有一点关系。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.3 Initialize a database using Spring JDBC.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.3 Initialize a database using Spring JDBC.md" new file mode 100644 index 00000000..9a8ad530 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.3 Initialize a database using Spring JDBC.md" @@ -0,0 +1,7 @@ +### 75.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/68.4. Initialize a Spring Batch database.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.4 Initialize a Spring Batch database.md" similarity index 92% rename from "IX. \342\200\230How-to\342\200\231 guides/68.4. Initialize a Spring Batch database.md" rename to "IX. \342\200\230How-to\342\200\231 guides/75.4 Initialize a Spring Batch database.md" index bd8c40d1..2560d126 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/68.4. Initialize a Spring Batch database.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.4 Initialize a Spring Batch database.md" @@ -1,3 +1,3 @@ -### 68.4. 初始化Spring Batch数据库 +### 75.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/75.5 Use a higher level database migration tool.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.5 Use a higher level database migration tool.md" new file mode 100644 index 00000000..f823c02d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.5 Use a higher level database migration tool.md" @@ -0,0 +1,3 @@ +### 75.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/75.5.1 Execute Flyway database migrations on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.5.1 Execute Flyway database migrations on startup.md" new file mode 100644 index 00000000..0a5c22b9 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.5.1 Execute Flyway database migrations on startup.md" @@ -0,0 +1,9 @@ +### 75.5.1 启动时执行Flyway数据库迁移 + +想要在启动时自动运行Flyway数据库迁移,需要将`org.flywaydb:flyway-core`添加到你的classpath下。 + +迁移是一些`V__.sql`格式的脚本(``是一个下划线分割的版本号,比如'1'或'2_1')。默认情况下,它们存放在`classpath:db/migration`文件夹中,但你可以使用`flyway.locations`(一个列表)改变它。详情可参考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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationStrategy.java)的`@Bean`。 + +默认情况下,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),你可以作为参考。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/75.5.2 Execute Liquibase database migrations on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/75.5.2 Execute Liquibase database migrations on startup.md" new file mode 100644 index 00000000..97f729d7 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/75.5.2 Execute Liquibase database migrations on startup.md" @@ -0,0 +1,8 @@ +### 75.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/v1.4.1.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java)获取可用配置,比如上下文,默认schema等。 + + +这里有个[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/76. Batch applications.md" "b/IX. \342\200\230How-to\342\200\231 guides/76. Batch applications.md" new file mode 100644 index 00000000..d922a10d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76. Batch applications.md" @@ -0,0 +1 @@ +### 76. 批处理应用 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/76.1 Execute Spring Batch jobs on startup.md" "b/IX. \342\200\230How-to\342\200\231 guides/76.1 Execute Spring Batch jobs on startup.md" new file mode 100644 index 00000000..184ac1f8 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/76.1 Execute Spring Batch jobs on startup.md" @@ -0,0 +1,9 @@ +### 76.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/77. Actuator.md" "b/IX. \342\200\230How-to\342\200\231 guides/77. Actuator.md" new file mode 100644 index 00000000..2d2f8452 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/77. Actuator.md" @@ -0,0 +1 @@ +### 77. 执行器(Actuator) diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.1 Change the HTTP port or address of the actuator endpoints.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.1 Change the HTTP port or address of the actuator endpoints.md" new file mode 100644 index 00000000..8611eb02 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/77.1 Change the HTTP port or address of the actuator endpoints.md" @@ -0,0 +1,6 @@ + +### 77.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 47.3, “Customizing the management server port”](../V. Spring Boot Actuator/47.3 Customizing the management server port.md)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/77.2 Customize the \342\200\230whitelabel\342\200\231 error page.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.2 Customize the \342\200\230whitelabel\342\200\231 error page.md" new file mode 100644 index 00000000..a9c545b3 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/77.2 Customize the \342\200\230whitelabel\342\200\231 error page.md" @@ -0,0 +1,5 @@ +### 77.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/77.3 Actuator and Jersey.md" "b/IX. \342\200\230How-to\342\200\231 guides/77.3 Actuator and Jersey.md" new file mode 100644 index 00000000..87d30fa3 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/77.3 Actuator and Jersey.md" @@ -0,0 +1,3 @@ +###77.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/78. Security.md" "b/IX. \342\200\230How-to\342\200\231 guides/78. Security.md" new file mode 100644 index 00000000..e39c655b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/78. Security.md" @@ -0,0 +1 @@ +### 78. 安全 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/71.1. Switch off the Spring Boot security configuration.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.1 Switch off the Spring Boot security configuration.md" similarity index 82% rename from "IX. \342\200\230How-to\342\200\231 guides/71.1. Switch off the Spring Boot security configuration.md" rename to "IX. \342\200\230How-to\342\200\231 guides/78.1 Switch off the Spring Boot security configuration.md" index bcc87a8f..9c826f7a 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.1. Switch off the Spring Boot security configuration.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/78.1 Switch off the Spring Boot security configuration.md" @@ -1,4 +1,3 @@ +### 78.1 关闭Spring Boot安全配置 -### 71.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章节)。 +不管你在应用的什么地方定义了一个使用`@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/71.2. Change the AuthenticationManager and add user accounts.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.2 Change the AuthenticationManager and add user accounts.md" similarity index 54% rename from "IX. \342\200\230How-to\342\200\231 guides/71.2. Change the AuthenticationManager and add user accounts.md" rename to "IX. \342\200\230How-to\342\200\231 guides/78.2 Change the AuthenticationManager and add user accounts.md" index a71b6cb4..ed030e22 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/71.2. Change the AuthenticationManager and add user accounts.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/78.2 Change the AuthenticationManager and add user accounts.md" @@ -1,8 +1,8 @@ -### 71.2. 改变AuthenticationManager并添加用户账号 +### 78.2 改变AuthenticationManager并添加用户账号 -如果你提供了一个AuthenticationManager类型的`@Bean`,那么默认的就不会被创建了,所以你可以获得Spring Security可用的全部特性(比如,[不同的认证选项](http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authentication))。 +如果你提供了一个`AuthenticationManager`类型的`@Bean`,那么默认的就不会被创建了,所以你可以获得Spring Security可用的全部特性(比如,[不同的认证选项](http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authentication))。 -Spring Security也提供了一个方便的AuthenticationManagerBuilder,可用于构建具有常见选项的AuthenticationManager。在一个webapp中,推荐将它注入到WebSecurityConfigurerAdapter的一个void方法中,比如: +Spring Security也提供了一个方便的`AuthenticationManagerBuilder`,用于构建具有常见选项的`AuthenticationManager`。在一个webapp中,推荐将它注入到`WebSecurityConfigurerAdapter`的一个void方法中,比如: ```java @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @@ -18,7 +18,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { ``` 如果把它放到一个内部类或一个单独的类中,你将得到最好的结果(也就是不跟很多其他`@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)可能是个不错的选择,比如: +如果你遇到了实例化问题(比如,使用JDBC或JPA进行用户详细信息的存储),那将`AuthenticationManagerBuilder`回调提取到一个`GlobalAuthenticationConfigurerAdapter`(放到`init()`方法内以防其他地方也需要authentication manager)可能是个不错的选择,比如: ```java @Configuration public class AuthenticationManagerConfiguration extends diff --git "a/IX. \342\200\230How-to\342\200\231 guides/78.3 Enable HTTPS when running behind a proxy server.md" "b/IX. \342\200\230How-to\342\200\231 guides/78.3 Enable HTTPS when running behind a proxy server.md" new file mode 100644 index 00000000..f2203e59 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/78.3 Enable HTTPS when running behind a proxy server.md" @@ -0,0 +1,12 @@ +### 78.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 +``` +(这些属性出现一个就会开启该功能,或者你可以通过添加一个`TomcatEmbeddedServletContainerFactory` 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/79. Hot swapping.md" "b/IX. \342\200\230How-to\342\200\231 guides/79. Hot swapping.md" new file mode 100644 index 00000000..45d16f57 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79. Hot swapping.md" @@ -0,0 +1 @@ +### 79. 热交换 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.1 Reload static content.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.1 Reload static content.md" new file mode 100644 index 00000000..ab3338ec --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.1 Reload static content.md" @@ -0,0 +1,8 @@ +### 79.1 重新加载静态内容 + +Spring Boot有很多用于热加载的选项,不过推荐使用[spring-boot-devtools](../III. Using Spring Boot/20. Developer tools.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/79.2. Reload templates without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.2. Reload templates without restarting the container.md" new file mode 100644 index 00000000..821a3f0a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.2. Reload templates without restarting the container.md" @@ -0,0 +1,3 @@ +###79.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/79.2.1 Thymeleaf templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.2.1 Thymeleaf templates.md" new file mode 100644 index 00000000..c82dff4d --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.2.1 Thymeleaf templates.md" @@ -0,0 +1,3 @@ +### 79.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/79.2.2 FreeMarker templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.2.2 FreeMarker templates.md" new file mode 100644 index 00000000..3855dacb --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.2.2 FreeMarker templates.md" @@ -0,0 +1,3 @@ +### 79.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/79.2.3 Groovy templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.2.3 Groovy templates.md" new file mode 100644 index 00000000..d5421877 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.2.3 Groovy templates.md" @@ -0,0 +1,3 @@ +### 79.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/79.2.4 Velocity templates.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.2.4 Velocity templates.md" new file mode 100644 index 00000000..ac6642c8 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.2.4 Velocity templates.md" @@ -0,0 +1,3 @@ +### 79.2.4 Velocity模板 + +如果你正在使用Velocity,那就将`spring.velocity.cache`设置为`false`,查看[VelocityAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfiguration.java)可以获取其他Velocity自定义选项。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/79.3 Fast application restarts.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.3 Fast application restarts.md" new file mode 100644 index 00000000..37dbb2f0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.3 Fast application restarts.md" @@ -0,0 +1,3 @@ +###79.3 应用快速重启 + +`spring-boot-devtools`模块包括应用自动重启支持,虽然没有其他技术快,比如[JRebel](http://zeroturnaround.com/software/jrebel/)或[Spring Loaded](https://github.com/spring-projects/spring-loaded),但比"冷启动"快。在研究其他复杂重启选项时,你最好自己先试下,更多详情可参考[Chapter 20, Developer tools](../III. Using Spring Boot/20. Developer tools.md)章节。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.6. Reload Java classes without restarting the container.md" "b/IX. \342\200\230How-to\342\200\231 guides/79.4 Reload Java classes without restarting the container.md" similarity index 51% rename from "IX. \342\200\230How-to\342\200\231 guides/72.6. Reload Java classes without restarting the container.md" rename to "IX. \342\200\230How-to\342\200\231 guides/79.4 Reload Java classes without restarting the container.md" index eadf01e1..558c4c6a 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.6. Reload Java classes without restarting the container.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.4 Reload Java classes without restarting the container.md" @@ -1,5 +1,5 @@ -### 72.6. 在不重启容器的情况下重新加载Java类 +### 79.4 在不重启容器的情况下重新加载Java类 现代IDEs(Eclipse, IDEA等)都支持字节码的热交换,所以如果你做了一个没有影响类或方法签名的改变,它会利索地重新加载并没有任何影响。 -[Spring Loaded](https://github.com/spring-projects/spring-loaded)在这方面走的更远,它能够重新加载方法签名改变的类定义。如果对它进行一些自定义配置可以强制ApplicationContext刷新自己(但没有通用的机制来确保这对一个运行中的应用总是安全的,所以它可能只是一个开发时间的技巧)。 +[Spring Loaded](https://github.com/spring-projects/spring-loaded)在这方面走的更远,它能够重新加载方法签名改变的类定义,如果对它进行一些自定义配置可以强制`ApplicationContext`刷新自己(但没有通用的机制来确保这对一个运行中的应用总是安全的,所以它可能只是一个开发时的技巧)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/72.6.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" similarity index 57% rename from "IX. \342\200\230How-to\342\200\231 guides/72.6.1. Configuring Spring Loaded for use with Maven.md" rename to "IX. \342\200\230How-to\342\200\231 guides/79.4.1 Configuring Spring Loaded for use with Maven.md" index ec1206b0..5628b90d 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/72.6.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" @@ -1,6 +1,6 @@ -### 72.6.1. 使用Maven配置Spring Loaded +### 79.4.1 使用Maven配置Spring Loaded -为了在Maven命令行下使用Spring Loaded,你只需将它作为一个依赖添加到Spring Boot插件声明中即可,比如: +为了在Maven命令行下使用Spring Loaded,你只需将它作为依赖添加到Spring Boot插件声明中即可,比如: ```xml org.springframework.boot @@ -14,4 +14,4 @@ ``` -正常情况下,这在Eclipse和IntelliJ中工作的相当漂亮,只要它们有相应的,和Maven默认一致的构建配置(Eclipse m2e对此支持的更好,开箱即用)。 +正常情况下,这在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" new file mode 100644 index 00000000..a258c30a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/79.4.2 Configuring Spring Loaded for use with Gradle and IntelliJ.md" @@ -0,0 +1,28 @@ +### 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:1.4.1.RELEASE" + 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/80. Build.md" "b/IX. \342\200\230How-to\342\200\231 guides/80. Build.md" new file mode 100644 index 00000000..1634e8ab --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80. Build.md" @@ -0,0 +1 @@ +### 80. 构建 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.1 Generate build information.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.1 Generate build information.md" new file mode 100644 index 00000000..16d2d071 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.1 Generate build information.md" @@ -0,0 +1,41 @@ +###80.1 生成构建信息 + +Maven和Gradle都支持产生包含项目版本,坐标,名称的构建信息,该插件可以通过配置添加其他属性。当这些文件出现时,Spring Boot自动配置一个`BuildProperties` bean。 + +为了让Maven生成构建信息,你需要为`build-info` goal添加一个execution: +```xml + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.1.RELEASE + + + + build-info + + + + + + +``` +**注** 更多详情查看[Spring Boot Maven插件文档](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/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/80.10 Build an executable archive from Ant without using spring-boot-antlib.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.10 Build an executable archive from Ant without using spring-boot-antlib.md" new file mode 100644 index 00000000..e4a018c0 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.10 Build an executable archive from Ant without using spring-boot-antlib.md" @@ -0,0 +1,42 @@ +### 80.10 使用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/v1.4.1.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/80.11 How to use Java 6.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.11 How to use Java 6.md" new file mode 100644 index 00000000..df83b1bb --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.11 How to use Java 6.md" @@ -0,0 +1,3 @@ +### 80.11 如何使用Java6 + +如果想在Java6环境中使用Spring Boot,你需要改变一些配置,具体的改变取决于你应用的功能。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.11.1 Embedded servlet container compatibility.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.11.1 Embedded servlet container compatibility.md" new file mode 100644 index 00000000..c650a896 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.11.1 Embedded servlet container compatibility.md" @@ -0,0 +1,3 @@ +### 80.11.1 内嵌Servlet容器兼容性 + +如果你在使用Boot的内嵌Servlet容器,你需要使用一个兼容Java6的容器。Tomcat 7和Jetty 8都是Java 6兼容的。具体参考[Section 70.16 使用Tomcat 7.x或8.0](../IX. ‘How-to’ guides/70.16 Use Tomcat 7.x or 8.0.md)和[Section 70.18 使用Jetty 8](../IX. ‘How-to’ guides/70.18 Use Jetty 8.md)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.11.2 Jackson.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.11.2 Jackson.md" new file mode 100644 index 00000000..53796a70 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.11.2 Jackson.md" @@ -0,0 +1,3 @@ +###80.11.2 Jackson + +Jackson 2.7及以后版本需要Java 7,如果想要在Java 6环境使用Jackson,你需要降级使用Jackson 2.6。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.11.3 JTA API compatibility.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.11.3 JTA API compatibility.md" new file mode 100644 index 00000000..02e6cff5 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.11.3 JTA API compatibility.md" @@ -0,0 +1,3 @@ +###80.11.3 JTA API兼容性 + +虽然Java Transaction API自身不要求Java 7,但官方API jar包含的已构建类需要Java 7。如果正在使用JTA,你需要使用能够在Java 6环境工作的jar替换官方的JTA 1.2 API jar。想要实现这样的效果,你需要排除任何`javax.transaction:javax.transaction-api`依赖,并使用`org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:1.0.0.Final`替换它。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.2 Generate git information.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.2 Generate git information.md" new file mode 100644 index 00000000..91c3f80f --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.2 Generate git information.md" @@ -0,0 +1,19 @@ +###80.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.6" +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.3 Customize dependency versions.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.3 Customize dependency versions.md" new file mode 100644 index 00000000..4d0684a1 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.3 Customize dependency versions.md" @@ -0,0 +1,17 @@ +### 80.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发布都是基于一些特定的第三方依赖集进行设计和测试的,覆盖版本可能导致兼容性问题。 + +Gradle中为了覆盖依赖版本,你需要指定如下所示的version: +```gradle +ext['slf4j.version'] = '1.7.5' +``` +更多详情查看[Gradle Dependency Management插件文档](https://github.com/spring-gradle-plugins/dependency-management-plugin)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.2. Create an executable JAR with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.4 Create an executable JAR with Maven.md" similarity index 67% rename from "IX. \342\200\230How-to\342\200\231 guides/73.2. Create an executable JAR with Maven.md" rename to "IX. \342\200\230How-to\342\200\231 guides/80.4 Create an executable JAR with Maven.md" index cdf30456..99310955 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.2. Create an executable JAR with Maven.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.4 Create an executable JAR with Maven.md" @@ -1,6 +1,6 @@ -### 73.2. 使用Maven创建可执行JAR +### 80.4 使用Maven创建可执行JAR -`spring-boot-maven-plugin`能够用来创建可执行的'胖'JAR。如果你正在使用`spring-boot-starter-parent` POM,你可以简单地声明该插件,然后你的jar将被重新打包: +`spring-boot-maven-plugin`能够用来创建可执行的'胖'JAR。如果正在使用`spring-boot-starter-parent` POM,你可以简单地声明该插件,然后你的jar将被重新打包: ```xml @@ -18,7 +18,7 @@ org.springframework.boot spring-boot-maven-plugin - 1.3.0.BUILD-SNAPSHOT + 1.4.1.RELEASE @@ -30,4 +30,4 @@ ``` -查看[插件文档](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/usage.html)获取详细的用例。 +查看[插件文档](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/maven-plugin/usage.html)获取详细的用例。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.5 Use a Spring Boot application as a dependency.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.5 Use a Spring Boot application as a dependency.md" new file mode 100644 index 00000000..a47c7693 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.5 Use a Spring Boot application as a dependency.md" @@ -0,0 +1,28 @@ +###80.5 将Spring Boot应用作为依赖 + +跟war包一样,Spring Boot应用不是用来作为依赖的。如果你的应用包含需要跟其他项目共享的类,最好的方式是将代码放到单独的模块,然后其他项目及你的应用都可以依赖该模块。 + +如果不能按照上述推荐的方式重新组织代码,你需要配置Spring Boot的Maven和Gradle插件去产生一个单独的artifact,以适合于作为依赖。可执行存档不能用于依赖,因为[可执行jar格式](http://docs.spring.io/spring-boot/docs/1.4.1.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 + + + + +``` +使用Gradle可以添加以下配置: +```gradle +bootRepackage { + classifier = 'exec' +} +``` diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.4. Extract specific libraries when an executable jar runs.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.6 Extract specific libraries when an executable jar runs.md" similarity index 93% rename from "IX. \342\200\230How-to\342\200\231 guides/73.4. Extract specific libraries when an executable jar runs.md" rename to "IX. \342\200\230How-to\342\200\231 guides/80.6 Extract specific libraries when an executable jar runs.md" index 06f0ec2d..1ce02dcc 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.4. Extract specific libraries when an executable jar runs.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.6 Extract specific libraries when an executable jar runs.md" @@ -1,4 +1,4 @@ -### 73.4. 在可执行jar运行时提取特定的版本 +### 80.6 在可执行jar运行时提取特定的版本 在一个可执行jar中,为了运行,多数内嵌的库不需要拆包(unpacked),然而有一些库可能会遇到问题。例如,JRuby包含它自己的内嵌jar,它假定`jruby-complete.jar`本身总是能够直接作为文件访问的。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.5. Create a non-executable JAR with exclusions.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.7 Create a non-executable JAR with exclusions.md" similarity index 86% rename from "IX. \342\200\230How-to\342\200\231 guides/73.5. Create a non-executable JAR with exclusions.md" rename to "IX. \342\200\230How-to\342\200\231 guides/80.7 Create a non-executable JAR with exclusions.md" index 57ec974c..010e5312 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.5. Create a non-executable JAR with exclusions.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.7 Create a non-executable JAR with exclusions.md" @@ -1,6 +1,6 @@ -### 73.5. 使用排除创建不可执行的JAR +### 80.7 使用排除创建不可执行的JAR -如果你构建的产物既有可执行的jar和非可执行的jar,那你常常需要为可执行的版本添加额外的配置文件,而这些文件在一个library jar中是不需要的。比如,application.yml配置文件可能需要从非可执行的JAR中排除。 +如果你构建的产物既有可执行的jar和非可执行的jar,那你常常需要为可执行的版本添加额外的配置文件,而这些文件在一个library jar中是不需要的。比如,`application.yml`配置文件可能需要从非可执行的JAR中排除。 下面是如何在Maven中实现: ```xml @@ -44,7 +44,7 @@ ``` -在Gradle中,你可以使用标准任务的DSL(领域特定语言)特性创建一个新的JAR存档,然后在bootRepackage任务中使用withJarTask属性添加对它的依赖: +在Gradle中,你可以使用标准任务的DSL(领域特定语言)特性创建一个新的JAR存档,然后在`bootRepackage`任务中使用`withJarTask`属性添加对它的依赖: ```gradle jar { baseName = 'spring-boot-sample-profile' diff --git "a/IX. \342\200\230How-to\342\200\231 guides/80.8 Remote debug a Spring Boot application started with Maven.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.8 Remote debug a Spring Boot application started with Maven.md" new file mode 100644 index 00000000..3df236ed --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.8 Remote debug a Spring Boot application started with Maven.md" @@ -0,0 +1,3 @@ +### 80.8 远程调试使用Maven启动的Spring Boot项目 + +想要为使用Maven启动的Spring Boot应用添加一个远程调试器,你可以使用[mave插件](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/maven-plugin/)的jvmArguments属性,详情参考[示例](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/maven-plugin/examples/run-debug.html)。 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/73.7. Remote debug a Spring Boot application started with Gradle.md" "b/IX. \342\200\230How-to\342\200\231 guides/80.9 Remote debug a Spring Boot application started with Gradle.md" similarity index 67% rename from "IX. \342\200\230How-to\342\200\231 guides/73.7. Remote debug a Spring Boot application started with Gradle.md" rename to "IX. \342\200\230How-to\342\200\231 guides/80.9 Remote debug a Spring Boot application started with Gradle.md" index d8f3152c..78df0ba9 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/73.7. Remote debug a Spring Boot application started with Gradle.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/80.9 Remote debug a Spring Boot application started with Gradle.md" @@ -1,6 +1,6 @@ -### 73.7. 远程调试一个使用Gradle启动的Spring Boot项目 +### 80.9 远程调试使用Gradle启动的Spring Boot项目 -想要为使用Gradle启动的Spring Boot应用添加一个远程调试器,你可以使用build.gradle的applicationDefaultJvmArgs属性或`--debug-jvm`命令行选项。 +想要为使用Gradle启动的Spring Boot应用添加一个远程调试器,你可以使用`build.gradle`的`applicationDefaultJvmArgs`属性或`--debug-jvm`命令行选项。 build.gradle: ```gradle diff --git "a/IX. \342\200\230How-to\342\200\231 guides/81. Traditional deployment.md" "b/IX. \342\200\230How-to\342\200\231 guides/81. Traditional deployment.md" new file mode 100644 index 00000000..1b64431a --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/81. Traditional deployment.md" @@ -0,0 +1 @@ +### 81. 传统部署 diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.1. Create a deployable war file.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.1 Create a deployable war file.md" similarity index 50% rename from "IX. \342\200\230How-to\342\200\231 guides/74.1. Create a deployable war file.md" rename to "IX. \342\200\230How-to\342\200\231 guides/81.1 Create a deployable war file.md" index ea23bfd7..07e181fd 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.1. Create a deployable war file.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/81.1 Create a deployable war file.md" @@ -1,6 +1,6 @@ -### 74.1. 创建一个可部署的war文件 +### 81.1 创建可部署的war文件 -产生一个可部署war包的第一步是提供一个SpringBootServletInitializer子类,并覆盖它的configure方法。这充分利用了Spring框架对Servlet 3.0的支持,并允许你在应用通过servlet容器启动时配置它。通常,你只需把应用的主类改为继承SpringBootServletInitializer即可: +产生一个可部署war包的第一步是提供一个`SpringBootServletInitializer`子类,并覆盖它的`configure`方法,这充分利用了Spring框架对Servlet 3.0的支持,并允许你在应用通过servlet容器启动时配置它。通常,你只需把应用的主类改为继承`SpringBootServletInitializer`即可: ```java @SpringBootApplication public class Application extends SpringBootServletInitializer { @@ -16,15 +16,15 @@ public class Application extends SpringBootServletInitializer { } ``` -下一步是更新你的构建配置,这样你的项目将产生一个war包而不是jar包。如果你使用Maven,并使用`spring-boot-starter-parent`(为了配置Maven的war插件),所有你需要做的就是更改pom.xml的packaging为war: +下一步是更新你的构建配置,这样你的项目将产生一个war包而不是jar包。如果你使用Maven,并使用`spring-boot-starter-parent`(为了配置Maven的war插件),所有你需要做的就是更改`pom.xml`的打包方式为`war`: ```xml war ``` -如果你使用Gradle,你需要修改build.gradle来将war插件应用到项目上: +如果你使用Gradle,你需要修改`build.gradle`来将war插件应用到项目上: ```gradle apply plugin: 'war' ``` -该过程最后的一步是确保内嵌的servlet容器不能干扰war包将部署的servlet容器。为了达到这个目的,你需要将内嵌容器的依赖标记为provided。 +该过程最后的一步是确保内嵌的servlet容器不能干扰war包将部署的servlet容器。为了达到这个目的,你需要将内嵌容器的依赖标记为`provided`。 如果使用Maven: ```xml @@ -46,6 +46,6 @@ dependencies { // … } ``` -如果你使用[Spring Boot构建工具](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins),将内嵌容器依赖标记为provided将产生一个可执行war包,在`lib-provided`目录有该war包的provided依赖。这意味着,除了部署到servlet容器,你还可以通过使用命令行`java -jar`命令来运行应用。 +如果你使用[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)。 +**注** 查看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/81.2 Create a deployable war file for older servlet containers.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.2 Create a deployable war file for older servlet containers.md" new file mode 100644 index 00000000..3b46052b --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/81.2 Create a deployable war file for older servlet containers.md" @@ -0,0 +1,3 @@ +### 81.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/81.3 Convert an existing application to Spring Boot.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.3 Convert an existing application to Spring Boot.md" new file mode 100644 index 00000000..18d5c371 --- /dev/null +++ "b/IX. \342\200\230How-to\342\200\231 guides/81.3 Convert an existing application to Spring Boot.md" @@ -0,0 +1,49 @@ +### 81.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的`@EnableAutoConfiguration`注解,示例: +```java +@Configuration +@EnableAutoConfiguration +@ComponentScan +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 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`可以通过`@Import`添加到你的`Application`中。简单的情况下,大量使用注解配置可以在几行内定义`@Bean`定义。 + +一旦war可以使用,我们就通过添加一个main方法到`Application`来让它可以执行,比如: +```java +public static void main(String[] args) { + SpringApplication.run(Application.class, args); +} +``` +应用可以划分为多个类别: + +- 没有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/74.4. Deploying a WAR to Weblogic.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.4 Deploying a WAR to Weblogic.md" similarity index 88% rename from "IX. \342\200\230How-to\342\200\231 guides/74.4. Deploying a WAR to Weblogic.md" rename to "IX. \342\200\230How-to\342\200\231 guides/81.4 Deploying a WAR to Weblogic.md" index b543127d..539eef08 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.4. Deploying a WAR to Weblogic.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/81.4 Deploying a WAR to Weblogic.md" @@ -1,6 +1,6 @@ -### 74.4. 部署WAR到Weblogic +### 81.4 部署WAR到Weblogic -想要将Spring Boot应用部署到Weblogic,你需要确保你的servlet初始化器直接实现WebApplicationInitializer(即使你继承的基类已经实现了它)。 +想要将Spring Boot应用部署到Weblogic,你需要确保你的servlet初始化器直接实现`WebApplicationInitializer`(即使你继承的基类已经实现了它)。 一个传统的Weblogic初始化器可能如下所示: ```java diff --git "a/IX. \342\200\230How-to\342\200\231 guides/74.5. Deploying a WAR in an Old (Servlet 2.5) Container.md" "b/IX. \342\200\230How-to\342\200\231 guides/81.5 Deploying a WAR in an Old (Servlet 2.5) Container.md" similarity index 74% rename from "IX. \342\200\230How-to\342\200\231 guides/74.5. Deploying a WAR in an Old (Servlet 2.5) Container.md" rename to "IX. \342\200\230How-to\342\200\231 guides/81.5 Deploying a WAR in an Old (Servlet 2.5) Container.md" index d190bdb4..a2421941 100644 --- "a/IX. \342\200\230How-to\342\200\231 guides/74.5. Deploying a WAR in an Old (Servlet 2.5) Container.md" +++ "b/IX. \342\200\230How-to\342\200\231 guides/81.5 Deploying a WAR in an Old (Servlet 2.5) Container.md" @@ -1,6 +1,6 @@ -### 74.5. 部署WAR到老的(Servlet2.5)容器 +### 81.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应用所具有的。示例: +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 ``` -在该示例中,我们使用一个单一的应用上下文(通过上下文监听器创建的),然后使用一个init参数将它附加到DispatcherServlet。这在一个Spring Boot应用中是很正常的(你通常只有一个应用上下文)。 +在该示例中,我们使用一个单一的应用上下文(通过上下文监听器创建的),然后使用一个init参数将它附加到`DispatcherServlet`。这在一个Spring Boot应用中是很正常的(你通常只有一个应用上下文)。 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 09866bb9..5df2a394 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" @@ -1,7 +1,7 @@ ### How-to指南 -本章节将回答一些常见的"我该怎么做"类型的问题,这些问题在我们使用Spring Boot时经常遇到。这绝不是一个详尽的列表,但它覆盖了很多方面。 +本章节将回答一些常见的"我该怎么做"类型的问题,这些问题在我们使用Spring Boot时经常遇到。这虽然不是一个详尽的列表,但它覆盖了很多方面。 -如果遇到一个特殊的我们没有覆盖的问题,你可能想去查看[stackoverflow.com](http://stackoverflow.com/tags/spring-boot),看是否有人已经给出了答案;这也是一个很好的提新问题的地方(请使用`spring-boot`标签)。 +如果遇到一个特殊的我们没有覆盖的问题,你可以查看[stackoverflow.com](http://stackoverflow.com/tags/spring-boot),看是否已经有人给出了答案;这也是一个很好的提新问题的地方(请使用`spring-boot`标签)。 -我们也乐意扩展本章节;如果想添加一个'how-to',你可以给我们发一个[pull请求](http://github.com/spring-projects/spring-boot/tree/master)。 +我们也乐意扩展本章节;如果想添加一个'how-to',你可以给我们发一个[pull请求](http://github.com/spring-projects/spring-boot/tree/master)。 diff --git a/README.md b/README.md index a773705f..aafb4d99 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Spring-Boot-Reference-Guide Spring Boot Reference Guide中文翻译 -《Spring Boot参考指南》 -说明:本文档针对的是最新版本:[1.3.0.BUILD-SNAPSHOT](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-spring-boot)。 +说明:本文档翻译的版本:[1.4.1.RELEASE](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/)。 如感兴趣,可以star或fork该[仓库](https://github.com/qibaoguang/Spring-Boot-Reference-Guide)! @@ -9,6 +9,15 @@ Github:[https://github.com/qibaoguang/](https://github.com/qibaoguang/) GitBook : [Spring Boot参考指南](https://www.gitbook.com/book/qbgbook/spring-boot-reference-guide-zh/details) +整合示例:[程序猿DD-Spring Boot教程](http://git.oschina.net/didispace/SpringBoot-Learning) + Email:qibaoguang@gmail.com [从这里开始](SUMMARY.md) + +交流群: +* Spring For All社区:470962790 +* spring boot最佳实践2(已满) : 460560346 +* spring boot最佳实践(已满) :445015546 + +**注** 1.3版本查看本仓库的release。 diff --git a/SUMMARY.md b/SUMMARY.md index 9e2774fe..5a58e457 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -6,7 +6,7 @@ * [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) + * [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) @@ -18,7 +18,7 @@ * [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. 使用GVM安装](II. Getting started/10.2.2. Installation with GVM.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) @@ -36,17 +36,18 @@ * [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. Maven](III. Using Spring Boot/13.1. Maven.md) - * [13.1.1. 继承starter parent](III. Using Spring Boot/13.1.1. Inheriting the starter parent.md) - * [13.1.2. 使用没有父POM的Spring Boot](III. Using Spring Boot/13.1.2. Using Spring Boot without the parent POM.md) - * [13.1.3. 改变Java版本](III. Using Spring Boot/13.1.3. Changing the Java version.md) - * [13.1.4. 使用Spring Boot Maven插件](III. Using Spring Boot/13.1.4. Using the Spring Boot Maven plugin.md) - * [13.2. Gradle](III. Using Spring Boot/13.2. Gradle.md) - * [13.3. Ant](III. Using Spring Boot/13.3. Ant.md) - * [13.4. Starter POMs](III. Using Spring Boot/13.4. Starter POMs.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. 改变Java版本](III. Using Spring Boot/13.2.3. Changing the Java version.md) + * [13.2.4. 使用Spring Boot Maven插件](III. Using Spring Boot/13.2.4. 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) + * [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) @@ -61,318 +62,463 @@ * [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. Packaging your application for production.md) - * [21. 接下来阅读什么](III. Using Spring Boot/21. What to read next.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) + * [20.5.3 远程调试通道](III. Using Spring Boot/20.5.3 Remote debug tunnel.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) - * [22. SpringApplication](IV. Spring Boot features/22. SpringApplication.md) - * [22.1. 自定义Banner](IV. Spring Boot features/22.1. Customizing the Banner.md) - * [22.2. 自定义SpringApplication](IV. Spring Boot features/22.2. Customizing SpringApplication.md) - * [22.3. 流畅的构建API](IV. Spring Boot features/22.3. Fluent builder API.md) - * [22.4. Application事件和监听器](IV. Spring Boot features/22.4. Application events and listeners.md) - * [22.5. Web环境](IV. Spring Boot features/22.5. Web environment.md) - * [22.6. 命令行启动器](IV. Spring Boot features/22.6. Using the CommandLineRunner.md) - * [22.7. Application退出](IV. Spring Boot features/22.7. Application exit.md) - * [23.外化配置](IV. Spring Boot features/23. Externalized Configuration.md) - * [23.1. 配置随机值](IV. Spring Boot features/23.1. Configuring random values.md) - * [23.2. 访问命令行属性](IV. Spring Boot features/23.2. Accessing command line properties.md) - * [23.3. Application属性文件](IV. Spring Boot features/23.3. Application property files.md) - * [23.4. 特定的Profile属性](IV. Spring Boot features/23.4. Profile-specific properties.md) - * [23.5. 属性占位符](IV. Spring Boot features/23.5. Placeholders in properties.md) - * [23.6. 使用YAML代替Properties](IV. Spring Boot features/23.6. Using YAML instead of Properties.md) - * [23.6.1. 加载YAML](IV. Spring Boot features/23.6.1. Loading YAML.md) - * [23.6.2. 在Spring环境中使用YAML暴露属性](IV. Spring Boot features/23.6.2. Exposing YAML as properties in the Spring Environment.md) - * [23.6.3. Multi-profile YAML文档](IV. Spring Boot features/23.6.3. Multi-profile YAML documents.md) - * [23.6.4. YAML缺点](IV. Spring Boot features/23.6.4. YAML shortcomings.md) - * [23.7. 类型安全的配置属性](IV. Spring Boot features/23.7. Typesafe Configuration Properties.md) - * [23.7.1. 第三方配置](IV. Spring Boot features/23.7.1. Third-party configuration.md) - * [23.7.2. 松散的绑定(Relaxed binding)](IV. Spring Boot features/23.7.2. Relaxed binding.md) - * [23.7.3. @ConfigurationProperties校验](IV. Spring Boot features/23.7.3. @ConfigurationProperties Validation.md) - * [24. Profiles](IV. Spring Boot features/24. Profiles.md) - * [24.1. 添加激活的配置(profiles)](IV. Spring Boot features/24.1. Adding active profiles.md) - * [24.2.以编程方式设置profiles](IV. Spring Boot features/24.2. Programmatically setting profiles.md) - * [24.3. Profile特定配置文件](IV. Spring Boot features/24.3. Profile specific configuration files.md) - * [25. 日志](IV. Spring Boot features/25. Logging.md) - * [25.1. 日志格式](IV. Spring Boot features/25.1. Log format.md) - * [25.2. 控制台输出](IV. Spring Boot features/25.2. Console output.md) - * [25.3. 文件输出](IV. Spring Boot features/25.3. File output.md) - * [25.4. 日志级别](IV. Spring Boot features/25.4. Log Levels.md) - * [25.5. 自定义日志配置](IV. Spring Boot features/25.5. Custom log configuration.md) - * [26. 开发Web应用](IV. Spring Boot features/26. Developing web applications.md) - * [26.1. Spring Web MVC框架](IV. Spring Boot features/26.1. The ‘Spring Web MVC framework’.md) - * [26.1.1. Spring MVC自动配置](IV. Spring Boot features/26.1.1. Spring MVC auto-configuration.md) - * [26.1.2. HttpMessageConverters](IV. Spring Boot features/26.1.2. HttpMessageConverters.md) - * [26.1.3. MessageCodesResolver](IV. Spring Boot features/26.1.3. MessageCodesResolver.md) - * [26.1.4. 静态内容](IV. Spring Boot features/26.1.4. Static Content.md) - * [26.1.5. 模板引擎](IV. Spring Boot features/26.1.5. Template engines.md) - * [26.1.6. 错误处理](IV. Spring Boot features/26.1.6. Error Handling.md) - * [26.1.7. Spring HATEOAS](IV. Spring Boot features/26.1.7. Spring HATEOAS.md) - * [26.2. JAX-RS和Jersey](IV. Spring Boot features/26.2. JAX-RS and Jersey.md) - * [26.3. 内嵌servlet容器支持](IV. Spring Boot features/26.3. Embedded servlet container support.md) - * [26.3.1. Servlets和Filters](IV. Spring Boot features/26.3.1. Servlets and Filters.md) - * [26.3.2. EmbeddedWebApplicationContext](IV. Spring Boot features/26.3.2. The EmbeddedWebApplicationContext.md) - * [26.3.3. 自定义内嵌servlet容器](IV. Spring Boot features/26.3.3. Customizing embedded servlet containers.md) - * [26.3.4. JSP的限制](IV. Spring Boot features/26.3.4. JSP limitations.md) - * [27. 安全](IV. Spring Boot features/27. Security.md) - * [28. 使用SQL数据库](IV. Spring Boot features/28. Working with SQL databases.md) - * [28.1. 配置DataSource](IV. Spring Boot features/28.1. Configure a DataSource.md) - * [28.1.1. 对内嵌数据库的支持](IV. Spring Boot features/28.1.1. Embedded Database Support.md) - * [28.1.2. 连接到一个生产环境数据库](IV. Spring Boot features/28.1.2. Connection to a production database.md) - * [28.1.3. 连接到一个JNDI数据库](IV. Spring Boot features/28.1.3. Connection to a JNDI DataSource.md) - * [28.2. 使用JdbcTemplate](IV. Spring Boot features/28.2. Using JdbcTemplate.md) - * [28.3. JPA和Spring Data](IV. Spring Boot features/28.3. JPA and ‘Spring Data’.md) - * [28.3.1. 实体类](IV. Spring Boot features/28.3.1. Entity Classes.md) - * [28.3.2. Spring Data JPA仓库](IV. Spring Boot features/28.3.2. Spring Data JPA Repositories.md) - * [28.3.3. 创建和删除JPA数据库](IV. Spring Boot features/28.3.3. Creating and dropping JPA databases.md) - * [29. 使用NoSQL技术](IV. Spring Boot features/29. Working with NoSQL technologies.md) - * [29.1. Redis](IV. Spring Boot features/29.1. Redis.md) - * [29.1.1. 连接Redis](IV. Spring Boot features/29.1.1. Connecting to Redis.md) - * [29.2. MongoDB](IV. Spring Boot features/29.2. MongoDB.md) - * [29.2.1. 连接MongoDB数据库](IV. Spring Boot features/29.2.1. Connecting to a MongoDB database.md) - * [29.2.2. MongoDBTemplate](IV. Spring Boot features/29.2.2. MongoTemplate.md) - * [29.2.3. Spring Data MongoDB仓库](IV. Spring Boot features/29.2.3. Spring Data MongoDB repositories.md) - * [29.3. Gemfire](IV. Spring Boot features/29.3. Gemfire.md) - * [29.4. Solr](IV. Spring Boot features/29.4. Solr.md) - * [29.4.1. 连接Solr](IV. Spring Boot features/29.4.1. Connecting to Solr.md) - * [29.4.2. Spring Data Solr仓库](IV. Spring Boot features/29.4.2. Spring Data Solr repositories.md) - * [29.5. Elasticsearch](IV. Spring Boot features/29.5. Elasticsearch.md) - * [29.5.1. 连接Elasticsearch](IV. Spring Boot features/29.5.1. Connecting to Elasticsearch.md) - * [29.5.2. Spring Data Elasticseach仓库](IV. Spring Boot features/29.5.2. Spring Data Elasticsearch repositories.md) - * [30. 消息](IV. Spring Boot features/30. Messaging.md) - * [30.1. JMS](IV. Spring Boot features/30.1. JMS.md) - * [30.1.1. HornetQ支持](IV. Spring Boot features/30.1.1. HornetQ support.md) - * [30.1.2. ActiveQ支持](IV. Spring Boot features/30.1.2. ActiveMQ support.md) - * [30.1.3. 使用JNDI ConnectionFactory](IV. Spring Boot features/30.1.3. Using a JNDI ConnectionFactory.md) - * [30.1.4. 发送消息](IV. Spring Boot features/30.1.4. Sending a message.md) - * [30.1.5. 接收消息](IV. Spring Boot features/30.1.5. Receiving a message.md) - * [31. 发送邮件](IV. Spring Boot features/31. Sending email.md) - * [32. 使用JTA处理分布式事务](IV. Spring Boot features/32. Distributed Transactions with JTA.md) - * [32.1. 使用一个Atomikos事务管理器](IV. Spring Boot features/32.1. Using an Atomikos transaction manager.md) - * [32.2. 使用一个Bitronix事务管理器](IV. Spring Boot features/32.2. Using a Bitronix transaction manager.md) - * [32.3. 使用一个J2EE管理的事务管理器](IV. Spring Boot features/32.3. Using a Java EE managed transaction manager.md) - * [32.4. 混合XA和non-XA的JMS连接](IV. Spring Boot features/32.4. Mixing XA and non-XA JMS connections.md) - * [32.5. 支持可替代的内嵌事务管理器](IV. Spring Boot features/32.5. Supporting an alternative embedded ) - * [33. Spring集成](IV. Spring Boot features/33. Spring Integration.md) - * [34. 基于JMX的监控和管理](IV. Spring Boot features/34. Monitoring and management over JMX.md) - * [35. 测试](IV. Spring Boot features/35. Testing.md) - * [35.1. 测试作用域依赖](IV. Spring Boot features/35.1. Test scope dependencies.md) - * [35.2. 测试Spring应用](IV. Spring Boot features/35.2. Testing Spring applications.md) - * [35.3. 测试Spring Boot应用](IV. Spring Boot features/35.3. Testing Spring Boot applications.md) - * [35.3.1. 使用Spock测试Spring Boot应用](IV. Spring Boot features/35.3.1. Using Spock to test Spring Boot applications.md) - * [35.4. 测试工具](IV. Spring Boot features/35.4. Test utilities.md) - * [35.4.1. ConfigFileApplicationContextInitializer](IV. Spring Boot features/35.4.1. ConfigFileApplicationContextInitializer.md) - * [35.4.2. EnvironmentTestUtils](IV. Spring Boot features/35.4.2. EnvironmentTestUtils.md) - * [35.4.3. OutputCapture](IV. Spring Boot features/35.4.3. OutputCapture.md) - * [35.4.4. TestRestTemplate](IV. Spring Boot features/35.4.4. TestRestTemplate.md) - * [36. 开发自动配置和使用条件](IV. Spring Boot features/36. Developing auto-configuration and using conditions.md) - * [36.1. 理解auto-configured beans](IV. Spring Boot features/36.1. Understanding auto-configured beans.md) - * [36.2. 定位auto-configuration候选者](IV. Spring Boot features/36.2. Locating auto-configuration candidates.md) - * [36.3. Condition注解](IV. Spring Boot features/36.3. Condition annotations.md) - * [36.3.1. Class条件](IV. Spring Boot features/36.3.1. Class conditions.md) - * [36.3.2. Bean条件](IV. Spring Boot features/36.3.2. Bean conditions.md) - * [36.3.3. Property条件](IV. Spring Boot features/36.3.3. Property conditions.md) - * [36.3.4. Resource条件](IV. Spring Boot features/36.3.4. Resource conditions.md) - * [36.3.5. Web Application条件](IV. Spring Boot features/36.3.5. Web Application Conditions.md) - * [36.3.6. SpEL表达式条件](IV. Spring Boot features/36.3.6. SpEL expression conditions.md) - * [37. WebSockets](IV. Spring Boot features/37. WebSockets.md) - * [38. 接下来阅读什么](IV. Spring Boot features/38. What to read next.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) + * [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. Typesafe 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/25. 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 ConfigurableWebBindingInitializer](IV. Spring Boot features/27.1.6 ConfigurableWebBindingInitializer.md) + * [27.1.7 模板引擎](IV. Spring Boot features/27.1.7 Template engines.md) + * [27.1.8 错误处理](IV. Spring Boot features/27.1.8 Error Handling.md) + * [27.1.9 Spring HATEOAS](IV. Spring Boot features/27.1.9 Spring HATEOAS.md) + * [27.1.10 CORS支持](IV. Spring Boot features/27.1.10 CORS support.md) + * [27.2 JAX-RS和Jersey](IV. Spring Boot features/27.2 JAX-RS and Jersey.md) + * [27.3 内嵌servlet容器支持](IV. Spring Boot features/27.3 Embedded servlet container support.md) + * [27.3.1 Servlets, Filters和listeners](IV. Spring Boot features/27.3.1 Servlets, Filters, and listeners.md) + * [27.3.2 Servlet上下文初始化](IV. Spring Boot features/27.3.2 Servlet Context Initialization.md) + * [27.3.3 EmbeddedWebApplicationContext](27.3.3 The EmbeddedWebApplicationContext.md) + * [27.3.4 自定义内嵌servlet容器](IV. Spring Boot features/27.3.4 Customizing embedded servlet containers.md) + * [27.3.5 JSP的限制](IV. Spring Boot features/27.3.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.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](IV. Spring Boot features/29.5.3 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) + * [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 Guava](IV. Spring Boot features/31.1.9 Guava.md) + * [31.1.10 Simple](IV. Spring Boot features/31.1.10 Simple.md) + * [31.1.11 None](IV. Spring Boot features/31.1.11 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 HornetQ支持](IV. Spring Boot features/32.1.3 HornetQ support.md) + * [32.1.4 使用JNDI ConnectionFactory](IV. Spring Boot features/32.1.4 Using a JNDI ConnectionFactory.md) + * [32.1.5 发送消息](IV. Spring Boot features/32.1.5 Sending a message.md) + * [32.1.6 接收消息](IV. Spring Boot features/32.1.6 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) + * [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. Sending email.md) + * [35. 使用JTA处理分布式事务](IV. Spring Boot features/35. Distributed Transactions with JTA.md) + * [35.1 使用Atomikos事务管理器](IV. Spring Boot features/35.1 Using an Atomikos transaction manager.md) + * [35.2 使用Bitronix事务管理器](IV. Spring Boot features/35.2 Using a Bitronix transaction manager.md) + * [35.3 使用Narayana事务管理器](IV. Spring Boot features/35.3 Using a Narayana transaction manager.md) + * [35.4 使用J2EE管理的事务管理器](IV. Spring Boot features/35.4 Using a Java EE managed transaction manager.md) + * [35.5 混合XA和non-XA的JMS连接](IV. Spring Boot features/35.5 Mixing XA and non-XA JMS connections.md) + * [35.6 支持可替代的内嵌事务管理器](IV. Spring Boot features/35.6 Supporting an alternative embedded transaction manager.md) + * [36. Hazelcast](IV. Spring Boot features/36. Hazelcast.md) + * [37. Spring集成](IV. Spring Boot features/37. Spring Integration.md) + * [38. Spring Session](IV. Spring Boot features/38. Spring Session.md) + * [39. 基于JMX的监控和管理](IV. Spring Boot features/39. Monitoring and management over JMX.md) + * [40. 测试](IV. Spring Boot features/40. Testing.md) + * [40.1 测试作用域依赖](IV. Spring Boot features/40.1 Test scope dependencies.md) + * [40.2 测试Spring应用](IV. Spring Boot features/40.2 Testing Spring applications.md) + * [40.3 测试Spring Boot应用](IV. Spring Boot features/40.3 Testing Spring Boot applications.md) + * [40.3.1 发现测试配置](IV. Spring Boot features/40.3.1 Detecting test configuration.md) + * [40.3.2 排除测试配置](IV. Spring Boot features/40.3.2 Excluding test configuration.md) + * [40.3.3 使用随机端口](IV. Spring Boot features/40.3.3 Working with random ports.md) + * [40.3.4 模拟和监视beans](IV. Spring Boot features/40.3.4 Mocking and spying beans.md) + * [40.3.5 自动配置测试](IV. Spring Boot features/40.3.5 Auto-configured tests.md) + * [40.3.6 自动配置的JSON测试](IV. Spring Boot features/40.3.6 Auto-configured JSON tests.md) + * [40.3.7 自动配置的Spring MVC测试](IV. Spring Boot features/40.3.7 Auto-configured Spring MVC tests.md) + * [40.3.8 自动配置的Data JPA测试](IV. Spring Boot features/40.3.8 Auto-configured Data JPA tests.md) + * [40.3.9 自动配置的REST客户端](IV. Spring Boot features/40.3.9 Auto-configured REST clients.md) + * [40.3.10 自动配置的Spring REST Docs测试](IV. Spring Boot features/40.3.10 Auto-configured Spring REST Docs tests.md) + * [40.3.11 使用Spock测试Spring Boot应用](IV. Spring Boot features/40.3.11 Using Spock to test Spring Boot applications.md) + * [40.4 测试工具类](IV. Spring Boot features/40.4 Test utilities.md) + * [40.4.1 ConfigFileApplicationContextInitializer](IV. Spring Boot features/40.4.1 ConfigFileApplicationContextInitializer.md) + * [40.4.2 EnvironmentTestUtils](IV. Spring Boot features/40.4.2 EnvironmentTestUtils.md) + * [40.4.3 OutputCapture](IV. Spring Boot features/40.4.3 OutputCapture.md) + * [40.4.4 TestRestTemplate](IV. Spring Boot features/40.4.4 TestRestTemplate.md) + * [41. WebSockets](IV. Spring Boot features/41. WebSockets.md) + * [42. Web Services](IV. Spring Boot features/42. Web Services.md) + * [43. 创建自己的auto-configuration](IV. Spring Boot features/43. Creating your own auto-configuration.md) + * [43.1 理解自动配置的beans](IV. Spring Boot features/43.1 Understanding auto-configured beans.md) + * [43.2 定位自动配置候选者](IV. Spring Boot features/43.2 Locating auto-configuration candidates.md) + * [43.3 条件注解](IV. Spring Boot features/43.3 Condition annotations.md) + * [43.3.1 Class条件](IV. Spring Boot features/43.3.1 Class conditions.md) + * [43.3.2 Bean条件](IV. Spring Boot features/43.3.2 Bean conditions.md) + * [43.3.3 Property条件](IV. Spring Boot features/43.3.3 Property conditions.md) + * [43.3.4 Resource条件](IV. Spring Boot features/43.3.4 Resource conditions.md) + * [43.3.5 Web Application条件](IV. Spring Boot features/43.3.5 Web Application Conditions.md) + * [43.3.6 SpEL表达式条件](IV. Spring Boot features/43.3.6 SpEL expression conditions.md) + * [43.4 创建自己的starter](IV. Spring Boot features/43.4 Creating your own starter.md) + * [43.4.1 命名](IV. Spring Boot features/43.4.1 Naming.md) + * [43.4.2 自动配置模块](IV. Spring Boot features/43.4.2 Autoconfigure module.md) + * [43.4.3 Starter模块](IV. Spring Boot features/43.4.3 Starter module.md) + * [44. 接下来阅读什么](IV. Spring Boot features/44. What to read next.md) * [V. Spring Boot执行器: Production-ready特性](V. Spring Boot Actuator/README.md) - * [39. 开启production-ready特性](V. Spring Boot Actuator/39. Enabling production-ready features.md) - * [40. 端点](V. Spring Boot Actuator/40. Endpoints.md) - * [40.1. 自定义端点](V. Spring Boot Actuator/40.1. Customizing endpoints.md) - * [40.2. 健康信息](V. Spring Boot Actuator/40.2. Health information.md) - * [40.3. 安全与HealthIndicators](V. Spring Boot Actuator/40.3. Security with HealthIndicators.md) - * [40.3.1. 自动配置的HealthIndicators](V. Spring Boot Actuator/40.3.1. Auto-configured-HealthIndicators.md) - * [40.3.2. 编写自定义HealthIndicators](V. Spring Boot Actuator/40.3.2. Writing custom HealthIndicators.md) - * [40.4. 自定义应用info信息](V. Spring Boot Actuator/40.4. Custom application info information.md) - * [40.4.1. 在构建时期自动扩展info属性](V. Spring Boot Actuator/40.4.1. Automatically expand info properties at build time.md) - * [40.4.2. Git提交信息](V. Spring Boot Actuator/40.4.2. Git commit information.md) - * [41. 基于HTTP的监控和管理](V. Spring Boot Actuator/41. Monitoring and management over HTTP.md) - * [41.1. 保护敏感端点](V. Spring Boot Actuator/41.1. Securing sensitive endpoints.md) - * [41.2. 自定义管理服务器的上下文路径](V. Spring Boot Actuator/41.2. Customizing the management server context path.md) - * [41.3. 自定义管理服务器的端口](V. Spring Boot Actuator/41.3. Customizing the management server port.md) - * [41.4. 自定义管理服务器的地址](V. Spring Boot Actuator/41.4. Customizing the management server address.md) - * [41.5. 禁用HTTP端点](V. Spring Boot Actuator/41.5. Disabling HTTP endpoints.md) - * [41.6. HTTP Health端点访问限制](V. Spring Boot Actuator/41.6. HTTP Health endpoint access restrictions.md) - * [42. 基于JMX的监控和管理](V. Spring Boot Actuator/42. Monitoring and management over JMX.md) - * [42.1. 自定义MBean名称](V. Spring Boot Actuator/42.1. Customizing MBean names.md) - * [42.2. 禁用JMX端点](V. Spring Boot Actuator/42.2. Disabling JMX endpoints.md) - * [42.3. 使用Jolokia通过HTTP实现JMX远程管理](V. Spring Boot Actuator/42.3. Using Jolokia for JMX over HTTP.md) - * [42.3.1. 自定义Jolokia](V. Spring Boot Actuator/42.3.1. Customizing Jolokia.md) - * [42.3.2. 禁用Jolokia](V. Spring Boot Actuator/42.3.2. Disabling Jolokia.md) - * [43. 使用远程shell来进行监控和管理](V. Spring Boot Actuator/43. Monitoring and management using a remote shell.md) - * [43.1. 连接远程shell](V. Spring Boot Actuator/43.1. Connecting to the remote shell.md) - * [43.1.1. 远程shell证书](V. Spring Boot Actuator/43.1.1. Remote shell credentials.md) - * [43.2. 扩展远程shell](V. Spring Boot Actuator/43.2. Extending the remote shell.md) - * [43.2.1. 远程shell命令](V. Spring Boot Actuator/43.2.1. Remote shell commands.md) - * [43.2.2. 远程shell插件](V. Spring Boot Actuator/43.2.2. Remote shell plugins.md) - * [44. 度量指标(Metrics)](V. Spring Boot Actuator/44. Metrics.md) - * [44.1. 系统指标](V. Spring Boot Actuator/44.1. System metrics.md) - * [44.2. 数据源指标](V. Spring Boot Actuator/44.2. DataSource metrics.md) - * [44.3. Tomcat session指标](V. Spring Boot Actuator/44.3. Tomcat session metrics.md) - * [44.4. 记录自己的指标](V. Spring Boot Actuator/44.4. Recording your own metrics.md) - * [44.5. 添加你自己的公共指标](V. Spring Boot Actuator/44.5. Adding your own public metrics.md) - * [44.6. 指标仓库](V. Spring Boot Actuator/44.6. Metric repositories.md) - * [44.7. Dropwizard指标](V. Spring Boot Actuator/44.7. Dropwizard Metrics.md) - * [44.8. 消息渠道集成](V. Spring Boot Actuator/44.8. Message channel integration.md) - * [45. 审计](V. Spring Boot Actuator/45. Auditing.md) - * [46. 追踪(Tracing)](V. Spring Boot Actuator/46. Tracing.md) - * [46.1. 自定义追踪](V. Spring Boot Actuator/46.1. Custom tracing.md) - * [47. 进程监控](V. Spring Boot Actuator/47. Process monitoring.md) - * [47.1. 扩展属性](V. Spring Boot Actuator/47.1. Extend configuration.md) - * [47.2. 以编程方式](V. Spring Boot Actuator/47.2. Programmatically.md) - * [48. 接下来阅读什么](V. Spring Boot Actuator/48. What to read next.md`) + * [45. 开启production-ready特性](V. Spring Boot Actuator/45. Enabling production-ready features.md) + * [46. 端点](V. Spring Boot Actuator/46. Endpoints.md) + * [46.1 自定义端点](V. Spring Boot Actuator/46.1 Customizing endpoints.md) + * [46.2 执行器MVC端点的超媒体支持](V. Spring Boot Actuator/46.2 Hypermedia for actuator MVC endpoints.md) + * [46.3 CORS支持](V. Spring Boot Actuator/46.3 CORS support.md) + * [46.4 添加自定义端点](V. Spring Boot Actuator/46.4 Adding custom endpoints.md) + * [46.5 健康信息](V. Spring Boot Actuator/46.5 Health information.md) + * [46.6 安全与HealthIndicators](V. Spring Boot Actuator/46.6 Security with HealthIndicators.md) + * [46.6.1 自动配置的HealthIndicators](V. Spring Boot Actuator/46.6.1 Auto-configured-HealthIndicators.md) + * [46.6.2 编写自定义HealthIndicators](V. Spring Boot Actuator/46.6.2 Writing custom HealthIndicators.md) + * [46.7 应用信息](V. Spring Boot Actuator/46.7 Application information.md) + * [46.7.1 自动配置的InfoContributors](V. Spring Boot Actuator/46.7.1 Auto-configured InfoContributors.md) + * [46.7.2 自定义应用info信息](V. Spring Boot Actuator/46.7.2 Custom application info information.md) + * [46.7.3 Git提交信息](V. Spring Boot Actuator/46.7.3 Git commit information.md) + * [46.7.4 构建信息](V. Spring Boot Actuator/46.7.4 Build information.md) + * [46.7.5 编写自定义的InfoContributors](V. Spring Boot Actuator/46.7.5 Writing custom InfoContributors.md) + * [47. 基于HTTP的监控和管理](V. Spring Boot Actuator/47. Monitoring and management over HTTP.md) + * [47.1 保护敏感端点](V. Spring Boot Actuator/47.1 Securing sensitive endpoints.md) + * [47.2 自定义管理端点路径](V. Spring Boot Actuator/47.2 Customizing the management endpoint paths.md) + * [47.3 自定义管理服务器端口](V. Spring Boot Actuator/47.3 Customizing the management server port.md) + * [47.4 配置管理相关的SSL](V. Spring Boot Actuator/47.4 Configuring management-specific SSL.md) + * [47.5 自定义管理服务器地址](V. Spring Boot Actuator/47.5 Customizing the management server address.md) + * [47.6 禁用HTTP端点](V. Spring Boot Actuator/47.6 Disabling HTTP endpoints.md) + * [47.7 HTTP health端点访问限制](V. Spring Boot Actuator/47.7 HTTP Health endpoint access restrictions.md) + * [48. 基于JMX的监控和管理](V. Spring Boot Actuator/48. Monitoring and management over JMX.md) + * [48.1 自定义MBean名称](V. Spring Boot Actuator/48.1 Customizing MBean names.md) + * [48.2 禁用JMX端点](V. Spring Boot Actuator/48.2 Disabling JMX endpoints.md) + * [48.3 使用Jolokia通过HTTP实现JMX远程管理](V. Spring Boot Actuator/48.3 Using Jolokia for JMX over HTTP.md) + * [48.3.1 自定义Jolokia](V. Spring Boot Actuator/48.3.1 Customizing Jolokia.md) + * [48.3.2 禁用Jolokia](V. Spring Boot Actuator/48.3.2 Disabling Jolokia.md) + * [49. 使用远程shell进行监控和管理](V. Spring Boot Actuator/49. Monitoring and management using a remote shell.md) + * [49.1 连接远程shell](V. Spring Boot Actuator/49.1 Connecting to the remote shell.md) + * [49.1.1 远程shell证书](V. Spring Boot Actuator/49.1.1 Remote shell credentials.md) + * [49.2 扩展远程shell](V. Spring Boot Actuator/49.2 Extending the remote shell.md) + * [49.2.1 远程shell命令](V. Spring Boot Actuator/49.2.1 Remote shell commands.md) + * [49.2.2 远程shell插件](V. Spring Boot Actuator/49.2.2 Remote shell plugins.md) + * [50. 度量指标](V. Spring Boot Actuator/50. Metrics.md) + * [50.1 系统指标](V. Spring Boot Actuator/50.1 System metrics.md) + * [50.2 数据源指标](V. Spring Boot Actuator/50.2 DataSource metrics.md) + * [50.3 缓存指标](V. Spring Boot Actuator/50.3 Cache metrics.md) + * [50.4 Tomcat session指标](V. Spring Boot Actuator/50.4 Tomcat session metrics.md) + * [50.5 记录自己的指标](V. Spring Boot Actuator/50.5 Recording your own metrics.md) + * [50.6 添加自己的公共指标](V. Spring Boot Actuator/50.6 Adding your own public metrics.md) + * [50.7 使用Java8的特性](V. Spring Boot Actuator/50.7 Special features with Java 8.md) + * [50.8 指标写入,导出和聚合](V. Spring Boot Actuator/50.8 Metric writers, exporters and aggregation.md) + * [50.8.1 示例: 导出到Redis](V. Spring Boot Actuator/50.8.1 Export to Redis.md) + * [50.8.2 示例: 导出到Open TSDB](V. Spring Boot Actuator/50.8.2 Export to Open TSDB.md) + * [50.8.3 示例: 导出到Statsd](V. Spring Boot Actuator/50.8.3 Export to Statsd.md) + * [50.8.4 示例: 导出到JMX](V. Spring Boot Actuator/50.8.4 Export to JMX.md) + * [50.9 聚合多个来源的指标](V. Spring Boot Actuator/50.9 Aggregating metrics from multiple sources.md) + * [50.10 Dropwizard指标](V. Spring Boot Actuator/50.10 Dropwizard Metrics.md) + * [50.11 消息渠道集成](V. Spring Boot Actuator/50.11 Message channel integration.md) + * [51. 审计](V. Spring Boot Actuator/51. Auditing.md) + * [52. 追踪](V. Spring Boot Actuator/52. Tracing.md) + * [52.1 自定义追踪](V. Spring Boot Actuator/52.1 Custom tracing.md) + * [53. 进程监控](V. Spring Boot Actuator/47. Process monitoring.md) + * [53.1 扩展配置](V. Spring Boot Actuator/53.1 Extend configuration.md) + * [53.2 以编程方式](V. Spring Boot Actuator/53.2 Programmatically.md) + * [54. 接下来阅读什么](V. Spring Boot Actuator/54. What to read next.md) * [VI. 部署到云端](VI. Deploying to the cloud/README.md) - * [49. Cloud Foundry](VI. Deploying to the cloud/49. Cloud Foundry.md) - * [49.1. 绑定服务](VI. Deploying to the cloud/49.1. Binding to services.md) - * [50. Heroku](VI. Deploying to the cloud/50. Heroku.md) - * [51. Openshift](VI. Deploying to the cloud/51. Openshift.md) - * [52. Google App Engine](VI. Deploying to the cloud/52. Google App Engine.md) - * [53. 接下来阅读什么](VI. Deploying to the cloud/53. What to read next.md) + * [55. 部署到云端](VI. Deploying Spring Boot applications/55. Deploying to the cloud.md) + * [55.1 Cloud Foundry](VI. Deploying Spring Boot applications/55.1 Cloud Foundry.md) + * [55.1.1 绑定服务](VI. Deploying Spring Boot applications/55.1.1 Binding to services.md) + * [55.2 Heroku](VI. Deploying Spring Boot applications/55.2 Heroku.md) + * [55.3 Openshift](VI. Deploying Spring Boot applications/55.3 Openshift.md) + * [55.4 Boxfuse和Amazon Web Services](VI. Deploying Spring Boot applications/55.4 Boxfuse and Amazon Web Services.md) + * [55.5 Google App Engine](VI. Deploying Spring Boot applications/55.5 Google App Engine.md) + * [56. 安装Spring Boot应用](VI. Deploying Spring Boot applications/56. Installing Spring Boot applications.md) + * [56.1 Unix/Linux服务](VI. Deploying Spring Boot applications/56.1 Unix&Linux services.md) + * [56.1.1 安装为init.d服务(System V)](VI. Deploying Spring Boot applications/56.1.1 Installation as an init.d service (System V).md) + * [56.1.2 安装为Systemd服务](VI. Deploying Spring Boot applications/56.1.2 Installation as a systemd service.md) + * [56.1.3 自定义启动脚本](VI. Deploying Spring Boot applications/56.1.3 Customizing the startup script.md) + * [56.2 Microsoft Windows服务](VI. Deploying Spring Boot applications/56.2 Microsoft Windows services.md) + * [57. 接下来阅读什么](VI. Deploying Spring Boot applications/57. What to read next.md) * [VII. Spring Boot CLI](VII. Spring Boot CLI/README.md) - * [54. 安装CLI](VII. Spring Boot CLI/54. Installing the CLI.md) - * [55. 使用CLI](VII. Spring Boot CLI/55. Using the CLI.md) - * [55.1. 使用CLI运行应用](VII. Spring Boot CLI/55.1. Running applications using the CLI.md) - * [55.1.1. 推断"grab"依赖](VII. Spring Boot CLI/55.1.1. Deduced “grab” dependencies.md) - * [55.1.2. 推断"grab"坐标](VII. Spring Boot CLI/55.1.2. Deduced “grab” coordinates.md) - * [55.1.3. 默认import语句](VII. Spring Boot CLI/55.1.3. Default import statements.md) - * [55.1.4. 自动创建main方法](VII. Spring Boot CLI/55.1.4. Automatic main method.md) - * [55.1.5. 自定义"grab"元数据](VII. Spring Boot CLI/55.1.5. Custom “grab” metadata.md) - * [55.2. 测试你的代码](VII. Spring Boot CLI/55.2. Testing your code.md) - * [55.3. 多源文件应用](VII. Spring Boot CLI/55.3. Applications with multiple source files.md) - * [55.4. 应用打包](VII. Spring Boot CLI/55.4. Packaging your application.md) - * [55.5. 初始化新工程](VII. Spring Boot CLI/55.5. Initialize a new project.md) - * [55.6. 使用内嵌shell](VII. Spring Boot CLI/55.6. Using the embedded shell.md) - * [55.7. 为CLI添加扩展](VII. Spring Boot CLI/55.7. Adding extensions to the CLI.md) - * [56. 使用Groovy beans DSL开发应用](VII. Spring Boot CLI/56. Developing application with the Groovy beans DSL.md) - * [57. 接下来阅读什么](VII. Spring Boot CLI/57. What to read next.md) + * [58. 安装CLI](VII. Spring Boot CLI/58. Installing the CLI.md) + * [59. 使用CLI](VII. Spring Boot CLI/59. Using the CLI.md) + * [59.1 使用CLI运行应用](VII. Spring Boot CLI/59.1. Running applications using the CLI.md) + * [59.1.1 推断"grab"依赖](VII. Spring Boot CLI/59.1.1 Deduced “grab” dependencies.md) + * [59.1.2 推断"grab"坐标](VII. Spring Boot CLI/59.1.2 Deduced “grab” coordinates.md) + * [59.1.3 默认import语句](VII. Spring Boot CLI/59.1.3 Default import statements.md) + * [59.1.4 自动创建main方法](VII. Spring Boot CLI/59.1.4 Automatic main method.md) + * [59.1.5 自定义依赖管理](VII. Spring Boot CLI/59.1.5 Custom dependency management.md) + * [59.2 测试你的代码](VII. Spring Boot CLI/59.2 Testing your code.md) + * [59.3 多源文件应用](VII. Spring Boot CLI/59.3 Applications with multiple source files.md) + * [59.4 应用打包](VII. Spring Boot CLI/59.4 Packaging your application.md) + * [59.5 初始化新工程](VII. Spring Boot CLI/59.5 Initialize a new project.md) + * [59.6 使用内嵌shell](VII. Spring Boot CLI/59.6 Using the embedded shell.md) + * [59.7 为CLI添加扩展](VII. Spring Boot CLI/59.7 Adding extensions to the CLI.md) + * [60. 使用Groovy beans DSL开发应用](VII. Spring Boot CLI/60. Developing application with the Groovy beans DSL.md) + * [61. 使用settings.xml配置CLI](VII. Spring Boot CLI/61. Configuring the CLI with settings.xml.md) + * [62. 接下来阅读什么](VII. Spring Boot CLI/62. What to read next.md) * [VIII. 构建工具插件](VIII. Build tool plugins/README.md) - * [58. Spring Boot Maven插件](VIII. Build tool plugins/58. Spring Boot Maven plugin.md) - * [58.1. 包含该插件](VIII. Build tool plugins/58.1. Including the plugin.md) - * [58.2. 打包可执行jar和war文件](VIII. Build tool plugins/58.2. Packaging executable jar and war files.md) - * [59. Spring Boot Gradle插件](VIII. Build tool plugins/59. Spring Boot Gradle plugin.md) - * [59.1. 包含该插件](VIII. Build tool plugins/59.1. Including the plugin.md) - * [59.2. 声明不带版本的依赖](VIII. Build tool plugins/59.2. Declaring dependencies without versions.md) - * [59.2.1. 自定义版本管理](VIII. Build tool plugins/59.2.1. Custom version management.md) - * [59.3. 默认排除规则](VIII. Build tool plugins/59.3. Default exclude rules.md) - * [59.4. 打包可执行jar和war文件](VIII. Build tool plugins/59.4. Packaging executable jar and war files.md) - * [59.5. 就地(in-place)运行项目](VIII. Build tool plugins/59.5. Running a project in-place.md) - * [59.6. Spring Boot插件配置](VIII. Build tool plugins/59.6. Spring Boot plugin configuration.md) - * [59.7. Repackage配置](VIII. Build tool plugins/59.7. Repackage configuration.md) - * [59.8. 使用Gradle自定义配置进行Repackage](VIII. Build tool plugins/59.8. Repackage with custom Gradle configuration.md) - * [59.8.1. 配置选项](VIII. Build tool plugins/59.8.1. Configuration options.md) - * [59.9. 理解Gradle插件是如何工作的](VIII. Build tool plugins/59.9. Understanding how the Gradle plugin works.md) - * [60. 对其他构建系统的支持](VIII. Build tool plugins/60. Supporting other build systems.md) - * [60.1. 重新打包存档](VIII. Build tool plugins/60.1. Repackaging archives.md) - * [60.2. 内嵌的库](VIII. Build tool plugins/60.2. Nested libraries.md) - * [60.3. 查找main类](VIII. Build tool plugins/60.3. Finding a main class.md) - * [60.4. repackage实现示例](VIII. Build tool plugins/60.4. Example repackage implementation.md) - * [61. 接下来阅读什么](VIII. Build tool plugins/61. What to read next.md) + * [63. Spring Boot Maven插件](VIII. Build tool plugins/63. Spring Boot Maven plugin.md) + * [63.1 包含该插件](VIII. Build tool plugins/63.1 Including the plugin.md) + * [63.2 打包可执行jar和war文件](VIII. Build tool plugins/63.2 Packaging executable jar and war files.md) + * [64. Spring Boot Gradle插件](VIII. Build tool plugins/64. Spring Boot Gradle plugin.md) + * [64.1 包含该插件](VIII. Build tool plugins/64.1 Including the plugin.md) + * [64.2 Gradle依赖管理](VIII. Build tool plugins/64.2 Gradle dependency management.md) + * [64.3 打包可执行jar和war文件](VIII. Build tool plugins/64.3 Packaging executable jar and war files.md) + * [64.4 就地(in-place)运行项目](VIII. Build tool plugins/64.4 Running a project in-place.md) + * [64.5 Spring Boot插件配置](VIII. Build tool plugins/64.5 Spring Boot plugin configuration.md) + * [64.6 Repackage配置](VIII. Build tool plugins/64.6 Repackage configuration.md) + * [64.7 使用Gradle自定义配置进行Repackage](VIII. Build tool plugins/64.7 Repackage with custom Gradle configuration.md) + * [64.7.1 配置选项](VIII. Build tool plugins/64.7.1 Configuration options.md) + * [64.7.2 可用的layouts](VIII. Build tool plugins/64.7.2 Available layouts.md) + * [64.8 理解Gradle插件是如何工作的](VIII. Build tool plugins/64.8 Understanding how the Gradle plugin works.md) + * [64.9 使用Gradle将artifacts发布到Maven仓库](VIII. Build tool plugins/64.9 Publishing artifacts to a Maven repository using Gradle.md) + * [64.9.1 自定义Gradle,用于产生一个继承依赖管理的pom](VIII. Build tool plugins/64.9.1 Configuring Gradle to produce a pom that inherits dependency management.md) + * [64.9.2 自定义Gradle,用于产生一个导入依赖管理的pom](VIII. Build tool plugins/64.9.2 Configuring Gradle to produce a pom that imports dependency management.md) + * [65. Spring Boot AntLib模块](VIII. Build tool plugins/65. Spring Boot AntLib module.md) + * [65.1. Spring Boot Ant任务](VIII. Build tool plugins/65.1. Spring Boot Ant tasks.md) + * [65.1.1. spring-boot:exejar](VIII. Build tool plugins/65.1.1. spring-boot:exejar.md) + * [65.1.2. 示例](VIII. Build tool plugins/65.1.2. Examples.md) + * [65.2. spring-boot:findmainclass](VIII. Build tool plugins/65.2. spring-boot:findmainclass.md) + * [65.2.1. 示例](VIII. Build tool plugins/65.2.1. Examples.md) +   * [66. 对其他构建系统的支持](VIII. Build tool plugins/66. Supporting other build systems.md) + * [66.1. 重新打包存档](VIII. Build tool plugins/66.1. Repackaging archives.md) + * [66.2. 内嵌库](VIII. Build tool plugins/66.2.Nested libraries.md) + * [66.3. 查找main类](VIII. Build tool plugins/66.3. Finding a main class.md) + * [66.4. repackage实现示例](VIII. Build tool plugins/66.4. Example repackage implementation.md) + * [67. 接下来阅读什么](VIII. Build tool plugins/67. What to read next.md) * [IX. How-to指南](IX. ‘How-to’ guides/README.md) - * [62. Spring Boot应用](IX. ‘How-to’ guides/62. Spring Boot application.md) - * [62.1. 解决自动配置问题](IX. ‘How-to’ guides/62.1. Troubleshoot auto-configuration.md) - * [62.2. 启动前自定义Environment或ApplicationContext](IX. ‘How-to’ guides/62.2. Customize the Environment or ApplicationContext before it starts.md) - * [62.3. 构建ApplicationContext层次结构(添加父或根上下文](IX. ‘How-to’ guides/62.3. Build an ApplicationContext hierarchy (adding a parent or root context).md) - * [62.4. 创建一个非web(non-web)应用](IX. ‘How-to’ guides/62.4. Create a non-web application.md) - * [63. 属性&配置](IX. ‘How-to’ guides/63. Properties & configuration.md) - * [63.1. 外部化SpringApplication配置](IX. ‘How-to’ guides/63.1. Externalize the configuration of SpringApplication.md) - * [63.2. 改变应用程序外部配置文件的位置](IX. ‘How-to’ guides/63.2. Change the location of external properties of an application.md) - * [63.3. 使用'short'命令行参数](IX. ‘How-to’ guides/63.3. Use ‘short’ command line arguments.md) - * [63.4. 使用YAML配置外部属性](IX. ‘How-to’ guides/63.4. Use YAML for external properties.md) - * [63.5. 设置生效的Spring profiles](IX. ‘How-to’ guides/63.5. Set the active Spring profiles.md) - * [63.6. 根据环境改变配置](IX. ‘How-to’ guides/63.6. Change configuration depending on the environment.md) - * [63.7. 发现外部属性的内置选项](IX. ‘How-to’ guides/63.7. Discover built-in options for external properties.md) - * [64. 内嵌的servlet容器](IX. ‘How-to’ guides/64. Embedded servlet containers.md) - * [64.1. 为应用添加Servlet,Filter或ServletContextListener](IX. ‘How-to’ guides/64.1. Add a Servlet, Filter or ServletContextListener to an application.md) - * [64.2. 改变HTTP端口](IX. ‘How-to’ guides/64.2. Change the HTTP port.md) - * [64.3. 使用随机未分配的HTTP端口](IX. ‘How-to’ guides/64.3. Use a random unassigned HTTP port.md) - * [64.4. 发现运行时的HTTP端口](IX. ‘How-to’ guides/64.4. Discover the HTTP port at runtime.md) - * [64.5. 配置SSL](IX. ‘How-to’ guides/64.5. Configure SSL.md) - * [64.6. 配置Tomcat](IX. ‘How-to’ guides/64.6. Configure Tomcat.md) - * [64.7. 启用Tomcat的多连接器(Multiple Connectors)](IX. ‘How-to’ guides/64.7. Enable Multiple Connectors with Tomcat.md) - * [64.8. 在前端代理服务器后使用Tomcat](IX. ‘How-to’ guides/64.8. Use Tomcat behind a front-end proxy server.md) - * [64.9. 使用Jetty替代Tomcat](IX. ‘How-to’ guides/64.9. Use Jetty instead of Tomcat.md) - * [64.10. 配置Jetty](IX. ‘How-to’ guides/64.10. Configure Jetty.md) - * [64.11. 使用Undertow替代Tomcat](IX. ‘How-to’ guides/64.11. Use Undertow instead of Tomcat.md) - * [64.12. 配置Undertow](IX. ‘How-to’ guides/64.12. Configure Undertow.md) - * [64.13. 启用Undertow的多监听器](IX. ‘How-to’ guides/64.13. Enable Multiple Listeners with Undertow.md) - * [64.14. 使用Tomcat7](IX. ‘How-to’ guides/64.14. Use Tomcat 7.md) - * [64.14.1. 通过Maven使用Tomcat7](IX. ‘How-to’ guides/64.14.1. Use Tomcat 7 with Maven.md) - * [64.14.2. 通过Gradle使用Tomcat7](IX. ‘How-to’ guides/64.14.2. Use Tomcat 7 with Gradle.md) - * [64.15. 使用Jetty8](IX. ‘How-to’ guides/64.15. Use Jetty 8.md) - * [64.15.1. 通过Maven使用Jetty8](IX. ‘How-to’ guides/64.15.1. Use Jetty 8 with Maven.md) - * [64.15.2. 通过Gradle使用Jetty8](IX. ‘How-to’ guides/64.15.2. Use Jetty 8 with Gradle.md) - * [64.16. 使用@ServerEndpoint创建WebSocket端点](IX. ‘How-to’ guides/64.16. Create WebSocket endpoints using @ServerEndpoint.md) - * [64.17. 启用HTTP响应压缩](IX. ‘How-to’ guides/64.17. Enable HTTP response compression.md) - * [64.17.1. 启用Tomcat的HTTP响应压缩](IX. ‘How-to’ guides/64.17.1. Enable Tomcat’s HTTP response compression.md) - * [64.17.2. 使用GzipFilter开启HTTP响应压缩](IX. ‘How-to’ guides/64.17.2. Enable HTTP response compression using GzipFilter.md) - * [65. Spring MVC](IX. ‘How-to’ guides/65. Spring MVC.md) - * [65.1. 编写一个JSON REST服务](IX. ‘How-to’ guides/65.1. Write a JSON REST service.md) - * [65.2. 编写一个XML REST服务](IX. ‘How-to’ guides/65.2. Write an XML REST service.md) - * [65.3. 自定义Jackson ObjectMapper](IX. ‘How-to’ guides/65.3. Customize the Jackson ObjectMapper.md) - * [65.4. 自定义@ResponseBody渲染](IX. ‘How-to’ guides/65.4. Customize the @ResponseBody rendering.md) - * [65.5. 处理Multipart文件上传](IX. ‘How-to’ guides/65.5. Handling Multipart File Uploads.md) - * [65.6. 关闭Spring MVC DispatcherServlet](IX. ‘How-to’ guides/65.6. Switch off the Spring MVC DispatcherServlet.md) - * [65.7. 关闭默认的MVC配置](IX. ‘How-to’ guides/65.7. Switch off the Default MVC configuration.md) - * [65.8. 自定义ViewResolvers](IX. ‘How-to’ guides/65.8. Customize ViewResolvers.md) - * [66. 日志](IX. ‘How-to’ guides/66. Logging.md) - * [66.1. 配置Logback](IX. ‘How-to’ guides/66.1. Configure Logback for logging.md) - * [66.2. 配置Log4j](IX. ‘How-to’ guides/66.2. Configure Log4j for logging.md) - * [66.2.1. 使用YAML或JSON配置Log4j2](IX. ‘How-to’ guides/66.2.1. Use YAML or JSON to configure Log4j 2.md) - * [67. 数据访问](IX. ‘How-to’ guides/67. Data Access.md) - * [67.1. 配置一个数据源](IX. ‘How-to’ guides/67.1. Configure a DataSource.md) - * [67.2. 配置两个数据源](IX. ‘How-to’ guides/67.2. Configure Two DataSources.md) - * [67.3. 使用Spring Data仓库](IX. ‘How-to’ guides/67.3. Use Spring Data repositories.md) - * [67.4. 从Spring配置分离@Entity定义](IX. ‘How-to’ guides/67.4. Separate @Entity definitions from Spring configuration.md) - * [67.5. 配置JPA属性](IX. ‘How-to’ guides/67.5. Configure JPA properties.md) - * [67.6. 使用自定义的EntityManagerFactory](IX. ‘How-to’ guides/67.6. Use a custom EntityManagerFactory.md) - * [67.7. 使用两个EntityManagers](IX. ‘How-to’ guides/67.7. Use Two EntityManagers.md) - * [67.8. 使用普通的persistence.xml](IX. ‘How-to’ guides/67.8. Use a traditional persistence.xml.md) - * [67.9. 使用Spring Data JPA和Mongo仓库](IX. ‘How-to’ guides/67.9. Use Spring Data JPA and Mongo repositories.md) - * [67.10. 将Spring Data仓库暴露为REST端点](IX. ‘How-to’ guides/67.10. Expose Spring Data repositories as REST endpoint.md) - * [68. 数据库初始化](IX. ‘How-to’ guides/68. Database initialization.md) - * [68.1. 使用JPA初始化数据库](IX. ‘How-to’ guides/68.1. Initialize a database using JPA.md) - * [68.2. 使用Hibernate初始化数据库](IX. ‘How-to’ guides/68.2. Initialize a database using Hibernate.md) - * [68.3. 使用Spring JDBC初始化数据库](IX. ‘How-to’ guides/68.3. Initialize a database using Spring JDBC.md) - * [68.4. 初始化Spring Batch数据库](IX. ‘How-to’ guides/68.4. Initialize a Spring Batch database.md) - * [68.5. 使用一个高级别的数据迁移工具](IX. ‘How-to’ guides/68.5. Use a higher level database migration tool.md) - * [68.5.1. 启动时执行Flyway数据库迁移](IX. ‘How-to’ guides/68.5.1. Execute Flyway database migrations on startup.md) - * [68.5.2. 启动时执行Liquibase数据库迁移](IX. ‘How-to’ guides/68.5.2. Execute Liquibase database migrations on startup.md) - * [69. 批处理应用](IX. ‘How-to’ guides/69. Batch applications.md) - * [69.1. 在启动时执行Spring Batch作业](IX. ‘How-to’ guides/69.1. Execute Spring Batch jobs on startup.md) - * [70. 执行器(Actuator)](IX. ‘How-to’ guides/70. Actuator.md) - * [70.1. 改变HTTP端口或执行器端点的地址](IX. ‘How-to’ guides/70.1. Change the HTTP port or address of the actuator endpoints.md) - * [70.2. 自定义'白标'(whitelabel,可以了解下相关理念)错误页面](IX. ‘How-to’ guides/70.2. Customize the ‘whitelabel’ error page.md) - * [71. 安全](IX. ‘How-to’ guides/71. Security.md) - * [71.1. 关闭Spring Boot安全配置](IX. ‘How-to’ guides/71.1. Switch off the Spring Boot security configuration.md) - * [71.2. 改变AuthenticationManager并添加用户账号](IX. ‘How-to’ guides/71.2. Change the AuthenticationManager and add user accounts.md) - * [71.3. 当前端使用代理服务器时,启用HTTPS](IX. ‘How-to’ guides/71.3. Enable HTTPS when running behind a proxy server.md) - * [72. 热交换](IX. ‘How-to’ guides/72. Hot swapping.md) - * [72.1. 重新加载静态内容](IX. ‘How-to’ guides/72.1. Reload static content.md) - * [72.2. 在不重启容器的情况下重新加载Thymeleaf模板](IX. ‘How-to’ guides/72.2. Reload Thymeleaf templates without restarting the container.md) - * [72.3. 在不重启容器的情况下重新加载FreeMarker模板](IX. ‘How-to’ guides/72.3. Reload FreeMarker templates without restarting the container.md) - * [72.4. 在不重启容器的情况下重新加载Groovy模板](IX. ‘How-to’ guides/72.4. Reload Groovy templates without restarting the container.md) - * [72.5. 在不重启容器的情况下重新加载Velocity模板](IX. ‘How-to’ guides/72.5. Reload Velocity templates without restarting the container.md) - * [72.6. 在不重启容器的情况下重新加载Java类](IX. ‘How-to’ guides/72.6. Reload Java classes without restarting the container.md) - * [72.6.1. 使用Maven配置Spring Loaded](IX. ‘How-to’ guides/72.6.1. Configuring Spring Loaded for use with Maven.md) - * [72.6.2. 使用Gradle和IntelliJ配置Spring Loaded](IX. ‘How-to’ guides/72.6.2. Configuring Spring Loaded for use with Gradle and IntelliJ.md) - * [73. 构建](IX. ‘How-to’ guides/73. Build.md) - * [73.1. 使用Maven自定义依赖版本](IX. ‘How-to’ guides/73.1. Customize dependency versions with Maven.md) - * [73.2. 使用Maven创建可执行JAR](IX. ‘How-to’ guides/73.2. Create an executable JAR with Maven.md) - * [73.3. 创建其他的可执行JAR](IX. ‘How-to’ guides/73.3. Create an additional executable JAR.md) - * [73.4. 在可执行jar运行时提取特定的版本](IX. ‘How-to’ guides/73.4. Extract specific libraries when an executable jar runs.md) - * [73.5. 使用排除创建不可执行的JAR](IX. ‘How-to’ guides/73.5. Create a non-executable JAR with exclusions.m) - * [73.6. 远程调试一个使用Maven启动的Spring Boot项目](IX. ‘How-to’ guides/73.6. Remote debug a Spring Boot application started with Maven.md) - * [73.7. 远程调试一个使用Gradle启动的Spring Boot项目](IX. ‘How-to’ guides/73.7. Remote debug a Spring Boot application started with Gradle.md) - * [73.8. 使用Ant构建可执行存档(archive)](IX. ‘How-to’ guides/73.8. Build an executable archive with Ant.md) - * [73.9. 如何使用Java6](IX. ‘How-to’ guides/73.9. How to use Java 6.md) - * [73.9.1. 内嵌Servlet容器兼容性](IX. ‘How-to’ guides/73.9.1. Embedded servlet container compatibility.md) - * [73.9.2. JTA API兼容性](IX. ‘How-to’ guides/73.9.2. JTA API compatibility.md) - * [74. 传统部署](IX. ‘How-to’ guides/74. Traditional deployment.md) - * [74.1. 创建一个可部署的war文件](IX. ‘How-to’ guides/74.1. Create a deployable war file.md) - * [74.2. 为老的servlet容器创建一个可部署的war文件](IX. ‘How-to’ guides/74.2. Create a deployable war file for older servlet containers.md) - * [74.3. 将现有的应用转换为Spring Boot](IX. ‘How-to’ guides/74.3. Convert an existing application to Spring Boot.md) - * [74.4. 部署WAR到Weblogic](IX. ‘How-to’ guides/74.4. Deploying a WAR to Weblogic.md) - * [74.5. 部署WAR到老的(Servlet2.5)容器](IX. ‘How-to’ guides/74.5. Deploying a WAR in an Old (Servlet 2.5) Container.md) + * [68. Spring Boot应用](IX. ‘How-to’ guides/68. Spring Boot application.md) + * [68.1 创建自己的FailureAnalyzer](IX. ‘How-to’ guides/68.1 Create your own FailureAnalyzer.md) + * [68.2 解决自动配置问题](IX. ‘How-to’ guides/68.2 Troubleshoot auto-configuration.md) + * [68.3 启动前自定义Environment或ApplicationContext](IX. ‘How-to’ guides/68.3 Customize the Environment or ApplicationContext before it starts.md) + * [68.4 构建ApplicationContext层次结构](IX. ‘How-to’ guides/68.4 Build an ApplicationContext hierarchy (adding a parent or root context).md) + * [68.5 创建no-web应用](IX. ‘How-to’ guides/68.5 Create a non-web application.md) + * [69. 属性&配置](IX. ‘How-to’ guides/69. Properties & configuration.md) + * [69.1. 运行时暴露属性](IX. ‘How-to’ guides/69.1. Automatically expand properties at build time.md) + * [69.1.1. 使用Maven自动暴露属性](IX. ‘How-to’ guides/69.1.1. Automatic property expansion using Maven.md) + * [69.1.2. 使用Gradle自动暴露属性](IX. ‘How-to’ guides/69.1.2. Automatic property expansion using Gradle.md) + * [69.2. 外部化SpringApplication配置](IX. ‘How-to’ guides/69.2. Externalize the configuration of SpringApplication.md) + * [69.3 改变应用程序外部配置文件的位置](IX. ‘How-to’ guides/69.3 Change the location of external properties of an application.md) + * [69.4 使用'short'命令行参数](IX. ‘How-to’ guides/69.4 Use ‘short’ command line arguments.md) + * [69.5 使用YAML配置外部属性](IX. ‘How-to’ guides/69.5 Use YAML for external properties.md) + * [69.6 设置生效的Spring profiles](IX. ‘How-to’ guides/69.6 Set the active Spring profiles.md) + * [69.7 根据环境改变配置](IX. ‘How-to’ guides/69.7 Change configuration depending on the environment.md) + * [69.8 发现外部属性的内置选项](IX. ‘How-to’ guides/69.8 Discover built-in options for external properties.md) + * [70. 内嵌servlet容器](IX. ‘How-to’ guides/70. Embedded servlet containers.md) + * [70.1 为应用添加Servlet,Filter或Listener](IX. ‘How-to’ guides/70.1 Add a Servlet, Filter or ServletContextListener to an application.md) + * [70.1.1 使用Spring bean添加Servlet, Filter或Listener](IX. ‘How-to’ guides/70.1.1 Add a Servlet, Filter or Listener using a Spring bean.md) + * [70.1.2 使用classpath扫描添加Servlets, Filters和Listeners](IX. ‘How-to’ guides/70.1.2 Add Servlets, Filters, and Listeners using classpath scanning.md) + * [70.2 改变HTTP端口](IX. ‘How-to’ guides/70.2 Change the HTTP port.md) + * [70.3 使用随机未分配的HTTP端口](IX. ‘How-to’ guides/70.3 Use a random unassigned HTTP port.md) + * [70.4 发现运行时的HTTP端口](IX. ‘How-to’ guides/70.4 Discover the HTTP port at runtime.md) + * [70.5 配置SSL](IX. ‘How-to’ guides/70.5 Configure SSL.md) + * [70.6 配置访问日志](IX. ‘How-to’ guides/70.6 Configure Access Logging.md) + * [70.7 在前端代理服务器后使用](IX. ‘How-to’ guides/70.7 Use behind a front-end proxy server.md) + * [70.7.1 自定义Tomcat代理配置](IX. ‘How-to’ guides/70.7.1 Customize Tomcat’s proxy configuration.md) + * [70.8 配置Tomcat](IX. ‘How-to’ guides/70.8 Configure Tomcat.md) + * [70.9 启用Tomcat的多连接器](IX. ‘How-to’ guides/70.9 Enable Multiple Connectors with Tomcat.md) + * [70.10 使用Tomcat的LegacyCookieProcessor](IX. ‘How-to’ guides/70.10 Use Tomcat’s LegacyCookieProcessor.md) + * [70.11 使用Jetty替代Tomcat](IX. ‘How-to’ guides/70.11 Use Jetty instead of Tomcat.md) + * [70.12 配置Jetty](IX. ‘How-to’ guides/70.12 Configure Jetty.md) + * [70.13 使用Undertow替代Tomcat](IX. ‘How-to’ guides/70.13 Use Undertow instead of Tomcat.md) + * [70.14 配置Undertow](IX. ‘How-to’ guides/70.14 Configure Undertow.md) + * [70.15 启用Undertow的多监听器](IX. ‘How-to’ guides/70.15 Enable Multiple Listeners with Undertow.md) + * [70.16 使用Tomcat 7.x或8.0](IX. ‘How-to’ guides/70.16 Use Tomcat 7.x or 8.0.md) + * [70.16.1 通过Maven使用Tomcat 7.x或8.0](IX. ‘How-to’ guides/70.16.1 Use Tomcat 7.x or 8.0 with Maven.md) + * [70.16.2 通过Gradle使用Tomcat7.x或8.0](IX. ‘How-to’ guides/70.16.2 Use Tomcat 7.x or 8.0 with Gradle.md) + * [70.17 使用Jetty9.2](IX. ‘How-to’ guides/70.17 Use Jetty 9.2.md) + * [70.17.1 通过Maven使用Jetty9.2](IX. ‘How-to’ guides/70.17.1 Use Jetty9.2 with Maven.md) + * [70.17.2 通过Gradle使用Jetty 9.2](IX. ‘How-to’ guides/70.17.2 Use Jetty 9.2 with Gradle.md) + * [70.18 使用Jetty 8](IX. ‘How-to’ guides/70.18 Use Jetty 8.md) + * [70.18.1 通过Maven使用Jetty8](IX. ‘How-to’ guides/70.18.1 Use Jetty 8 with Maven.md) + * [70.18.2 通过Gradle使用Jetty8](IX. ‘How-to’ guides/70.18.2 Use Jetty 8 with Gradle.md) + * [70.19 使用@ServerEndpoint创建WebSocket端点](IX. ‘How-to’ guides/70.19 Create WebSocket endpoints using @ServerEndpoint.md) + * [71. Spring MVC](IX. ‘How-to’ guides/71. Spring MVC.md) + * [71.1 编写JSON REST服务](IX. ‘How-to’ guides/71.1 Write a JSON REST service.md) + * [71.2 编写XML REST服务](IX. ‘How-to’ guides/71.2 Write an XML REST service.md) + * [71.3 自定义Jackson ObjectMapper](IX. ‘How-to’ guides/71.3 Customize the Jackson ObjectMapper.md) + * [71.4 自定义@ResponseBody渲染](IX. ‘How-to’ guides/71.4 Customize the @ResponseBody rendering.md) + * [71.5 处理Multipart文件上传](IX. ‘How-to’ guides/71.5 Handling Multipart File Uploads.md) + * [71.6 关闭Spring MVC DispatcherServlet](IX. ‘How-to’ guides/71.6 Switch off the Spring MVC DispatcherServlet.md) + * [71.7 关闭默认的MVC配置](IX. ‘How-to’ guides/71.7 Switch off the Default MVC configuration.md) + * [71.8 自定义ViewResolvers](IX. ‘How-to’ guides/71.8 Customize ViewResolvers.md) + * [71.9 Velocity](IX. ‘How-to’ guides/71.9 Velocity.md) + * [71.10 使用Thymeleaf 3](IX. ‘How-to’ guides/71.10 Use Thymeleaf 3.md) + * [73. 日志](IX. ‘How-to’ guides/73. Logging.md) + * [73.1 配置Logback](IX. ‘How-to’ guides/73.1 Configure Logback for logging.md) + * [73.1.1 配置logback只输出到文件](IX. ‘How-to’ guides/73.1.1 Configure logback for file only output.md) + * [73.2 配置Log4j](IX. ‘How-to’ guides/73.2 Configure Log4j for logging.md) + * [73.2.1 使用YAML或JSON配置Log4j2](IX. ‘How-to’ guides/73.2.1 Use YAML or JSON to configure Log4j 2.md) + * [74. 数据访问](IX. ‘How-to’ guides/74. Data Access.md) + * [74.1 配置数据源](IX. ‘How-to’ guides/74.1 Configure a DataSource.md) + * [74.2 配置两个数据源](IX. ‘How-to’ guides/74.2 Configure Two DataSources.md) + * [74.3 使用Spring Data仓库](IX. ‘How-to’ guides/74.3 Use Spring Data repositories.md) + * [74.4 从Spring配置分离@Entity定义](IX. ‘How-to’ guides/74.4 Separate @Entity definitions from Spring configuration.md) + * [74.5 配置JPA属性](IX. ‘How-to’ guides/74.5 Configure JPA properties.md) + * [74.6 使用自定义EntityManagerFactory](IX. ‘How-to’ guides/74.6 Use a custom EntityManagerFactory.md) + * [74.7 使用两个EntityManagers](IX. ‘How-to’ guides/74.7 Use Two EntityManagers.md) + * [74.8 使用普通的persistence.xml](IX. ‘How-to’ guides/74.8 Use a traditional persistence.xml.md) + * [74.9 使用Spring Data JPA和Mongo仓库](IX. ‘How-to’ guides/74.9 Use Spring Data JPA and Mongo repositories.md) + * [74.10 将Spring Data仓库暴露为REST端点](IX. ‘How-to’ guides/74.10 Expose Spring Data repositories as REST endpoint.md) + * [74.11 配置JPA使用的组件](IX. ‘How-to’ guides/74.11 Configure a component that is used by JPA.md) + * [75. 数据库初始化](IX. ‘How-to’ guides/75. Database initialization.md) + * [75.1 使用JPA初始化数据库](IX. ‘How-to’ guides/75.1 Initialize a database using JPA.md) + * [75.2 使用Hibernate初始化数据库](IX. ‘How-to’ guides/75.2 Initialize a database using Hibernate.md) + * [75.3 使用Spring JDBC初始化数据库](IX. ‘How-to’ guides/75.3 Initialize a database using Spring JDBC.md) + * [75.4 初始化Spring Batch数据库](IX. ‘How-to’ guides/75.4 Initialize a Spring Batch database.md) + * [75.5 使用高级数据迁移工具](IX. ‘How-to’ guides/75.5 Use a higher level database migration tool.md) + * [75.5.1 启动时执行Flyway数据库迁移](IX. ‘How-to’ guides/75.5.1 Execute Flyway database migrations on startup.md) + * [75.5.2 启动时执行Liquibase数据库迁移](IX. ‘How-to’ guides/75.5.2 Execute Liquibase database migrations on startup.md) + * [76. 批处理应用](IX. ‘How-to’ guides/76. Batch applications.md) + * [76.1 在启动时执行Spring Batch作业](IX. ‘How-to’ guides/76.1 Execute Spring Batch jobs on startup.md) + * [77. 执行器](IX. ‘How-to’ guides/77. Actuator.md) + * [77.1 改变HTTP端口或执行器端点的地址](IX. ‘How-to’ guides/77.1 Change the HTTP port or address of the actuator endpoints.md) + * [77.2 自定义WhiteLabel错误页面](IX. ‘How-to’ guides/77.2 Customize the ‘whitelabel’ error page.md) + * [77.3 Actuator和Jersey](IX. ‘How-to’ guides/77.3 Actuator and Jersey.md) + * [78. 安全](IX. ‘How-to’ guides/78. Security.md) + * [78.1 关闭Spring Boot安全配置](IX. ‘How-to’ guides/78.1 Switch off the Spring Boot security configuration.md) + * [78.2 改变AuthenticationManager并添加用户账号](IX. ‘How-to’ guides/78.2 Change the AuthenticationManager and add user accounts.md) + * [78.3 当前端使用代理服务器时启用HTTPS](IX. ‘How-to’ guides/78.3 Enable HTTPS when running behind a proxy server.md) + * [79. 热交换](IX. ‘How-to’ guides/79. Hot swapping.md) + * [79.1 重新加载静态内容](IX. ‘How-to’ guides/79.1 Reload static content.md) + * [79.2. 在不重启容器的情况下重新加载模板](IX. ‘How-to’ guides/79.2. Reload templates without restarting the container.md) + * [79.2.1 Thymeleaf模板](IX. ‘How-to’ guides/79.2.1 Thymeleaf templates.md) + * [79.2.2 FreeMarker模板](IX. ‘How-to’ guides/79.2.2 FreeMarker templates.md) + * [79.2.3 Groovy模板](IX. ‘How-to’ guides/79.2.3 Groovy templates.md) + * [79.2.4 Velocity模板](IX. ‘How-to’ guides/79.2.4 Velocity templates.md) + * [79.3 应用快速重启](IX. ‘How-to’ guides/79.3 Fast application restarts.md) + * [79.4 在不重启容器的情况下重新加载Java类](IX. ‘How-to’ guides/79.4 Reload Java classes without restarting the container.md) + * [79.4.1 使用Maven配置Spring Loaded](IX. ‘How-to’ guides/79.4.1 Configuring Spring Loaded for use with Maven.md) + * [79.4.2 使用Gradle和IntelliJ IDEA配置Spring Loaded](IX. ‘How-to’ guides/79.4.2 Configuring Spring Loaded for use with Gradle and IntelliJ.md) + * [80. 构建](IX. ‘How-to’ guides/80. Build.md) + * [80.1 生成构建信息](IX. ‘How-to’ guides/80.1 Generate build information.md) + * [80.2 生成Git信息](IX. ‘How-to’ guides/80.2 Generate git information.md) + * [80.3 自定义依赖版本](IX. ‘How-to’ guides/80.3 Customize dependency versions.md) + * [80.4 使用Maven创建可执行JAR](IX. ‘How-to’ guides/80.4 Create an executable JAR with Maven.md) + * [80.5 将Spring Boot应用作为依赖](IX. ‘How-to’ guides/80.5 Use a Spring Boot application as a dependency.md) + * [80.6 在可执行jar运行时提取特定的版本](IX. ‘How-to’ guides/80.6 Extract specific libraries when an executable jar runs.md) + * [80.7 使用排除创建不可执行的JAR](IX. ‘How-to’ guides/80.7 Create a non-executable JAR with exclusions.md) + * [80.8 远程调试使用Maven启动的Spring Boot项目](IX. ‘How-to’ guides/80.8 Remote debug a Spring Boot application started with Maven.md) + * [80.9 远程调试使用Gradle启动的Spring Boot项目](IX. ‘How-to’ guides/80.9 Remote debug a Spring Boot application started with Gradle.md) + * [80.10 使用Ant构建可执行存档](IX. ‘How-to’ guides/80.10 Build an executable archive from Ant without using spring-boot-antlib.md) + * [80.11 如何使用Java6](IX. ‘How-to’ guides/80.11 How to use Java 6.md) + * [80.11.1 内嵌Servlet容器兼容性](IX. ‘How-to’ guides/80.11.1 Embedded servlet container compatibility.md) + * [80.11.2 Jackson](IX. ‘How-to’ guides/80.11.2 Jackson.md) + * [80.11.3 JTA API兼容性](IX. ‘How-to’ guides/80.11.3 JTA API compatibility.md) + * [81. 传统部署](IX. ‘How-to’ guides/81. Traditional deployment.md) + * [81.1 创建可部署的war文件](IX. ‘How-to’ guides/81.1 Create a deployable war file.md) + * [81.2 为老的servlet容器创建可部署的war文件](IX. ‘How-to’ guides/81.2 Create a deployable war file for older servlet containers.md) + * [81.3 将现有的应用转换为Spring Boot](IX. ‘How-to’ guides/81.3 Convert an existing application to Spring Boot.md) + * [81.4 部署WAR到Weblogic](IX. ‘How-to’ guides/81.4 Deploying a WAR to Weblogic.md) + * [81.5 部署WAR到老的(Servlet2.5)容器](IX. ‘How-to’ guides/81.5 Deploying a WAR in an Old (Servlet 2.5) Container.md) * [X.附录](X. Appendices/README.md) * [附录A. 常见应用属性](X. Appendices/A. Common application properties.md) * [附录B. 配置元数据](X. Appendices/B. Configuration meta-data.md) diff --git a/V. Spring Boot Actuator/40. Endpoints.md b/V. Spring Boot Actuator/40. Endpoints.md deleted file mode 100644 index c6884522..00000000 --- a/V. Spring Boot Actuator/40. Endpoints.md +++ /dev/null @@ -1,23 +0,0 @@ -### 40. 端点 - -执行器端点允许你监控应用及与应用进行交互。Spring Boot包含很多内置的端点,你也可以添加自己的。例如,health端点提供了应用的基本健康信息。 - -端点暴露的方式取决于你采用的技术类型。大部分应用选择HTTP监控,端点的ID映射到一个URL。例如,默认情况下,health端点将被映射到/health。 - -下面的端点都是可用的: - -| ID | 描述 |敏感(Sensitive)| -| ---- | :----- | :----- | -|autoconfig|显示一个auto-configuration的报告,该报告展示所有auto-configuration候选者及它们被应用或未被应用的原因|true| -|beans|显示一个应用中所有Spring Beans的完整列表|true| -|configprops|显示一个所有@ConfigurationProperties的整理列表|true| -|dump|执行一个线程转储|true| -|env|暴露来自Spring ConfigurableEnvironment的属性|true| -|health|展示应用的健康信息(当使用一个未认证连接访问时显示一个简单的'status',使用认证连接访问则显示全部信息详情)|false| -|info|显示任意的应用信息|false| -|metrics|展示当前应用的'指标'信息|true| -|mappings|显示一个所有@RequestMapping路径的整理列表|true| -|shutdown|允许应用以优雅的方式关闭(默认情况下不启用)|true| -|trace|显示trace信息(默认为最新的一些HTTP请求)|true| - -**注**:根据一个端点暴露的方式,sensitive参数可能会被用做一个安全提示。例如,在使用HTTP访问sensitive端点时需要提供用户名/密码(如果没有启用web安全,可能会简化为禁止访问该端点)。 diff --git a/V. Spring Boot Actuator/40.1. Customizing endpoints.md b/V. Spring Boot Actuator/40.1. Customizing endpoints.md deleted file mode 100644 index 3cb88c2d..00000000 --- a/V. Spring Boot Actuator/40.1. Customizing endpoints.md +++ /dev/null @@ -1,15 +0,0 @@ -### 40.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 -``` diff --git a/V. Spring Boot Actuator/40.2. Health information.md b/V. Spring Boot Actuator/40.2. Health information.md deleted file mode 100644 index e73d622d..00000000 --- a/V. Spring Boot Actuator/40.2. Health information.md +++ /dev/null @@ -1,5 +0,0 @@ -### 40.2. 健康信息 - -健康信息可以用来检查应用的运行状态。它经常被监控软件用来提醒人们生产系统是否停止。health端点暴露的默认信息取决于端点是如何被访问的。对于一个非安全,未认证的连接只返回一个简单的'status'信息。对于一个安全或认证过的连接其他详细信息也会展示(具体参考[Section 41.6, “HTTP Health endpoint access restrictions” ](41.6. HTTP Health endpoint 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包含很多auto-configured的HealthIndicators,你也可以写自己的。 diff --git a/V. Spring Boot Actuator/40.3. Security with HealthIndicators.md b/V. Spring Boot Actuator/40.3. Security with HealthIndicators.md deleted file mode 100644 index b7b19405..00000000 --- a/V. Spring Boot Actuator/40.3. Security with HealthIndicators.md +++ /dev/null @@ -1,5 +0,0 @@ -### 40.3. 安全与HealthIndicators - -HealthIndicators返回的信息常常性质上有点敏感。例如,你可能不想将数据库服务器的详情发布到外面。因此,在使用一个未认证的HTTP连接时,默认只会暴露健康状态(health status)。如果想将所有的健康信息暴露出去,你可以把endpoints.health.sensitive设置为false。 - -为防止'拒绝服务'攻击,Health响应会被缓存。你可以使用`endpoints.health.time-to-live`属性改变默认的缓存时间(1000毫秒)。 diff --git a/V. Spring Boot Actuator/40.3.1. Auto-configured-HealthIndicators.md b/V. Spring Boot Actuator/40.3.1. Auto-configured-HealthIndicators.md deleted file mode 100644 index cd4267b9..00000000 --- a/V. Spring Boot Actuator/40.3.1. Auto-configured-HealthIndicators.md +++ /dev/null @@ -1,12 +0,0 @@ -### 40.3.1. 自动配置的HealthIndicators - -下面的HealthIndicators会被Spring Boot自动配置(在合适的时候): - -|名称|描述| -|----|:-----| -|[DiskSpaceHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java)|低磁盘空间检测| -|[DataSourceHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java)|检查是否能从DataSource获取连接| -|[MongoHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MongoHealthIndicator.java)|检查一个Mongo数据库是否可用(up)| -|[RabbitHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java)|检查一个Rabbit服务器是否可用(up)| -|[RedisHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java)|检查一个Redis服务器是否可用(up)| -|[SolrHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/SolrHealthIndicator.java)|检查一个Solr服务器是否可用(up)| diff --git a/V. Spring Boot Actuator/40.3.2. Writing custom HealthIndicators.md b/V. Spring Boot Actuator/40.3.2. Writing custom HealthIndicators.md deleted file mode 100644 index a5db2a9a..00000000 --- a/V. Spring Boot Actuator/40.3.2. Writing custom HealthIndicators.md +++ /dev/null @@ -1,28 +0,0 @@ -### 40.3.2. 编写自定义HealthIndicators - -想提供自定义健康信息,你可以注册实现了[HealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java)接口的Spring beans。你需要提供一个health()方法的实现,并返回一个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(); - } - -} -``` -除了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属性文件中: -```java -management.health.status.order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP -``` -如果使用HTTP访问health端点,你可能想要注册自定义的status,并使用HealthMvcEndpoint进行映射。例如,你可以将FATAL映射为HttpStatus.SERVICE_UNAVAILABLE。 diff --git a/V. Spring Boot Actuator/40.4. Custom application info information.md b/V. Spring Boot Actuator/40.4. Custom application info information.md deleted file mode 100644 index 2774a6e1..00000000 --- a/V. Spring Boot Actuator/40.4. Custom application info information.md +++ /dev/null @@ -1,8 +0,0 @@ -### 40.4. 自定义应用info信息 - -通过设置Spring属性info.*,你可以定义info端点暴露的数据。所有在info关键字下的Environment属性都将被自动暴露。例如,你可以将下面的配置添加到application.properties: -```java -info.app.name=MyService -info.app.description=My awesome service -info.app.version=1.0.0 -``` diff --git a/V. Spring Boot Actuator/40.4.1. Automatically expand info properties at build time.md b/V. Spring Boot Actuator/40.4.1. Automatically expand info properties at build time.md deleted file mode 100644 index e7019f7f..00000000 --- a/V. Spring Boot Actuator/40.4.1. Automatically expand info properties at build time.md +++ /dev/null @@ -1,55 +0,0 @@ -### 40.4.1. 在构建时期自动扩展info属性 - -你可以使用已经存在的构建配置自动扩展info属性,而不是对在项目构建配置中存在的属性进行硬编码。这在Maven和Gradle都是可能的。 - -**使用Maven自动扩展属性** - -对于Maven项目,你可以使用资源过滤来自动扩展info属性。如果使用spring-boot-starter-parent,你可以通过`@..@`占位符引用Maven的'project properties'。 -```java -project.artifactId=myproject -project.name=Demo -project.version=X.X.X.X -project.description=Demo project for info endpoint -info.build.artifact=@project.artifactId@ -info.build.name=@project.name@ -info.build.description=@project.description@ -info.build.version=@project.version@ -``` -**注**:在上面的示例中,我们使用project.*来设置一些值以防止由于某些原因Maven的资源过滤没有开启。Maven目标`spring-boot:run`直接将`src/main/resources`添加到classpath下(出于热加载的目的)。这就绕过了资源过滤和自动扩展属性的特性。你可以使用`exec:java`替换该目标或自定义插件的配置,具体参考[plugin usage page](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/usage.html)。 - -如果你不使用starter parent,在你的pom.xml你需要添加(处于元素内): -```xml - - - src/main/resources - true - - -``` -和(处于内): -```xml - - org.apache.maven.plugins - maven-resources-plugin - 2.6 - - - @ - - - -``` -**使用Gradle自动扩展属性** - -通过配置Java插件的processResources任务,你也可以自动使用来自Gradle项目的属性扩展info属性。 -```java -processResources { - expand(project.properties) -} -``` -然后你可以通过占位符引用Gradle项目的属性: -```java -info.build.name=${name} -info.build.description=${description} -info.build.version=${version} -``` diff --git a/V. Spring Boot Actuator/40.4.2. Git commit information.md b/V. Spring Boot Actuator/40.4.2. Git commit information.md deleted file mode 100644 index f21d740e..00000000 --- a/V. Spring Boot Actuator/40.4.2. Git commit information.md +++ /dev/null @@ -1,16 +0,0 @@ -### 40.4.2. Git提交信息 - -info端点的另一个有用特性是,当项目构建完成后,它可以发布关于你的git源码仓库状态的信息。如果在你的jar中包含一个git.properties文件,git.branch和git.commit属性将被加载。 - -对于Maven用户,`spring-boot-starter-parent` POM包含一个能够产生git.properties文件的预配置插件。只需要简单的将下面的声明添加到你的POM中: -```xml - - - - pl.project13.maven - git-commit-id-plugin - - - -``` -对于Gradle用户可以使用一个相似的插件[gradle-git](https://github.com/ajoberstar/gradle-git),尽管为了产生属性文件可能需要稍微多点工作。 diff --git a/V. Spring Boot Actuator/41.1. Securing sensitive endpoints.md b/V. Spring Boot Actuator/41.1. Securing sensitive endpoints.md deleted file mode 100644 index a05e3804..00000000 --- a/V. Spring Boot Actuator/41.1. Securing sensitive endpoints.md +++ /dev/null @@ -1,12 +0,0 @@ -### 41.1. 保护敏感端点 - -如果你的项目中添加的有Spring Security,所有通过HTTP暴露的敏感端点都会受到保护。默认情况下会使用基本认证(basic authentication,用户名为user,密码为应用启动时在控制台打印的密码)。 - -你可以使用Spring属性改变用户名,密码和访问端点需要的安全角色。例如,你可能会在application.properties中添加下列配置: -```java -security.user.name=admin -security.user.password=secret -management.security.role=SUPERUSER -``` - -**注**:如果你不使用Spring Security,那你的HTTP端点就被公开暴露,你应该慎重考虑启用哪些端点。具体参考[Section 40.1, “Customizing endpoints”](40.1. Customizing endpoints.md)。 diff --git a/V. Spring Boot Actuator/41.2. Customizing the management server context path.md b/V. Spring Boot Actuator/41.2. Customizing the management server context path.md deleted file mode 100644 index 559629ce..00000000 --- a/V. Spring Boot Actuator/41.2. Customizing the management server context path.md +++ /dev/null @@ -1,7 +0,0 @@ -### 41.2. 自定义管理服务器的上下文路径 - -有时候将所有的管理端口划分到一个路径下是有用的。例如,你的应用可能已经将`/info`作为他用。你可以用`management.contextPath`属性为管理端口设置一个前缀: -```java -management.context-path=/manage -``` -上面的application.properties示例将把端口从`/{id}`改为`/manage/{id}`(比如,/manage/info)。 diff --git a/V. Spring Boot Actuator/41.3. Customizing the management server port.md b/V. Spring Boot Actuator/41.3. Customizing the management server port.md deleted file mode 100644 index 975c404d..00000000 --- a/V. Spring Boot Actuator/41.3. Customizing the management server port.md +++ /dev/null @@ -1,13 +0,0 @@ -### 41.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/41.4. Customizing the management server address.md b/V. Spring Boot Actuator/41.4. Customizing the management server address.md deleted file mode 100644 index 20f32698..00000000 --- a/V. Spring Boot Actuator/41.4. Customizing the management server address.md +++ /dev/null @@ -1,9 +0,0 @@ -### 41.4. 自定义管理服务器的地址 - -你可以通过设置`management.address`属性来定义管理端点可以使用的地址。这在你只想监听内部或面向生产环境的网络,或只监听来自localhost的连接时非常有用。 - -下面的application.properties示例不允许远程管理连接: -```java -management.port=8081 -management.address=127.0.0.1 -``` diff --git a/V. Spring Boot Actuator/41.6. HTTP Health endpoint access restrictions.md b/V. Spring Boot Actuator/41.6. HTTP Health endpoint access restrictions.md deleted file mode 100644 index ba0f937a..00000000 --- a/V. Spring Boot Actuator/41.6. HTTP Health endpoint access restrictions.md +++ /dev/null @@ -1,5 +0,0 @@ -### 41.6. HTTP Health端点访问限制 - -通过health端点暴露的信息根据是否为匿名访问而不同。默认情况下,当匿名访问时,任何有关服务器的健康详情都被隐藏了,该端点只简单的指示服务器是运行(up)还是停止(down)。此外,当匿名访问时,响应会被缓存一个可配置的时间段以防止端点被用于'拒绝服务'攻击。`endpoints.health.time-to-live`属性被用来配置缓存时间(单位为毫秒),默认为1000毫秒,也就是1秒。 - -上述的限制可以被禁止,从而允许匿名用户完全访问health端点。想达到这个效果,可以将`endpoints.health.sensitive`设为`false`。 diff --git a/V. Spring Boot Actuator/42.1. Customizing MBean names.md b/V. Spring Boot Actuator/42.1. Customizing MBean names.md deleted file mode 100644 index a9aff1d0..00000000 --- a/V. Spring Boot Actuator/42.1. Customizing MBean names.md +++ /dev/null @@ -1,10 +0,0 @@ -### 42.1. 自定义MBean名称 - -MBean的名称通常产生于端点的id。例如,health端点被暴露为`org.springframework.boot/Endpoint/HealthEndpoint`。 - -如果你的应用包含多个Spring ApplicationContext,你会发现存在名称冲突。为了解决这个问题,你可以将`endpoints.jmx.uniqueNames`设置为true,这样MBean的名称总是唯一的。 - -你也可以自定义JMX域,所有的端点都在该域下暴露。这里有个application.properties示例: -```java -endpoints.jmx.domain=myapp -endpoints.jmx.uniqueNames=true diff --git a/V. Spring Boot Actuator/42.2. Disabling JMX endpoints.md b/V. Spring Boot Actuator/42.2. Disabling JMX endpoints.md deleted file mode 100644 index 20bbf8ff..00000000 --- a/V. Spring Boot Actuator/42.2. Disabling JMX endpoints.md +++ /dev/null @@ -1,6 +0,0 @@ -### 42.2. 禁用JMX端点 - -如果不想通过JMX暴露端点,你可以将`spring.jmx.enabled`属性设置为false: -```java -spring.jmx.enabled=false -``` diff --git a/V. Spring Boot Actuator/42.3.1. Customizing Jolokia.md b/V. Spring Boot Actuator/42.3.1. Customizing Jolokia.md deleted file mode 100644 index 66d9027a..00000000 --- a/V. Spring Boot Actuator/42.3.1. Customizing Jolokia.md +++ /dev/null @@ -1,6 +0,0 @@ -### 42.3.1. 自定义Jolokia - -Jolokia有很多配置,传统上一般使用servlet参数进行设置。使用Spring Boot,你可以在application.properties中通过把参数加上`jolokia.config.`前缀来设置: -```java -jolokia.config.debug=true -``` diff --git a/V. Spring Boot Actuator/42.3.2. Disabling Jolokia.md b/V. Spring Boot Actuator/42.3.2. Disabling Jolokia.md deleted file mode 100644 index 0690a99e..00000000 --- a/V. Spring Boot Actuator/42.3.2. Disabling Jolokia.md +++ /dev/null @@ -1,6 +0,0 @@ -### 42.3.2. 禁用Jolokia - -如果你正在使用Jolokia,但不想让Spring Boot配置它,只需要简单的将`endpoints.jolokia.enabled`属性设置为false: -```java -endpoints.jolokia.enabled=false -``` diff --git a/V. Spring Boot Actuator/43. Monitoring and management using a remote shell.md b/V. Spring Boot Actuator/43. Monitoring and management using a remote shell.md deleted file mode 100644 index afa9e0f1..00000000 --- a/V. Spring Boot Actuator/43. Monitoring and management using a remote shell.md +++ /dev/null @@ -1,10 +0,0 @@ -### 43. 使用远程shell来进行监控和管理 - -Spring Boot支持集成一个称为'CRaSH'的Java shell。你可以在CRaSH中使用ssh或telnet命令连接到运行的应用。为了启用远程shell支持,你只需添加`spring-boot-starter-remote-shell`的依赖: -```xml - - org.springframework.boot - spring-boot-starter-remote-shell - -``` -**注**:如果想使用telnet访问,你还需添加对`org.crsh:crsh.shell.telnet`的依赖。 diff --git a/V. Spring Boot Actuator/43.1. Connecting to the remote shell.md b/V. Spring Boot Actuator/43.1. Connecting to the remote shell.md deleted file mode 100644 index f3646dbc..00000000 --- a/V. Spring Boot Actuator/43.1. Connecting to the remote shell.md +++ /dev/null @@ -1,20 +0,0 @@ -### 43.1. 连接远程shell - -默认情况下,远程shell监听端口2000以等待连接。默认用户名为`user`,密码为随机生成的,并且在输出日志中会显示。如果应用使用Spring Security,该shell默认使用[相同的配置](../IV. Spring Boot features/27. Security.md)。如果不是,将使用一个简单的认证策略,你可能会看到类似这样的信息: -```java -Using default password for shell access: ec03e16c-4cf4-49ee-b745-7c8255c1dd7e -``` -Linux和OSX用户可以使用`ssh`连接远程shell,Windows用户可以下载并安装[PuTTY](http://www.putty.org/)。 -```shell -$ ssh -p 2000 user@localhost - -user@localhost's password: - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ -( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v1.3.0.BUILD-SNAPSHOT) on myhost -``` -输入help可以获取一系列命令的帮助。Spring boot提供`metrics`,`beans`,`autoconfig`和`endpoint`命令。 diff --git a/V. Spring Boot Actuator/43.1.1. Remote shell credentials.md b/V. Spring Boot Actuator/43.1.1. Remote shell credentials.md deleted file mode 100644 index 10b5fb19..00000000 --- a/V. Spring Boot Actuator/43.1.1. Remote shell credentials.md +++ /dev/null @@ -1,3 +0,0 @@ -### 43.1.1. 远程shell证书 - -你可以使用`shell.auth.simple.user.name`和`shell.auth.simple.user.password`属性配置自定义的连接证书。也可以使用Spring Security的AuthenticationManager处理登录职责。具体参考Javadoc[CrshAutoConfiguration](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/api/org/springframework/boot/actuate/autoconfigure/CrshAutoConfiguration.html)和[ShellProperties](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/api/org/springframework/boot/actuate/autoconfigure/ShellProperties.html)。 diff --git a/V. Spring Boot Actuator/43.2.1. Remote shell commands.md b/V. Spring Boot Actuator/43.2.1. Remote shell commands.md deleted file mode 100644 index b23b3c57..00000000 --- a/V. Spring Boot Actuator/43.2.1. Remote shell commands.md +++ /dev/null @@ -1,33 +0,0 @@ -### 43.2.1. 远程shell命令 - -你可以使用Groovy或Java编写其他的shell命令(具体参考CRaSH文档)。默认情况下,Spring Boot会搜索以下路径的命令: -* `classpath*:/commands/**` -* `classpath*:/crash/commands/**` - -**注**:可以通过`shell.commandPathPatterns`属性改变搜索路径。 - -下面是一个从`src/main/resources/commands/hello.groovy`加载的'hello world'命令: -```java -package commands - -import org.crsh.cli.Usage -import org.crsh.cli.Command - -class hello { - - @Usage("Say Hello") - @Command - def main(InvocationContext context) { - return "Hello" - } - -} -``` -Spring Boot将一些额外属性添加到了InvocationContext,你可以在命令中访问它们: - -|属性名称|描述| -|------|:------| -|spring.boot.version|Spring Boot的版本| -|spring.version|Spring框架的核心版本| -|spring.beanfactory|获取Spring的BeanFactory| -|spring.environment|获取Spring的Environment| diff --git a/V. Spring Boot Actuator/43.2.2. Remote shell plugins.md b/V. Spring Boot Actuator/43.2.2. Remote shell plugins.md deleted file mode 100644 index ce34ae49..00000000 --- a/V. Spring Boot Actuator/43.2.2. Remote shell plugins.md +++ /dev/null @@ -1,5 +0,0 @@ -### 43.2.2. 远程shell插件 - -除了创建新命令,也可以扩展CRaSH shell的其他特性。所有继承`org.crsh.plugin.CRaSHPlugin`的Spring Beans将自动注册到shell。 - -具体查看[CRaSH参考文档](http://www.crashub.org/)。 diff --git a/V. Spring Boot Actuator/44. Metrics.md b/V. Spring Boot Actuator/44. Metrics.md deleted file mode 100644 index f0bb7e53..00000000 --- a/V. Spring Boot Actuator/44. Metrics.md +++ /dev/null @@ -1,37 +0,0 @@ - -### 44. 度量指标(Metrics) - -Spring Boot执行器包括一个支持'gauge'和'counter'级别的度量指标服务。'gauge'记录一个单一值;'counter'记录一个增量(增加或减少)。同时,Spring Boot提供一个[PublicMetrics](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/PublicMetrics.java)接口,你可以实现它,从而暴露以上两种机制不能记录的指标。具体参考[SystemPublicMetrics](http://github.com/spring-projects/spring-boot/tree/master/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)响应。双asterix(star-star)来自于被Spring MVC `/**`匹配到的一个请求(通常为一个静态资源)。 - -`gauge`级别展示了一个请求的最后响应时间。所以,`root`的最后请求被响应耗时2毫秒,`/metrics`耗时3毫秒。 diff --git a/V. Spring Boot Actuator/44.1. System metrics.md b/V. Spring Boot Actuator/44.1. System metrics.md deleted file mode 100644 index fc616aa5..00000000 --- a/V. Spring Boot Actuator/44.1. System metrics.md +++ /dev/null @@ -1,13 +0,0 @@ -### 44.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/44.2. DataSource metrics.md b/V. Spring Boot Actuator/44.2. DataSource metrics.md deleted file mode 100644 index 60445069..00000000 --- a/V. Spring Boot Actuator/44.2. DataSource metrics.md +++ /dev/null @@ -1,14 +0,0 @@ -### 44.2. 数据源指标 - -Spring Boot会为你应用中定义的支持的DataSource暴露以下指标: -- 最大连接数(datasource.xxx.max) -- 最小连接数(datasource.xxx.min) -- 活动连接数(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/44.3. Tomcat session metrics.md b/V. Spring Boot Actuator/44.3. Tomcat session metrics.md deleted file mode 100644 index e2b42ed6..00000000 --- a/V. Spring Boot Actuator/44.3. Tomcat session metrics.md +++ /dev/null @@ -1,4 +0,0 @@ -### 44.3. Tomcat session指标 - -如果你使用Tomcat作为内嵌的servlet容器,session指标将被自动暴露出去。 -`httpsessions.active`和`httpsessions.max`提供了活动的和最大的session数量。 diff --git a/V. Spring Boot Actuator/44.4. Recording your own metrics.md b/V. Spring Boot Actuator/44.4. Recording your own metrics.md deleted file mode 100644 index 353d42b4..00000000 --- a/V. Spring Boot Actuator/44.4. Recording your own metrics.md +++ /dev/null @@ -1,28 +0,0 @@ - -### 44.4. 记录自己的指标 - -想要记录你自己的指标,只需将[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/44.5. Adding your own public metrics.md b/V. Spring Boot Actuator/44.5. Adding your own public metrics.md deleted file mode 100644 index 7cc55202..00000000 --- a/V. Spring Boot Actuator/44.5. Adding your own public metrics.md +++ /dev/null @@ -1,3 +0,0 @@ -### 44.5. 添加你自己的公共指标 - -想要添加额外的,每次指标端点被调用时都会重新计算的度量指标,只需简单的注册其他的PublicMetrics实现bean(s)。默认情况下,端点会聚合所有这样的beans,通过定义自己的MetricsEndpoint可以轻易改变这种情况。 diff --git a/V. Spring Boot Actuator/44.6. Metric repositories.md b/V. Spring Boot Actuator/44.6. Metric repositories.md deleted file mode 100644 index 7d2f055b..00000000 --- a/V. Spring Boot Actuator/44.6. Metric repositories.md +++ /dev/null @@ -1,5 +0,0 @@ -### 44.6. 指标仓库 - -通过绑定一个[MetricRepository](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/MetricRepository.java)来实现指标服务。`MetricRepository`负责存储和追溯指标信息。Spring Boot提供一个`InMemoryMetricRepository`和一个`RedisMetricRepository`(默认使用in-memory仓库),不过你可以编写自己的`MetricRepository`。`MetricRepository`接口实际是`MetricReader`接口和`MetricWriter`接口的上层组合。具体参考[Javadoc](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/api/org/springframework/boot/actuate/metrics/repository/MetricRepository.html) - -没有什么能阻止你直接将`MetricRepository`的数据导入应用中的后端存储,但我们建议你使用默认的`InMemoryMetricRepository`(如果担心堆使用情况,你可以使用自定义的Map实例),然后通过一个scheduled export job填充后端仓库(意思是先将数据保存到内存中,然后通过异步job将数据持久化到数据库,可以提高系统性能)。通过这种方式,你可以将指标数据缓存到内存中,然后通过低频率或批量导出来减少网络拥堵。Spring Boot提供一个`Exporter`接口及一些帮你开始的基本实现。 diff --git a/V. Spring Boot Actuator/44.7. Dropwizard Metrics.md b/V. Spring Boot Actuator/44.7. Dropwizard Metrics.md deleted file mode 100644 index e0d765b8..00000000 --- a/V. Spring Boot Actuator/44.7. Dropwizard Metrics.md +++ /dev/null @@ -1,5 +0,0 @@ -### 44.7. Dropwizard指标 - -[Dropwizard ‘Metrics’库](https://dropwizard.github.io/metrics/)的用户会发现Spring Boot指标被发布到了`com.codahale.metrics.MetricRegistry`。当你声明对`io.dropwizard.metrics:metrics-core`库的依赖时会创建一个默认的`com.codahale.metrics.MetricRegistry` Spring bean;如果需要自定义,你可以注册自己的@Bean实例。来自于`MetricRegistry`的指标也是自动通过`/metrics`端点暴露的。 - -用户可以通过使用合适类型的指标名称作为前缀来创建Dropwizard指标(比如,`histogram.*`, `meter.*`)。 diff --git a/V. Spring Boot Actuator/44.8. Message channel integration.md b/V. Spring Boot Actuator/44.8. Message channel integration.md deleted file mode 100644 index 215aecb1..00000000 --- a/V. Spring Boot Actuator/44.8. Message channel integration.md +++ /dev/null @@ -1,3 +0,0 @@ -### 44.8. 消息渠道集成 - -如果你的classpath下存在'Spring Messaging' jar,一个名为`metricsChannel`的`MessageChannel`将被自动创建(除非已经存在一个)。此外,所有的指标更新事件作为'messages'发布到该渠道上。订阅该渠道的客户端可以进行额外的分析或行动。 diff --git a/V. Spring Boot Actuator/45. Auditing.md b/V. Spring Boot Actuator/45. Auditing.md deleted file mode 100644 index 19f49f07..00000000 --- a/V. Spring Boot Actuator/45. Auditing.md +++ /dev/null @@ -1,5 +0,0 @@ -### 45. 审计 - -Spring Boot执行器具有一个灵活的审计框架,一旦Spring Security处于活动状态(默认抛出'authentication success','failure'和'access denied'异常),它就会发布事件。这对于报告非常有用,同时可以基于认证失败实现一个锁定策略。 - -你也可以使用审计服务处理自己的业务事件。为此,你可以将存在的`AuditEventRepository`注入到自己的组件,并直接使用它,或者只是简单地通过Spring `ApplicationEventPublisher`发布`AuditApplicationEvent`(使用`ApplicationEventPublisherAware`)。 diff --git a/V. Spring Boot Actuator/39. Enabling production-ready features.md b/V. Spring Boot Actuator/45. Enabling production-ready features.md similarity index 56% rename from V. Spring Boot Actuator/39. Enabling production-ready features.md rename to V. Spring Boot Actuator/45. Enabling production-ready features.md index a2e9f1b8..ee2ee5ad 100644 --- a/V. Spring Boot Actuator/39. Enabling production-ready features.md +++ b/V. Spring Boot Actuator/45. Enabling production-ready features.md @@ -1,10 +1,9 @@ -### 39. 开启production-ready特性 +### 45. 开启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’依赖。 -[spring-boot-actuator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator)模块提供了Spring Boot所有的production-ready特性。启用该特性的最简单方式就是添加对spring-boot-starter-actuator ‘Starter POM’的依赖。 +**执行器(Actuator)的定义**:执行器是一个制造业术语,指的是用于移动或控制东西的一个机械装置,一个很小的改变就能让执行器产生大量的运动。 -**执行器(Actuator)的定义**:执行器是一个制造业术语,指的是用于移动或控制东西的一个机械装置。一个很小的改变就能让执行器产生大量的运动。 - -基于Maven的项目想要添加执行器只需添加下面的'starter'依赖: +按以下配置为Maven项目添加执行器: ```xml diff --git a/V. Spring Boot Actuator/46. Endpoints.md b/V. Spring Boot Actuator/46. Endpoints.md new file mode 100644 index 00000000..eabbf04e --- /dev/null +++ b/V. Spring Boot Actuator/46. Endpoints.md @@ -0,0 +1,33 @@ +### 46. 端点 +执行器端点(endpoints)可用于监控应用及与应用进行交互,Spring Boot包含很多内置的端点,你也可以添加自己的。例如,`health`端点提供了应用的基本健康信息。 +端点暴露的方式取决于你采用的技术类型,大部分应用选择HTTP监控,端点的ID映射到一个URL。例如,`health`端点默认映射到`/health`。 + +下面的端点都是可用的: + +| ID | 描述 |是否敏感| +| ---- | :----- | :----- | +|`actuator`|为其他端点提供基于超文本的导航页面,需要添加Spring HATEOAS依赖|true| +|`autoconfig`|显示一个自动配置类的报告,该报告展示所有自动配置候选者及它们被应用或未被应用的原因|true| +|`beans`|显示一个应用中所有Spring Beans的完整列表|true| +|`configprops`|显示一个所有`@ConfigurationProperties`的集合列表|true| +|`dump`|执行一个线程转储|true| +|`env`|暴露来自Spring `ConfigurableEnvironment`的属性|true| +|`flyway`|显示数据库迁移路径,如果有的话|true| +|`health`|展示应用的健康信息(当使用一个未认证连接访问时显示一个简单的'status',使用认证连接访问则显示全部信息详情)|false| +|`info`|显示任意的应用信息|false| +|`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/46.1 Customizing endpoints.md b/V. Spring Boot Actuator/46.1 Customizing endpoints.md new file mode 100644 index 00000000..ab6d39bb --- /dev/null +++ b/V. Spring Boot Actuator/46.1 Customizing endpoints.md @@ -0,0 +1,19 @@ +### 46.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/46.1. Custom tracing.md b/V. Spring Boot Actuator/46.1. Custom tracing.md deleted file mode 100644 index fb69b427..00000000 --- a/V. Spring Boot Actuator/46.1. Custom tracing.md +++ /dev/null @@ -1,5 +0,0 @@ -### 46.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`方法接收一个将被转化为JSON的`Map`结构,该数据将被记录下来。 - -默认情况下,使用的`InMemoryTraceRepository`将存储最新的100个事件。如果需要扩展该容量,你可以定义自己的`InMemoryTraceRepository`实例。如果需要,你可以创建自己的替代`TraceRepository`实现。 diff --git a/V. Spring Boot Actuator/46.2 Hypermedia for actuator MVC endpoints.md b/V. Spring Boot Actuator/46.2 Hypermedia for actuator MVC endpoints.md new file mode 100644 index 00000000..cc49caef --- /dev/null +++ b/V. Spring Boot Actuator/46.2 Hypermedia for actuator MVC endpoints.md @@ -0,0 +1,6 @@ +###46.2 执行器MVC端点的超媒体支持 +如果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),也就是使用一个“导航页”汇总所有端点链接,该页面默认路径为`/actuator`。该实现也是一个端点,可以通过属性配置它的路径(`endpoints.actuator.path`)及是否开启(`endpoints.actuator.enabled`)。 + +当指定了一个自定义管理上下文路径时,“导航页”路径自动从`/actuator`迁移到管理上下文根目录。例如,如果管理上下文路径为`/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/46.3 CORS support.md b/V. Spring Boot Actuator/46.3 CORS support.md new file mode 100644 index 00000000..dfd19fba --- /dev/null +++ b/V. Spring Boot Actuator/46.3 CORS support.md @@ -0,0 +1,10 @@ +###46.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/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointCorsProperties.java)获取完整的配置选项列表。 diff --git a/V. Spring Boot Actuator/46.4 Adding custom endpoints.md b/V. Spring Boot Actuator/46.4 Adding custom endpoints.md new file mode 100644 index 00000000..24e99229 --- /dev/null +++ b/V. Spring Boot Actuator/46.4 Adding custom endpoints.md @@ -0,0 +1,4 @@ +###46.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/46.5 Health information.md b/V. Spring Boot Actuator/46.5 Health information.md new file mode 100644 index 00000000..6e9939ba --- /dev/null +++ b/V. Spring Boot Actuator/46.5 Health information.md @@ -0,0 +1,4 @@ +### 46.5 健康信息 +健康信息可以检查应用的运行状态,它经常被监控软件用来提醒人们生产环境是否存在问题。`health`端点暴露的默认信息取决于端点是如何被访问的。对于一个非安全,未认证的连接只返回一个简单的'status'信息。对于一个安全或认证过的连接其他详细信息也会展示(具体参考[章节47.7, “HTTP健康端点访问限制” ](47.7. HTTP Health endpoint 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/46.6 Security with HealthIndicators.md b/V. Spring Boot Actuator/46.6 Security with HealthIndicators.md new file mode 100644 index 00000000..99c02db4 --- /dev/null +++ b/V. Spring Boot Actuator/46.6 Security with HealthIndicators.md @@ -0,0 +1,4 @@ +### 46.6 安全与HealthIndicators +`HealthIndicators`返回的信息通常有点敏感,例如,你可能不想将数据库服务器的详情发布到外面。因此,在使用一个未认证的HTTP连接时,默认只会暴露健康状态(health status)。如果想将所有的健康信息暴露出去,你可以把`endpoints.health.sensitive`设置为`false`。 + +为防止'拒绝服务'攻击,Health响应会被缓存,你可以使用`endpoints.health.time-to-live`属性改变默认的缓存时间(1000毫秒)。 diff --git a/V. Spring Boot Actuator/46.6.1 Auto-configured-HealthIndicators.md b/V. Spring Boot Actuator/46.6.1 Auto-configured-HealthIndicators.md new file mode 100644 index 00000000..ac9593a6 --- /dev/null +++ b/V. Spring Boot Actuator/46.6.1 Auto-configured-HealthIndicators.md @@ -0,0 +1,18 @@ +### 46.6.1 自动配置的HealthIndicators + +Spring Boot在合适的时候会自动配置以下`HealthIndicators`: + +|名称|描述| +|----|:-----| +|[`CassandraHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CassandraHealthIndicator.java)|检查Cassandra数据库状况| +|[`DiskSpaceHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java)|低磁盘空间检查| +|[`DataSourceHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java)|检查是否能从`DataSource`获取连接| +|[`ElasticsearchHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicator.java)|检查Elasticsearch集群状况| +|[`JmsHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java)|检查JMS消息代理状况| +|[`MailHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MailHealthIndicator.java)|检查邮件服务器状况| +|[`MongoHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MongoHealthIndicator.java)|检查Mongo数据库状况| +|[`RabbitHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MongoHealthIndicator.java)|检查Rabbit服务器状况| +|[`RedisHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java)|检查Redis服务器状况| +|[`SolrHealthIndicator`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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/46.6.2 Writing custom HealthIndicators.md b/V. Spring Boot Actuator/46.6.2 Writing custom HealthIndicators.md new file mode 100644 index 00000000..56aac115 --- /dev/null +++ b/V. Spring Boot Actuator/46.6.2 Writing custom HealthIndicators.md @@ -0,0 +1,29 @@ +### 46.6.2 编写自定义HealthIndicators +你可以注册实现[HealthIndicator](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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属性文件中: +```java +management.health.status.order=DOWN, OUT_OF_SERVICE, UNKNOWN, UP +``` +如果使用HTTP访问health端点,你可能想要注册自定义的status,并使用`HealthMvcEndpoint`进行映射。例如,你可以将`FATAL`映射为`HttpStatus.SERVICE_UNAVAILABLE`。 diff --git a/V. Spring Boot Actuator/46.7 Application information.md b/V. Spring Boot Actuator/46.7 Application information.md new file mode 100644 index 00000000..15c87507 --- /dev/null +++ b/V. Spring Boot Actuator/46.7 Application information.md @@ -0,0 +1,2 @@ +###46.7 应用信息 +应用信息会暴露所有[`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoContributor.java) beans收集的各种信息,Spring Boot包含很多自动配置的`InfoContributors`,你也可以编写自己的实现。 diff --git a/V. Spring Boot Actuator/46.7.1 Auto-configured InfoContributors.md b/V. Spring Boot Actuator/46.7.1 Auto-configured InfoContributors.md new file mode 100644 index 00000000..0557b9be --- /dev/null +++ b/V. Spring Boot Actuator/46.7.1 Auto-configured InfoContributors.md @@ -0,0 +1,10 @@ +###46.7.1 自动配置的InfoContributors +Spring Boot会在合适的时候自动配置以下`InfoContributors`: + +|名称|描述| +|:----|:----| +|[`EnvironmentInfoContributor`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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/v1.4.1.RELEASE/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/v1.4.1.RELEASE/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/46.7.2 Custom application info information.md b/V. Spring Boot Actuator/46.7.2 Custom application info information.md new file mode 100644 index 00000000..11d9a81d --- /dev/null +++ b/V. Spring Boot Actuator/46.7.2 Custom application info information.md @@ -0,0 +1,14 @@ +### 46.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属性](http://docs.spring.io/spring-boot/docs/1.4.1.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/46.7.3 Git commit information.md b/V. Spring Boot Actuator/46.7.3 Git commit information.md new file mode 100644 index 00000000..ed6d7f69 --- /dev/null +++ b/V. Spring Boot Actuator/46.7.3 Git commit information.md @@ -0,0 +1,9 @@ +### 46.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](http://docs.spring.io/spring-boot/docs/1.4.1.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/46.7.4 Build information.md b/V. Spring Boot Actuator/46.7.4 Build information.md new file mode 100644 index 00000000..6fee6c2a --- /dev/null +++ b/V. Spring Boot Actuator/46.7.4 Build information.md @@ -0,0 +1,4 @@ +###46.7.4 构建信息 +如果`BuildProperties` bean存在,`info`端点也会发布你的构建信息。 + +**注** 如果classpath下存在`META-INF/build-info.properties`文件,Spring Boot将自动构建`BuildProperties` bean。Maven和Gradle都能产生该文件,具体查看[Generate build information](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto-build-info)。 diff --git a/V. Spring Boot Actuator/46.7.5 Writing custom InfoContributors.md b/V. Spring Boot Actuator/46.7.5 Writing custom InfoContributors.md new file mode 100644 index 00000000..61bc66db --- /dev/null +++ b/V. Spring Boot Actuator/46.7.5 Writing custom InfoContributors.md @@ -0,0 +1,28 @@ +###46.7.5 编写自定义的InfoContributors +你可以注册实现了[`InfoContributor`](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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/41. Monitoring and management over HTTP.md b/V. Spring Boot Actuator/47. Monitoring and management over HTTP.md similarity index 51% rename from V. Spring Boot Actuator/41. Monitoring and management over HTTP.md rename to V. Spring Boot Actuator/47. Monitoring and management over HTTP.md index 699a0dd8..a01555f6 100644 --- a/V. Spring Boot Actuator/41. Monitoring and management over HTTP.md +++ b/V. Spring Boot Actuator/47. Monitoring and management over HTTP.md @@ -1,3 +1,3 @@ -### 41. 基于HTTP的监控和管理 +### 47. 基于HTTP的监控和管理 -如果你正在开发一个Spring MVC应用,Spring Boot执行器自动将所有启用的端点通过HTTP暴露出去。默认约定使用端点的id作为URL路径,例如,health暴露为/health。 +如果你正在开发一个Spring MVC应用,Spring Boot执行器自动将所有启用的端点通过HTTP暴露出去。默认约定使用端点的`id`作为URL路径,例如,`health`暴露为`/health`。 diff --git a/V. Spring Boot Actuator/47. Process monitoring.md b/V. Spring Boot Actuator/47. Process monitoring.md deleted file mode 100644 index 88eea99f..00000000 --- a/V. Spring Boot Actuator/47. Process monitoring.md +++ /dev/null @@ -1,7 +0,0 @@ -### 47. 进程监控 - -在Spring Boot执行器中,你可以找到几个创建有利于进程监控的文件的类: -- `ApplicationPidFileWriter`创建一个包含应用PID的文件(默认位于应用目录,文件名为application.pid) -- `EmbeddedServerPortFileWriter`创建一个或多个包含内嵌服务器端口的文件(默认位于应用目录,文件名为application.port) - -默认情况下,这些writers没有被激活,但你可以使用下面描述的任何方式来启用它们。 diff --git a/V. Spring Boot Actuator/47.1 Securing sensitive endpoints.md b/V. Spring Boot Actuator/47.1 Securing sensitive endpoints.md new file mode 100644 index 00000000..1572cab0 --- /dev/null +++ b/V. Spring Boot Actuator/47.1 Securing sensitive endpoints.md @@ -0,0 +1,13 @@ +### 47.1 保护敏感端点 +如果你的项目添加了‘Spring Security’依赖,所有通过HTTP暴露的敏感端点都会受到保护,默认情况下会使用用户名为`user`的基本认证(basic authentication),产生的密码会在应用启动时打印到控制台上。 + +**注** 在应用启动时会记录生成的密码,具体搜索`Using default security password`。 + +你可以使用Spring属性改变用户名,密码和访问端点需要的安全角色。例如,你可以将以下配置添加到`application.properties`中: +```java +security.user.name=admin +security.user.password=secret +management.security.role=SUPERUSER +``` + +**注** 如果不使用Spring Security,并且公开暴露HTTP端点,你应该慎重考虑启用哪些端点,具体参考[Section 46.1, “Customizing endpoints”](40.1. Customizing endpoints.md)。 diff --git a/V. Spring Boot Actuator/47.2 Customizing the management endpoint paths.md b/V. Spring Boot Actuator/47.2 Customizing the management endpoint paths.md new file mode 100644 index 00000000..4eb78e0b --- /dev/null +++ b/V. Spring Boot Actuator/47.2 Customizing the management endpoint paths.md @@ -0,0 +1,10 @@ +### 47.2 自定义管理端点路径 +有时将所有管理端点划分到单个路径下是有用的。例如,`/info`可能已被应用占用,你可以用`management.contextPath`属性为管理端点设置一个前缀: +```java +management.context-path=/manage +``` +以上的`application.properties`示例将把端点从`/{id}`改为`/manage/{id}`(比如`/manage/info`)。 + +你也可以改变端点的`id`(使用`endpoints.{name}.id`)来改变MVC端点的默认资源路径,合法的端点ids只能由字母数字组成(因为它们可以暴露到很多地方,包括不允许特殊字符的JMX对象name)。MVC路径也可以通过配置`endpoints.{name}.path`来单独改变,Spring Boot不会校验这些值(所以你可以使用URL中任何合法的字符)。例如,想要改变`/health`端点路径为`/ping/me`,你可以设置`endpoints.health.path=/ping/me`。 + +**注** 如果你提供一个自定义`MvcEndpoint`,记得包含一个可设置的`path`属性,并像标准MVC端点那样将该属性默认设置为`/{id}`(具体可参考`HealthMvcEndpoint`)。如果你的自定义端点是一个`Endpoint`(不是`MvcEndpoint`),Spring Boot将会为你分配路径。 diff --git a/V. Spring Boot Actuator/47.2. Programmatically.md b/V. Spring Boot Actuator/47.2. Programmatically.md deleted file mode 100644 index 09f1b23a..00000000 --- a/V. Spring Boot Actuator/47.2. Programmatically.md +++ /dev/null @@ -1,4 +0,0 @@ - -### 47.2. 以编程方式 - -你也可以通过调用`SpringApplication.addListeners(…)`方法来激活一个监听器,并传递相应的`Writer`对象。该方法允许你通过`Writer`构造器自定义文件名和路径。 diff --git a/V. Spring Boot Actuator/47.3 Customizing the management server port.md b/V. Spring Boot Actuator/47.3 Customizing the management server port.md new file mode 100644 index 00000000..d9aa5aa5 --- /dev/null +++ b/V. Spring Boot Actuator/47.3 Customizing the management server port.md @@ -0,0 +1,10 @@ +### 47.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/47.4 Configuring management-specific SSL.md b/V. Spring Boot Actuator/47.4 Configuring management-specific SSL.md new file mode 100644 index 00000000..78088bd4 --- /dev/null +++ b/V. Spring Boot Actuator/47.4 Configuring management-specific SSL.md @@ -0,0 +1,21 @@ +###47.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.enable=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.enable=true +management.ssl.key-store=classpath:management.jks +management.ssl.key-password=secret +``` diff --git a/V. Spring Boot Actuator/47.5 Customizing the management server address.md b/V. Spring Boot Actuator/47.5 Customizing the management server address.md new file mode 100644 index 00000000..d99a1368 --- /dev/null +++ b/V. Spring Boot Actuator/47.5 Customizing the management server address.md @@ -0,0 +1,10 @@ +### 47.5 自定义管理服务器地址 +你可以通过设置`management.address`属性来定义管理端点使用的地址,这在你只想监听内部或面向生产环境的网络,或只监听来自`localhost`的连接时非常有用。 + +**注** 如果端口跟主应用服务器不一样,你只能监听一个不同的地址。 + +下面的application.properties示例不允许远程访问管理服务器: +```java +management.port=8081 +management.address=127.0.0.1 +``` diff --git a/V. Spring Boot Actuator/41.5. Disabling HTTP endpoints.md b/V. Spring Boot Actuator/47.6 Disabling HTTP endpoints.md similarity index 75% rename from V. Spring Boot Actuator/41.5. Disabling HTTP endpoints.md rename to V. Spring Boot Actuator/47.6 Disabling HTTP endpoints.md index cad6919d..5a5094d5 100644 --- a/V. Spring Boot Actuator/41.5. Disabling HTTP endpoints.md +++ b/V. Spring Boot Actuator/47.6 Disabling HTTP endpoints.md @@ -1,4 +1,4 @@ -### 41.5. 禁用HTTP端点 +### 47.6 禁用HTTP端点 如果不想通过HTTP暴露端点,你可以将管理端口设置为-1: `management.port=-1` diff --git a/V. Spring Boot Actuator/47.7 HTTP Health endpoint access restrictions.md b/V. Spring Boot Actuator/47.7 HTTP Health endpoint access restrictions.md new file mode 100644 index 00000000..89a1fffa --- /dev/null +++ b/V. Spring Boot Actuator/47.7 HTTP Health endpoint access restrictions.md @@ -0,0 +1,12 @@ +### 47.7 HTTP health端点访问限制 +`health`端点暴露的信息依赖于是否为匿名访问,应用是否受保护。默认情况下,当匿名访问一个受保护的应用时,任何有关服务器的健康详情都被隐藏了,该端点只简单的展示服务器运行状况(up或down)。此外,响应会被缓存一个可配置的时间段以防止端点被用于'拒绝服务'攻击,你可以通过`endpoints.health.time-to-live`属性设置缓存时间(单位为毫秒),默认为1000毫秒,也就是1秒。 + +你可以增强上述限制,从而只允许认证用户完全访问一个受保护应用的`health`端点,将`endpoints.health.sensitive`设为`true`可以实现该效果,具体可查看以下总结(`sensitive`标识值为"false"的默认加粗): + +|`management.security.enabled`|`endpoints.health.sensitive`|未认证|认证| +|:----|:----|:----|:-----| +|false|**false**|全部内容|全部内容| +|false|true|只能查看Status|全部内容| +|true|**false**|只能查看Status|全部内容| +|true|true|不能查看任何内容|全部内容| + diff --git a/V. Spring Boot Actuator/42. Monitoring and management over JMX.md b/V. Spring Boot Actuator/48. Monitoring and management over JMX.md similarity index 82% rename from V. Spring Boot Actuator/42. Monitoring and management over JMX.md rename to V. Spring Boot Actuator/48. Monitoring and management over JMX.md index 792022c2..d347be5d 100644 --- a/V. Spring Boot Actuator/42. Monitoring and management over JMX.md +++ b/V. Spring Boot Actuator/48. Monitoring and management over JMX.md @@ -1,3 +1,3 @@ -### 42. 基于JMX的监控和管理 +### 48. 基于JMX的监控和管理 Java管理扩展(JMX)提供了一种标准的监控和管理应用的机制。默认情况下,Spring Boot在`org.springframework.boot`域下将管理端点暴露为JMX MBeans。 diff --git a/V. Spring Boot Actuator/48. What to read next.md b/V. Spring Boot Actuator/48. What to read next.md deleted file mode 100644 index 2bffc6bc..00000000 --- a/V. Spring Boot Actuator/48. What to read next.md +++ /dev/null @@ -1 +0,0 @@ -### 48. 接下来阅读什么 diff --git a/V. Spring Boot Actuator/48.1 Customizing MBean names.md b/V. Spring Boot Actuator/48.1 Customizing MBean names.md new file mode 100644 index 00000000..41ac5d84 --- /dev/null +++ b/V. Spring Boot Actuator/48.1 Customizing MBean names.md @@ -0,0 +1,9 @@ +### 48.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/48.2 Disabling JMX endpoints.md b/V. Spring Boot Actuator/48.2 Disabling JMX endpoints.md new file mode 100644 index 00000000..d23fba0a --- /dev/null +++ b/V. Spring Boot Actuator/48.2 Disabling JMX endpoints.md @@ -0,0 +1,5 @@ +### 48.2 禁用JMX端点 +如果不想通过JMX暴露端点,你可以将`endpoints.jmx.enabled`属性设置为`false`: +```java +endpoints.jmx.enabled=false +``` diff --git a/V. Spring Boot Actuator/42.3. Using Jolokia for JMX over HTTP.md b/V. Spring Boot Actuator/48.3 Using Jolokia for JMX over HTTP.md similarity index 53% rename from V. Spring Boot Actuator/42.3. Using Jolokia for JMX over HTTP.md rename to V. Spring Boot Actuator/48.3 Using Jolokia for JMX over HTTP.md index 1fd22872..670c0fba 100644 --- a/V. Spring Boot Actuator/42.3. Using Jolokia for JMX over HTTP.md +++ b/V. Spring Boot Actuator/48.3 Using Jolokia for JMX over HTTP.md @@ -1,10 +1,9 @@ -### 42.3. 使用Jolokia通过HTTP实现JMX远程管理 - -Jolokia是一个JMX-HTTP桥,它提供了一种访问JMX beans的替代方法。想要使用Jolokia,只需添加`org.jolokia:jolokia-core`的依赖。例如,使用Maven需要添加下面的配置: +### 48.3 使用Jolokia通过HTTP实现JMX远程管理 +Jolokia是一个JMX-HTTP桥,它提供了一种访问JMX beans的替代方法。想要使用Jolokia,只需添加`org.jolokia:jolokia-core`的依赖。例如,使用Maven需要添加以下配置: ```xml org.jolokia jolokia-core ``` -在你的管理HTTP服务器上可以通过`/jolokia`访问Jolokia。 +然后在你的管理HTTP服务器上可以通过`/jolokia`访问Jolokia。 diff --git a/V. Spring Boot Actuator/48.3.1 Customizing Jolokia.md b/V. Spring Boot Actuator/48.3.1 Customizing Jolokia.md new file mode 100644 index 00000000..51ee08e6 --- /dev/null +++ b/V. Spring Boot Actuator/48.3.1 Customizing Jolokia.md @@ -0,0 +1,5 @@ +### 48.3.1 自定义Jolokia +Jolokia有很多配置,通常使用servlet参数进行设置,跟Spring Boot一块使用时可以在`application.properties`中添加`jolokia.config.`前缀的属性进行配置: +```java +jolokia.config.debug=true +``` diff --git a/V. Spring Boot Actuator/48.3.2 Disabling Jolokia.md b/V. Spring Boot Actuator/48.3.2 Disabling Jolokia.md new file mode 100644 index 00000000..3e5160f6 --- /dev/null +++ b/V. Spring Boot Actuator/48.3.2 Disabling Jolokia.md @@ -0,0 +1,5 @@ +### 48.3.2 禁用Jolokia +如果正在使用Jolokia,又不想让Spring Boot配置它,你只需要简单的将`endpoints.jolokia.enabled`属性设置为`false`: +```java +endpoints.jolokia.enabled=false +``` diff --git a/V. Spring Boot Actuator/49. Monitoring and management using a remote shell.md b/V. Spring Boot Actuator/49. Monitoring and management using a remote shell.md new file mode 100644 index 00000000..16ce2968 --- /dev/null +++ b/V. Spring Boot Actuator/49. Monitoring and management using a remote shell.md @@ -0,0 +1,11 @@ +### 49. 使用远程shell进行监控和管理 +Spring Boot支持集成一个称为'CRaSH'的Java shell,你可以在CRaSH中使用ssh或telnet命令连接到运行的应用,项目中添加以下依赖可以启用远程shell支持: +```xml + + org.springframework.boot + spring-boot-starter-remote-shell + +``` +**注** 如果想使用telnet访问,你还需添加对`org.crsh:crsh.shell.telnet`的依赖。 + +**注** CRaSH运行时需要JDK,因为它要动态编译命令。如果一个基本的`help`命令都运行失败,你很可能使用的是JRE。 diff --git a/V. Spring Boot Actuator/49.1 Connecting to the remote shell.md b/V. Spring Boot Actuator/49.1 Connecting to the remote shell.md new file mode 100644 index 00000000..74d10c40 --- /dev/null +++ b/V. Spring Boot Actuator/49.1 Connecting to the remote shell.md @@ -0,0 +1,19 @@ +### 49.1 连接远程shell +远程shell默认监听端口为`2000`,默认用户名为`user`,密码为随机生成的,并且在输出日志中会显示。如果应用使用Spring Security,该shell默认使用[相同的配置](../IV. Spring Boot features/28. Security.md)。如果不是,将使用一个简单的认证策略,你可能会看到类似这样的信息: +```java +Using default password for shell access: ec03e16c-4cf4-49ee-b745-7c8255c1dd7e +``` +Linux和OSX用户可以使用`ssh`连接远程shell,Windows用户可以下载并安装[PuTTY](http://www.putty.org/)。 +```shell +$ ssh -p 2000 user@localhost + +user@localhost's password: + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v1.4.1.RELEASE) on myhost +``` +输入`help`可以获取命令列表,Spring Boot提供`metrics`,`beans`,`autoconfig`和`endpoint`命令。 diff --git a/V. Spring Boot Actuator/49.1.1 Remote shell credentials.md b/V. Spring Boot Actuator/49.1.1 Remote shell credentials.md new file mode 100644 index 00000000..8a01f010 --- /dev/null +++ b/V. Spring Boot Actuator/49.1.1 Remote shell credentials.md @@ -0,0 +1,2 @@ +### 49.1.1 远程shell证书 +你可以使用`management.shell.auth.simple.user.name`和`management.shell.auth.simple.user.password`属性配置自定义的连接证书,也可以使用Spring Security的`AuthenticationManager`处理登录职责,具体参考[CrshAutoConfiguration](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/api/org/springframework/boot/actuate/autoconfigure/CrshAutoConfiguration.html)和[ShellProperties](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/api/org/springframework/boot/actuate/autoconfigure/ShellProperties.html)的Javadoc。 diff --git a/V. Spring Boot Actuator/43.2. Extending the remote shell.md b/V. Spring Boot Actuator/49.2 Extending the remote shell.md similarity index 65% rename from V. Spring Boot Actuator/43.2. Extending the remote shell.md rename to V. Spring Boot Actuator/49.2 Extending the remote shell.md index 081b7bfc..cc6ba38b 100644 --- a/V. Spring Boot Actuator/43.2. Extending the remote shell.md +++ b/V. Spring Boot Actuator/49.2 Extending the remote shell.md @@ -1,3 +1,3 @@ -### 43.2. 扩展远程shell +### 49.2 扩展远程shell 有很多有趣的方式可以用来扩展远程shell。 diff --git a/V. Spring Boot Actuator/49.2.1 Remote shell commands.md b/V. Spring Boot Actuator/49.2.1 Remote shell commands.md new file mode 100644 index 00000000..29f1af91 --- /dev/null +++ b/V. Spring Boot Actuator/49.2.1 Remote shell commands.md @@ -0,0 +1,34 @@ +### 49.2.1 远程shell命令 +你可以使用Groovy或Java编写其他的shell命令(具体参考CRaSH文档),Spring Boot默认会搜索以下路径的命令: + +* `classpath*:/commands/**` +* `classpath*:/crash/commands/**` + +**注** 设置`shell.command-path-patterns`属性可以改变搜索路径。 +**注** 如果使用可执行存档(archive),shell依赖的所有类都必须打包进一个内嵌的jar,而不是直接打包进可执行jar或war。 + +下面是一个从`src/main/resources/commands/hello.groovy`加载的'hello'命令: +```java +package commands + +import org.crsh.cli.Usage +import org.crsh.cli.Command + +class hello { + + @Usage("Say Hello") + @Command + def main(InvocationContext context) { + return "Hello" + } + +} +``` +Spring Boot为`InvocationContext`添加一些其他属性,你可以在命令中访问它们: + +|属性名称|描述| +|------|:------| +|`spring.boot.version`|Spring Boot的版本| +|`spring.version`|Spring核心框架的版本| +|`spring.beanfactory`|获取Spring的`BeanFactory`| +|`spring.environment`|获取Spring的`Environment`| diff --git a/V. Spring Boot Actuator/49.2.2 Remote shell plugins.md b/V. Spring Boot Actuator/49.2.2 Remote shell plugins.md new file mode 100644 index 00000000..2fcac96a --- /dev/null +++ b/V. Spring Boot Actuator/49.2.2 Remote shell plugins.md @@ -0,0 +1,2 @@ +### 49.2.2 远程shell插件 +除了创建新命令,你也可以扩展CRaSH shell的其他特性,所有继承`org.crsh.plugin.CRaSHPlugin`的Spring Beans将自动注册到shell,具体查看[CRaSH参考文档](http://www.crashub.org/)。 diff --git a/V. Spring Boot Actuator/50. Metrics.md b/V. Spring Boot Actuator/50. Metrics.md new file mode 100644 index 00000000..41a935d1 --- /dev/null +++ b/V. Spring Boot Actuator/50. Metrics.md @@ -0,0 +1,38 @@ + +### 50. 度量指标(Metrics) +Spring Boot执行器包含一个支持'gauge'和'counter'级别的度量指标服务,'gauge'记录一个单一值,'counter'记录一个增量(增加或减少)。同时,Spring Boot提供一个[PublicMetrics](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/PublicMetrics.java)接口,你可以实现它,从而暴露以上两种机制不能记录的指标,具体参考[SystemPublicMetrics](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/PublicMetrics.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/50.1 System metrics.md b/V. Spring Boot Actuator/50.1 System metrics.md new file mode 100644 index 00000000..f4aa74a8 --- /dev/null +++ b/V. Spring Boot Actuator/50.1 System metrics.md @@ -0,0 +1,12 @@ +### 50.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/50.10 Dropwizard Metrics.md b/V. Spring Boot Actuator/50.10 Dropwizard Metrics.md new file mode 100644 index 00000000..ed75e36f --- /dev/null +++ b/V. Spring Boot Actuator/50.10 Dropwizard Metrics.md @@ -0,0 +1,4 @@ +### 50.10 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/50.11 Message channel integration.md b/V. Spring Boot Actuator/50.11 Message channel integration.md new file mode 100644 index 00000000..0a31d76e --- /dev/null +++ b/V. Spring Boot Actuator/50.11 Message channel integration.md @@ -0,0 +1,2 @@ +### 50.11 消息渠道集成 +如果存在名为`metricsChannel`的`MessageChannel` bean,Spring Boot将创建一个`MetricWriter`将指标写入该渠道(channel)。writer自动挂钩一个exporter,所以全部指标值都会出现在渠道上, 订阅者就可以进行其他分析或动作(提供渠道和订阅者取决于你)。 diff --git a/V. Spring Boot Actuator/50.2 DataSource metrics.md b/V. Spring Boot Actuator/50.2 DataSource metrics.md new file mode 100644 index 00000000..89f958da --- /dev/null +++ b/V. Spring Boot Actuator/50.2 DataSource metrics.md @@ -0,0 +1,11 @@ +### 50.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/50.3 Cache metrics.md b/V. Spring Boot Actuator/50.3 Cache metrics.md new file mode 100644 index 00000000..d958fb33 --- /dev/null +++ b/V. Spring Boot Actuator/50.3 Cache metrics.md @@ -0,0 +1,12 @@ +###50.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和Guava提供统计。如果喜欢的缓存库没被支持,你可以添加其他`CacheStatisticsProvider` beans,具体可参考`CacheStatisticsAutoConfiguration`。 diff --git a/V. Spring Boot Actuator/50.4 Tomcat session metrics.md b/V. Spring Boot Actuator/50.4 Tomcat session metrics.md new file mode 100644 index 00000000..53a870f9 --- /dev/null +++ b/V. Spring Boot Actuator/50.4 Tomcat session metrics.md @@ -0,0 +1,3 @@ +### 50.4 Tomcat session指标 +如果你使用Tomcat作为内嵌的servlet容器,Spring Boot将自动暴露session指标, +`httpsessions.active`和`httpsessions.max`分别提供活动的和最大的session数量。 diff --git a/V. Spring Boot Actuator/50.5 Recording your own metrics.md b/V. Spring Boot Actuator/50.5 Recording your own metrics.md new file mode 100644 index 00000000..e8c2a563 --- /dev/null +++ b/V. Spring Boot Actuator/50.5 Recording your own metrics.md @@ -0,0 +1,27 @@ + +### 50.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/50.6 Adding your own public metrics.md b/V. Spring Boot Actuator/50.6 Adding your own public metrics.md new file mode 100644 index 00000000..7f2ab4e4 --- /dev/null +++ b/V. Spring Boot Actuator/50.6 Adding your own public metrics.md @@ -0,0 +1,2 @@ +### 50.6 添加自己的公共指标 +只要注册其他的`PublicMetrics`实现beans,你就可以添加其他的度量指标,比如计算metrics端点每次调用的次数。默认情况下,端点会聚合所有这样的beans,通过定义自己的`MetricsEndpoint`可以轻易改变这种情况。 diff --git a/V. Spring Boot Actuator/50.7 Special features with Java 8.md b/V. Spring Boot Actuator/50.7 Special features with Java 8.md new file mode 100644 index 00000000..c80faa8c --- /dev/null +++ b/V. Spring Boot Actuator/50.7 Special features with Java 8.md @@ -0,0 +1,4 @@ +### 50.7 使用Java8的特性 +Spring Boot提供的`GaugeService`和`CounterService`默认实现依赖于你使用的Java版本。如果使用Java8(或更高版本),Spring Boot将实现切换为一个高性能版本,该版本优化了写速度,底层使用原子内存buffers,而不是通过不可变但相对昂贵的`Metric`类型(跟基于仓库的实现相比,counters大概快5倍,gauges大概快2倍)。对于Java7,Dropwizard指标服务也是很有效的(使用了某些Java8并发库),但它不记录指标值的时间戳。如果需要关注指标采集的性能,建议你使用高性能的选项,并不要频繁读取指标信息,这样写入会本地缓存,只有在需要时读取。 + +**注** 如果使用Java8或Dropwizard,Spring Boot默认不会使用老的`MetricRepository`和它的`InMemoryMetricRepository`实现。 diff --git a/V. Spring Boot Actuator/50.8 Metric writers, exporters and aggregation.md b/V. Spring Boot Actuator/50.8 Metric writers, exporters and aggregation.md new file mode 100644 index 00000000..64a19663 --- /dev/null +++ b/V. Spring Boot Actuator/50.8 Metric writers, exporters and aggregation.md @@ -0,0 +1,8 @@ +###50.8 指标写入,导出和聚合 +Spring Boot提供几个标记接口`Exporter`的实现,可用于将从内存buffers读取的指标复制到一个分析和展示它们的地方。实际上,如果提供一个实现`MetricWriter`接口(或`GaugeWriter`用于简单场景)且注解`@ExportMetricWriter`的`@Bean`,它将自动挂钩一个`Exporter`并每5秒反馈下指标更新(通过`spring.metrics.export.delay-millis`配置)。此外,你定义的所有注解`@ExportMetricReader`的`MetricReader`,它们的值将被默认exporter导出。 + +默认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/50.8.1 Export to Redis.md b/V. Spring Boot Actuator/50.8.1 Export to Redis.md new file mode 100644 index 00000000..797d0c8b --- /dev/null +++ b/V. Spring Boot Actuator/50.8.1 Export to Redis.md @@ -0,0 +1,22 @@ +###50.8.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/50.8.2 Export to Open TSDB.md b/V. Spring Boot Actuator/50.8.2 Export to Open TSDB.md new file mode 100644 index 00000000..a9df8adf --- /dev/null +++ b/V. Spring Boot Actuator/50.8.2 Export to Open TSDB.md @@ -0,0 +1,21 @@ +###50.8.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/50.8.3 Export to Statsd.md b/V. Spring Boot Actuator/50.8.3 Export to Statsd.md new file mode 100644 index 00000000..3d8862df --- /dev/null +++ b/V. Spring Boot Actuator/50.8.3 Export to Statsd.md @@ -0,0 +1,13 @@ +###50.8.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/50.8.4 Export to JMX.md b/V. Spring Boot Actuator/50.8.4 Export to JMX.md new file mode 100644 index 00000000..67374a16 --- /dev/null +++ b/V. Spring Boot Actuator/50.8.4 Export to JMX.md @@ -0,0 +1,12 @@ +###50.8.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/50.9 Aggregating metrics from multiple sources.md b/V. Spring Boot Actuator/50.9 Aggregating metrics from multiple sources.md new file mode 100644 index 00000000..302e6148 --- /dev/null +++ b/V. Spring Boot Actuator/50.9 Aggregating metrics from multiple sources.md @@ -0,0 +1,29 @@ +###50.9 聚合多个来源的指标 +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/51. Auditing.md b/V. Spring Boot Actuator/51. Auditing.md new file mode 100644 index 00000000..39902d11 --- /dev/null +++ b/V. Spring Boot Actuator/51. Auditing.md @@ -0,0 +1,2 @@ +### 51. 审计 +Spring Boot执行器有一个灵活的审计框架,一旦Spring Security处于活动状态(默认抛出'authentication success','failure'和'access denied'异常),它就会发布事件。这对于报告非常有用,同时可以基于认证失败实现一个锁定策略。为了自定义发布的安全事件,你可以提供自己的`AbstractAuthenticationAuditListener`,`AbstractAuthorizationAuditListener`实现。你也可以使用审计服务处理自己的业务事件。为此,你可以将存在的`AuditEventRepository`注入到自己的组件,并直接使用它,或者只是简单地通过Spring `ApplicationEventPublisher`发布`AuditApplicationEvent`(使用`ApplicationEventPublisherAware`)。 diff --git a/V. Spring Boot Actuator/46. Tracing.md b/V. Spring Boot Actuator/52. Tracing.md similarity index 83% rename from V. Spring Boot Actuator/46. Tracing.md rename to V. Spring Boot Actuator/52. Tracing.md index 0b1bf2fa..b15203c7 100644 --- a/V. Spring Boot Actuator/46. Tracing.md +++ b/V. Spring Boot Actuator/52. Tracing.md @@ -1,6 +1,5 @@ -### 46. 追踪(Tracing) - -对于所有的HTTP请求Spring Boot自动启用追踪。你可以查看`trace`端点,并获取最近一些请求的基本信息: +### 52. 追踪(Tracing) +对于所有的HTTP请求Spring Boot自动启用追踪,你可以查看`trace`端点获取最近100条请求的基本信息: ```javascript [{ "timestamp": 1394343677415, diff --git a/V. Spring Boot Actuator/52.1 Custom tracing.md b/V. Spring Boot Actuator/52.1 Custom tracing.md new file mode 100644 index 00000000..71499970 --- /dev/null +++ b/V. Spring Boot Actuator/52.1 Custom tracing.md @@ -0,0 +1,4 @@ +### 52.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/53. Process monitoring.md b/V. Spring Boot Actuator/53. Process monitoring.md new file mode 100644 index 00000000..e10846d6 --- /dev/null +++ b/V. Spring Boot Actuator/53. Process monitoring.md @@ -0,0 +1,6 @@ +### 53. 进程监控 +在Spring Boot执行器中,你可以找到几个类,它们创建的文件利于进程监控: +- `ApplicationPidFileWriter`创建一个包含应用PID的文件(默认位于应用目录,文件名为`application.pid`)。 +- `EmbeddedServerPortFileWriter`创建一个或多个包含内嵌服务器端口的文件(默认位于应用目录,文件名为`application.port`)。 + +这些writers默认没被激活,但你可以使用以下描述的任何方式来启用它们。 diff --git a/V. Spring Boot Actuator/47.1. Extend configuration.md b/V. Spring Boot Actuator/53.1 Extend configuration.md similarity index 60% rename from V. Spring Boot Actuator/47.1. Extend configuration.md rename to V. Spring Boot Actuator/53.1 Extend configuration.md index c1268d12..1b8245a9 100644 --- a/V. Spring Boot Actuator/47.1. Extend configuration.md +++ b/V. Spring Boot Actuator/53.1 Extend configuration.md @@ -1,6 +1,5 @@ -### 47.1. 扩展属性 - -你需要激活`META-INF/spring.factories`文件里的listener(s): +### 53.1 扩展配置 +在`META-INF/spring.factories`文件中,你可以激活创建PID文件的`listener(s)`,示例: ```java org.springframework.context.ApplicationListener=\ org.springframework.boot.actuate.system.ApplicationPidFileWriter, diff --git a/V. Spring Boot Actuator/53.2 Programmatically.md b/V. Spring Boot Actuator/53.2 Programmatically.md new file mode 100644 index 00000000..83cfd9db --- /dev/null +++ b/V. Spring Boot Actuator/53.2 Programmatically.md @@ -0,0 +1,3 @@ + +### 53.2 以编程方式 +你也可以通过调用`SpringApplication.addListeners(…)`方法并传递相应的`Writer`对象来激活一个监听器,该方法允许你通过`Writer`构造器自定义文件名和路径。 diff --git a/V. Spring Boot Actuator/54. What to read next.md b/V. Spring Boot Actuator/54. What to read next.md new file mode 100644 index 00000000..500b68f2 --- /dev/null +++ b/V. Spring Boot Actuator/54. What to read next.md @@ -0,0 +1,4 @@ +### 54. 接下来阅读什么 +如果想探索本章节讨论的某些内容,你可以看下执行器的[示例应用](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-samples),你也可能想了解图形工具比如[Graphite](http://graphite.wikidot.com/)。 + +此外,你可以继续了解[‘deployment options’](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#deployment)或直接跳到Spring Boot的[build tool plugins](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#build-tool-plugins)。 diff --git a/V. Spring Boot Actuator/README.md b/V. Spring Boot Actuator/README.md index eccf00c1..3de08826 100644 --- a/V. Spring Boot Actuator/README.md +++ b/V. Spring Boot Actuator/README.md @@ -1,3 +1,5 @@ ### Spring Boot执行器:Production-ready特性 -Spring Boot包含很多其他的特性,它们可以帮你监控和管理发布到生产环境的应用。你可以选择使用HTTP端点,JMX或远程shell(SSH或Telnet)来管理和监控应用。审计(Auditing),健康(health)和数据采集(metrics gathering)会自动应用到你的应用。 +Spring Boot包含很多其他特性,可用来帮你监控和管理发布到生产环境的应用。你可以选择使用HTTP端点,JMX,甚至通过远程shell(SSH或Telnet)来管理和监控应用。审计(Auditing),健康(health)和数据采集(metrics gathering)会自动应用到你的应用。 + +Actuator HTTP端点只能用在基于Spring MVC的应用,特别地,它不能跟Jersey一块使用,除非你也[启用Spring MVC](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#howto-use-actuator-with-jersey)。 diff --git a/VI. Deploying to the cloud/README.md b/VI. Deploying Spring Boot applications/55. Deploying to the cloud.md similarity index 69% rename from VI. Deploying to the cloud/README.md rename to VI. Deploying Spring Boot applications/55. Deploying to the cloud.md index 866a66a4..fd3a08d6 100644 --- a/VI. Deploying to the cloud/README.md +++ b/VI. Deploying Spring Boot applications/55. Deploying to the cloud.md @@ -1,7 +1,8 @@ -### 部署到云端 - -对于大多数流行云PaaS(平台即服务)提供商,Spring Boot的可执行jars就是为它们准备的。这些提供商往往要求你带上自己的容器;它们管理应用的进程(不特别针对Java应用程序),所以它们需要一些中间层来将你的应用适配到云概念中的一个运行进程。 +###55. 部署到云端 +对于大多数流行云PaaS(平台即服务)提供商,Spring Boot的可执行jars就是为它们准备的。这些提供商往往要求你自己提供容器,它们只负责管理应用的进程(不特别针对Java应用程序),所以它们需要一些中间层来将你的应用适配到云概念中的一个运行进程。 两个流行的云提供商,Heroku和Cloud Foundry,采取一个打包('buildpack')方法。为了启动你的应用程序,不管需要什么,buildpack都会将它们打包到你的部署代码:它可能是一个JDK和一个java调用,也可能是一个内嵌的webserver,或者是一个成熟的应用服务器。buildpack是可插拔的,但你最好尽可能少的对它进行自定义设置。这可以减少不受你控制的功能范围,最小化部署和生产环境的发散。 理想情况下,你的应用就像一个Spring Boot可执行jar,所有运行需要的东西都打包到它内部。 + +本章节我们将看到在“Getting Started”章节开发的简单应用是怎么在云端运行的。 diff --git a/VI. Deploying to the cloud/49. Cloud Foundry.md b/VI. Deploying Spring Boot applications/55.1 Cloud Foundry.md similarity index 72% rename from VI. Deploying to the cloud/49. Cloud Foundry.md rename to VI. Deploying Spring Boot applications/55.1 Cloud Foundry.md index ffd30da4..3b817e22 100644 --- a/VI. Deploying to the cloud/49. Cloud Foundry.md +++ b/VI. Deploying Spring Boot applications/55.1 Cloud Foundry.md @@ -1,46 +1,45 @@ -### 49. Cloud Foundry - -如果不指定其他打包方式,Cloud Foundry会启用它提供的默认打包方式。Cloud Foundry的[Java buildpack](https://github.com/cloudfoundry/java-buildpack)对Spring应用有出色的支持,包括Spring Boot。你可以部署独立的可执行jar应用,也可以部署传统的.war形式的应用。 - -一旦你构建了应用(比如,使用`mvn clean package`)并[安装](http://docs.cloudfoundry.org/devguide/installcf/install-go-cli.html)了cf[命令行工具](http://docs.cloudfoundry.org/devguide/installcf/install-go-cli.html),你可以使用下面的`cf push`命令(将路径指向你编译后的.jar)来部署应用。在发布一个应用前,确保你已登陆cf命令行客户端。 -```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 -Preparing to start acloudyspringtime... OK ------> Downloaded app package (8.9M) ------> Java Buildpack source: system ------> Downloading Open JDK 1.7.0_51 from .../x86_64/openjdk-1.7.0_51.tar.gz (1.8s) - Expanding Open JDK to .java-buildpack/open_jdk (1.2s) ------> Downloading Spring Auto Reconfiguration from 0.8.7 .../auto-reconfiguration-0.8.7.jar (0.1s) ------> Uploading droplet (44M) -Checking status of app 'acloudyspringtime'... - 0 of 1 instances running (1 starting) - ... - 0 of 1 instances running (1 down) - ... - 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/)。 - +### 55.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 +Preparing to start acloudyspringtime... OK +-----> Downloaded app package (8.9M) +-----> Java Buildpack source: system +-----> Downloading Open JDK 1.7.0_51 from .../x86_64/openjdk-1.7.0_51.tar.gz (1.8s) + Expanding Open JDK to .java-buildpack/open_jdk (1.2s) +-----> Downloading Spring Auto Reconfiguration from 0.8.7 .../auto-reconfiguration-0.8.7.jar (0.1s) +-----> Uploading droplet (44M) +Checking status of app 'acloudyspringtime'... + 0 of 1 instances running (1 starting) + ... + 0 of 1 instances running (1 down) + ... + 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 to the cloud/49.1. Binding to services.md b/VI. Deploying Spring Boot applications/55.1.1 Binding to services.md similarity index 51% rename from VI. Deploying to the cloud/49.1. Binding to services.md rename to VI. Deploying Spring Boot applications/55.1.1 Binding to services.md index a32fc5e1..8da2d194 100644 --- a/VI. Deploying to the cloud/49.1. Binding to services.md +++ b/VI. Deploying Spring Boot applications/55.1.1 Binding to services.md @@ -1,23 +1,23 @@ -### 49.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)和服务信息(比如数据库证书)。具体参考VcapApplicationListener Javadoc。 - -**注**:[Spring Cloud Connectors](http://cloud.spring.io/spring-cloud-connectors/)项目很适合比如配置数据源的任务。Spring Boot提供自动配置支持和一个`spring-boot-starter-cloud-connectors` starter POM。 +### 55.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 to the cloud/50. Heroku.md b/VI. Deploying Spring Boot applications/55.2 Heroku.md similarity index 64% rename from VI. Deploying to the cloud/50. Heroku.md rename to VI. Deploying Spring Boot applications/55.2 Heroku.md index 55f88dab..bf033feb 100644 --- a/VI. Deploying to the cloud/50. Heroku.md +++ b/VI. Deploying Spring Boot applications/55.2 Heroku.md @@ -1,61 +1,60 @@ -### 50. Heroku - -Heroku是另外一个流行的Paas平台。想要自定义Heroku的构建过程,你可以提供一个`Procfile`,它提供部署一个应用所需的指令。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默认使用Java 1.6。只要你的Maven或Gradle构建时使用相同的版本就没问题(Maven用户可以设置`java.version`属性)。如果你想使用JDK 1.7,在你的pom.xml和Procfile临近处创建一个system.properties文件。在该文件中添加以下设置: -```java -java.runtime.version=1.7 -``` -这就是你需要做的一切。对于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.7... done ------> Installing Maven 3.2.3... 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。 +###55.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默认使用Java 1.8,只要你的Maven或Gradle构建时使用相同的版本就没问题(Maven用户可以设置`java.version`属性)。如果你想使用JDK 1.7,在你的`pom.xml`和`Procfile`临近处创建一个`system.properties`文件,在该文件中添加以下设置: +```java +java.runtime.version=1.7 +``` +这就是你需要做的所有内容,对于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 to the cloud/51. Openshift.md b/VI. Deploying Spring Boot applications/55.3 Openshift.md similarity index 82% rename from VI. Deploying to the cloud/51. Openshift.md rename to VI. Deploying Spring Boot applications/55.3 Openshift.md index bd76ada2..bc12ffa9 100644 --- a/VI. Deploying to the cloud/51. Openshift.md +++ b/VI. Deploying Spring Boot applications/55.3 Openshift.md @@ -1,41 +1,41 @@ -### 51. 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构建运行的应用可以参考它。由于一个[Gradle bug](http://issues.gradle.org/browse/GRADLE-2871),你不能使用高于1.6版本的Gradle。 +###55.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/55.4 Boxfuse and Amazon Web Services.md b/VI. Deploying Spring Boot applications/55.4 Boxfuse and Amazon Web Services.md new file mode 100644 index 00000000..2bc4b59f --- /dev/null +++ b/VI. Deploying Spring Boot applications/55.4 Boxfuse and Amazon Web Services.md @@ -0,0 +1,34 @@ +### 55.4 Boxfuse和Amazon Web Services +[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/55.5 Google App Engine.md b/VI. Deploying Spring Boot applications/55.5 Google App Engine.md new file mode 100644 index 00000000..59c1775f --- /dev/null +++ b/VI. Deploying Spring Boot applications/55.5 Google App Engine.md @@ -0,0 +1,2 @@ +###55.5 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/56. Installing Spring Boot applications.md b/VI. Deploying Spring Boot applications/56. Installing Spring Boot applications.md new file mode 100644 index 00000000..1024167c --- /dev/null +++ b/VI. Deploying Spring Boot applications/56. Installing Spring Boot applications.md @@ -0,0 +1,26 @@ +###56. 安装Spring Boot应用 +除了使用`java -jar`运行Spring Boot应用,制作在Unix系统完全可执行的应用也是可能的,这会简化常见生产环境Spring Boot应用的安装和管理。在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)。 + +**注** 完全可执行jars在文件前内嵌了一个额外脚本,目前不是所有工具都能接受这种形式,所以你有时可能不能使用该技术。 + +**注** 默认脚本支持大多数Linux分发版本,并在CentOS和Ubuntu上测试过。其他平台,比如OS X和FreeBSD,可能需要使用自定义`embeddedLaunchScript`。 + +**注** 当一个完全可执行jar运行时,它会将jar的目录作为工作目录。 diff --git a/VI. Deploying Spring Boot applications/56.1 Unix&Linux services.md b/VI. Deploying Spring Boot applications/56.1 Unix&Linux services.md new file mode 100644 index 00000000..602e6dd8 --- /dev/null +++ b/VI. Deploying Spring Boot applications/56.1 Unix&Linux services.md @@ -0,0 +1,2 @@ +### 56.1 Unix/Linux服务 +你可以使用`init.d`或`systemd`启动Spring Boot应用,就像其他Unix/Linux服务那样。 diff --git a/VI. Deploying Spring Boot applications/56.1.1 Installation as an init.d service (System V).md b/VI. Deploying Spring Boot applications/56.1.1 Installation as an init.d service (System V).md new file mode 100644 index 00000000..8e104884 --- /dev/null +++ b/VI. Deploying Spring Boot applications/56.1.1 Installation as an init.d service (System V).md @@ -0,0 +1,48 @@ +###56.1.1 安装为init.d服务(System V) +如果你配置Spring Boot的Maven或Gradle插件产生一个[完全可执行jar](http://docs.spring.io/spring-boot/docs/1.4.1.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文件](http://docs.spring.io/spring-boot/docs/1.4.1.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/56.1.2 Installation as a systemd service.md b/VI. Deploying Spring Boot applications/56.1.2 Installation as a systemd service.md new file mode 100644 index 00000000..17311bc9 --- /dev/null +++ b/VI. Deploying Spring Boot applications/56.1.2 Installation as a systemd service.md @@ -0,0 +1,26 @@ +###56.1.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`字段。 + +注意跟作为`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/56.1.3 Customizing the startup script.md b/VI. Deploying Spring Boot applications/56.1.3 Customizing the startup script.md new file mode 100644 index 00000000..8c7ff425 --- /dev/null +++ b/VI. Deploying Spring Boot applications/56.1.3 Customizing the startup script.md @@ -0,0 +1,56 @@ +###56.1.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}`| +|`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`服务有效| +|`pidFolder`|`PID_FOLDER`的默认值,只对`init.d`服务有效| +|`useStartStopDaemon`|如果`start-stop-daemon`命令可用,它会控制该实例,默认为`true`| + +**在脚本运行时自定义** + +对于需要在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`标识有设值,则你能轻松看到脚本的处理逻辑| + +**注** `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/56.2 Microsoft Windows services.md b/VI. Deploying Spring Boot applications/56.2 Microsoft Windows services.md new file mode 100644 index 00000000..fed2630a --- /dev/null +++ b/VI. Deploying Spring Boot applications/56.2 Microsoft Windows services.md @@ -0,0 +1,2 @@ +###56.2 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/57. What to read next.md b/VI. Deploying Spring Boot applications/57. What to read next.md new file mode 100644 index 00000000..429f7e36 --- /dev/null +++ b/VI. Deploying Spring Boot applications/57. What to read next.md @@ -0,0 +1,4 @@ +###57. 接下来阅读什么 +打开[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](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#cli),你也可以直接跳到[build tool plugins](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#build-tool-plugins)。 diff --git a/VI. Deploying Spring Boot applications/README.md b/VI. Deploying Spring Boot applications/README.md new file mode 100644 index 00000000..8793f45a --- /dev/null +++ b/VI. Deploying Spring Boot applications/README.md @@ -0,0 +1,4 @@ +### 部署Spring Boot应用 +Spring Boot灵活的打包选项为部署应用提供多种选择,你可以轻易的将Spring Boot应用部署到各种云平台,容器镜像(比如Docker)或虚拟/真实机器。 + +本章节覆盖一些比较常见的部署场景。 diff --git a/VI. Deploying to the cloud/52. Google App Engine.md b/VI. Deploying to the cloud/52. Google App Engine.md deleted file mode 100644 index 71c01cb8..00000000 --- a/VI. Deploying to the cloud/52. Google App Engine.md +++ /dev/null @@ -1,3 +0,0 @@ -### 52. Google App Engine - -Google App Engine跟Servlet 2.5 API是有联系的,所以在不修改的情况系你是不能部署一个Spring应用的。具体查看本指南的[Servlet 2.5章节](../IX. ‘How-to’ guides/74.5. Deploying a WAR in an Old (Servlet 2.5) Container.md)。 diff --git a/VI. Deploying to the cloud/53. What to read next.md b/VI. Deploying to the cloud/53. What to read next.md deleted file mode 100644 index e5166c86..00000000 --- a/VI. Deploying to the cloud/53. What to read next.md +++ /dev/null @@ -1 +0,0 @@ -### 53. 接下来阅读什么 diff --git a/VII. Spring Boot CLI/54. Installing the CLI.md b/VII. Spring Boot CLI/54. Installing the CLI.md deleted file mode 100644 index 68ba2457..00000000 --- a/VII. Spring Boot CLI/54. Installing the CLI.md +++ /dev/null @@ -1,3 +0,0 @@ -### 54. 安装CLI - -你可以手动安装Spring Boot CLI,也可以使用GVM(Groovy环境管理工具)或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/55.1.1. Deduced \342\200\234grab\342\200\235 dependencies.md" "b/VII. Spring Boot CLI/55.1.1. Deduced \342\200\234grab\342\200\235 dependencies.md" deleted file mode 100644 index 3b798229..00000000 --- "a/VII. Spring Boot CLI/55.1.1. Deduced \342\200\234grab\342\200\235 dependencies.md" +++ /dev/null @@ -1,25 +0,0 @@ -### 55.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|Caching abstraction| -|@Test|JUnit| -|@EnableRabbit|RabbitMQ| -|@EnableReactor|Project Reactor| -|继承Specification|Spock test| -|@EnableBatchProcessing|Spring Batch| -|@MessageEndpoint,@EnableIntegrationPatterns|Spring Integration| -|@EnableDeviceResolver|Spring Mobile| -|@Controller,@RestController,@EnableWebMvc|Spring MVC + Embedded 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/55.1.2. Deduced \342\200\234grab\342\200\235 coordinates.md" "b/VII. Spring Boot CLI/55.1.2. Deduced \342\200\234grab\342\200\235 coordinates.md" deleted file mode 100644 index 145d11c7..00000000 --- "a/VII. Spring Boot CLI/55.1.2. Deduced \342\200\234grab\342\200\235 coordinates.md" +++ /dev/null @@ -1,4 +0,0 @@ -### 55.1.2. 推断"grab"坐标 - -Spring Boot扩展Groovy标准"@Grab"注解使其能够允许你指定一个没有group或version的依赖,例如`@Grab('freemarker')`。 -artifact’s的组和版本是通过查看Spring Boot的依赖元数据推断出来的。注意默认的元数据是和你使用的CLI版本绑定的-只有在你迁移到一个CLI新版本时它才会改变,这样当你的依赖改变时你就可以控制了。在[附录](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#appendix-dependency-versions)的表格中可以查看默认元数据包含的依赖和它们的版本。 diff --git "a/VII. Spring Boot CLI/55.1.5. Custom \342\200\234grab\342\200\235 metadata.md" "b/VII. Spring Boot CLI/55.1.5. Custom \342\200\234grab\342\200\235 metadata.md" deleted file mode 100644 index e3b0c636..00000000 --- "a/VII. Spring Boot CLI/55.1.5. Custom \342\200\234grab\342\200\235 metadata.md" +++ /dev/null @@ -1,21 +0,0 @@ -### 55.1.5. 自定义"grab"元数据 - -Spring Boot提供一个新的`@GrabMetadata`注解,你可以使用它提供自定义的依赖元数据,以覆盖Spring Boot的默认配置。该元数据通过使用提供一个或多个配置文件坐标的注解来指定(使用一个属性标识符"type"部署到Maven仓库).。配置文件中的每个实体必须遵循`group:module=version`的格式。 - -例如,下面的声明: -```java -`@GrabMetadata("com.example.custom-versions:1.0.0")` -``` -将会加载Maven仓库处于`com/example/custom-versions/1.0.0/`下的`custom-versions-1.0.0.properties`文件。 - -可以通过注解指定多个属性文件,它们会以声明的顺序被使用。例如: -```java -`@GrabMetadata(["com.example.custom-versions:1.0.0", - "com.example.more-versions:1.0.0"])` -``` -意味着位于`more-versions`的属性将覆盖位于`custom-versions`的属性。 - -你可以在任何能够使用`@Grab`的地方使用`@GrabMetadata`,然而,为了确保元数据的顺序一致,你在应用程序中最多只能使用一次`@GrabMetadata`。[Spring IO Platform](http://platform.spring.io/)是一个非常有用的依赖元数据源(Spring Boot的超集),例如: -```java -@GrabMetadata('io.spring.platform:platform-versions:1.0.4.RELEASE') -``` diff --git a/VII. Spring Boot CLI/55.6. Using the embedded shell.md b/VII. Spring Boot CLI/55.6. Using the embedded shell.md deleted file mode 100644 index 5a2052ea..00000000 --- a/VII. Spring Boot CLI/55.6. Using the embedded shell.md +++ /dev/null @@ -1,14 +0,0 @@ -### 55.6. 使用内嵌shell - -Spring Boot包括完整的BASH和zsh shells的命令行脚本。如果你不使用它们中的任何一个(可能你是一个Window用户),那你可以使用`shell`命令启用一个集成shell。 -```shell -$ spring shell -Spring Boot (v1.3.0.BUILD-SNAPSHOT) -Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit. -``` -从内嵌shell中可以直接运行其他命令: -```shell -$ version -Spring CLI v1.3.0.BUILD-SNAPSHOT -``` -内嵌shell支持ANSI颜色输出和tab补全。如果需要运行一个原生命令,你可以使用`$`前缀。点击ctrl-c将退出内嵌shell。 diff --git a/VII. Spring Boot CLI/55.7. Adding extensions to the CLI.md b/VII. Spring Boot CLI/55.7. Adding extensions to the CLI.md deleted file mode 100644 index 00a44667..00000000 --- a/VII. Spring Boot CLI/55.7. Adding extensions to the CLI.md +++ /dev/null @@ -1,16 +0,0 @@ -### 55.7. 为CLI添加扩展 - -使用`install`命令可以为CLI添加扩展。该命令接收一个或多个格式为`group:artifact:version`的artifact坐标集。例如: -```shell -$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE -``` -除了安装你提供坐标的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/56. Developing application with the Groovy beans DSL.md b/VII. Spring Boot CLI/56. Developing application with the Groovy beans DSL.md deleted file mode 100644 index cbe70552..00000000 --- a/VII. Spring Boot CLI/56. Developing application with the Groovy beans DSL.md +++ /dev/null @@ -1,26 +0,0 @@ -### 56. 使用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/57. What to read next.md b/VII. Spring Boot CLI/57. What to read next.md deleted file mode 100644 index a9a9e12c..00000000 --- a/VII. Spring Boot CLI/57. What to read next.md +++ /dev/null @@ -1 +0,0 @@ -### 57. 接下来阅读什么 diff --git a/VII. Spring Boot CLI/58. Installing the CLI.md b/VII. Spring Boot CLI/58. Installing the CLI.md new file mode 100644 index 00000000..fe377eca --- /dev/null +++ b/VII. Spring Boot CLI/58. Installing the CLI.md @@ -0,0 +1,3 @@ +### 58. 安装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/55. Using the CLI.md b/VII. Spring Boot CLI/59. Using the CLI.md similarity index 83% rename from VII. Spring Boot CLI/55. Using the CLI.md rename to VII. Spring Boot CLI/59. Using the CLI.md index a58a6238..f6e90fbe 100644 --- a/VII. Spring Boot CLI/55. Using the CLI.md +++ b/VII. Spring Boot CLI/59. Using the CLI.md @@ -1,6 +1,6 @@ -### 55. 使用CLI +### 59. 使用CLI -一旦安装好CLI,你可以输入`spring`来运行它。如果你不使用任何参数运行`spring`,将会展现一个简单的帮助界面: +一旦安装好CLI,你可以输入`spring`来运行它。如果不使用任何参数运行`spring`,将会展现一个简单的帮助界面: ```shell $ spring usage: spring [--help] [--version] @@ -13,7 +13,7 @@ Available commands are: ... more command help is shown here ``` -你可以使用`help`获取任何支持命令的详细信息。例如: +你可以使用`help`获取任何支持命令的详细信息,例如: ```shell $ spring help run spring run - Run a spring groovy script @@ -37,5 +37,5 @@ Option Description `version`命令提供一个检查你正在使用的Spring Boot版本的快速方式: ```shell $ spring version -Spring CLI v1.3.0.BUILD-SNAPSHOT +Spring CLI v1.4.1.RELEASE ``` diff --git a/VII. Spring Boot CLI/55.1. Running applications using the CLI.md b/VII. Spring Boot CLI/59.1. Running applications using the CLI.md similarity index 62% rename from VII. Spring Boot CLI/55.1. Running applications using the CLI.md rename to VII. Spring Boot CLI/59.1. Running applications using the CLI.md index a920db00..472bfe95 100644 --- a/VII. Spring Boot CLI/55.1. Running applications using the CLI.md +++ b/VII. Spring Boot CLI/59.1. Running applications using the CLI.md @@ -1,8 +1,9 @@ -### 55.1. 使用CLI运行应用 +### 59.1 使用CLI运行应用 你可以使用`run`命令编译和运行Groovy源代码。Spring Boot CLI完全自包含,以致于你不需要安装任何外部的Groovy。 下面是一个使用Groovy编写的"hello world" web应用: + hello.grooy ```java @RestController @@ -15,15 +16,15 @@ class WebApplication { } ``` -想要编译和运行应用,输入: +编译和运行应用可以输入: ```shell $ spring run hello.groovy ``` -想要给应用传递命令行参数,你需要使用一个`--`来将它们和"spring"命令参数区分开来。例如: +你可以使用`--`将命令行参数和"spring"命令参数区分开来,例如: ```shell $ spring run hello.groovy -- --server.port=9000 ``` -想要设置JVM命令行参数,你可以使用`JAVA_OPTS`环境变量,例如: +你可以使用`JAVA_OPTS`环境变量设置JVM命令行参数,例如: ```shell $ JAVA_OPTS=-Xmx1024m spring run hello.groovy ``` diff --git "a/VII. Spring Boot CLI/59.1.1 Deduced \342\200\234grab\342\200\235 dependencies.md" "b/VII. Spring Boot CLI/59.1.1 Deduced \342\200\234grab\342\200\235 dependencies.md" new file mode 100644 index 00000000..08c481b7 --- /dev/null +++ "b/VII. Spring Boot CLI/59.1.1 Deduced \342\200\234grab\342\200\235 dependencies.md" @@ -0,0 +1,25 @@ +###59.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/59.1.2 Deduced \342\200\234grab\342\200\235 coordinates.md" "b/VII. Spring Boot CLI/59.1.2 Deduced \342\200\234grab\342\200\235 coordinates.md" new file mode 100644 index 00000000..505d25a0 --- /dev/null +++ "b/VII. Spring Boot CLI/59.1.2 Deduced \342\200\234grab\342\200\235 coordinates.md" @@ -0,0 +1,2 @@ +###59.1.2 推断"grab"坐标 +Spring Boot扩展了Groovy标准`@Grab`注解,使其能够允许你指定一个没有`group`或`version`的依赖,例如`@Grab('freemarker')`。Spring Boot使用默认依赖元数据推断artifact’s的group和version,需要注意的是默认元数据和你使用的CLI版本有绑定关系-只有在迁移到新版本的CLI时它才会改变,这样你就可以控制何时改变依赖了,在[附录](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#appendix-dependency-versions)的表格中可以查看默认元数据包含的依赖和它们的版本。 diff --git a/VII. Spring Boot CLI/55.1.3. Default import statements.md b/VII. Spring Boot CLI/59.1.3 Default import statements.md similarity index 91% rename from VII. Spring Boot CLI/55.1.3. Default import statements.md rename to VII. Spring Boot CLI/59.1.3 Default import statements.md index c98e1641..a4442d47 100644 --- a/VII. Spring Boot CLI/55.1.3. Default import statements.md +++ b/VII. Spring Boot CLI/59.1.3 Default import statements.md @@ -1,4 +1,4 @@ -### 55.1.3. 默认import语句 +###59.1.3 默认import语句 为了帮助你减少Groovy代码量,一些`import`语句被自动包含进来了。注意上面的示例中引用`@Component`,`@RestController`和`@RequestMapping`而没有使用全限定名或`import`语句。 diff --git a/VII. Spring Boot CLI/55.1.4. Automatic main method.md b/VII. Spring Boot CLI/59.1.4 Automatic main method.md similarity index 53% rename from VII. Spring Boot CLI/55.1.4. Automatic main method.md rename to VII. Spring Boot CLI/59.1.4 Automatic main method.md index 8b669d13..6460a56a 100644 --- a/VII. Spring Boot CLI/55.1.4. Automatic main method.md +++ b/VII. Spring Boot CLI/59.1.4 Automatic main method.md @@ -1,3 +1,3 @@ -### 55.1.4. 自动创建main方法 +###59.1.4 自动创建main方法 -跟等效的Java应用不同,你不需要在Groovy脚本中添加一个`public static void main(String[] args)`方法。Spring Boot 会使用你编译后的代码自动创建一个SpringApplication。 +跟等效的Java应用不同,你不需要在Groovy脚本中添加一个`public static void main(String[] args)`方法。Spring Boot会使用你编译后的代码自动创建一个`SpringApplication`。 diff --git a/VII. Spring Boot CLI/59.1.5 Custom dependency management.md b/VII. Spring Boot CLI/59.1.5 Custom dependency management.md new file mode 100644 index 00000000..6f22ab1b --- /dev/null +++ b/VII. Spring Boot CLI/59.1.5 Custom dependency management.md @@ -0,0 +1,18 @@ +### 59.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/55.2. Testing your code.md b/VII. Spring Boot CLI/59.2 Testing your code.md similarity index 59% rename from VII. Spring Boot CLI/55.2. Testing your code.md rename to VII. Spring Boot CLI/59.2 Testing your code.md index 0e84ae43..99b5e235 100644 --- a/VII. Spring Boot CLI/55.2. Testing your code.md +++ b/VII. Spring Boot CLI/59.2 Testing your code.md @@ -1,12 +1,12 @@ -### 55.2. 测试你的代码 +### 59.2 测试你的代码 -`test`命令允许你编译和运行应用程序的测试用例。常规使用方式如下: +`test`命令允许你编译和运行应用程序的测试用例,常规使用方式如下: ```shell $ spring test app.groovy tests.groovy Total: 1, Success: 1, : Failures: 0 Passed? true ``` -在这个示例中,`test.groovy`包含JUnit `@Test`方法或Spock `Specification`类。所有的普通框架注解和静态方法在不使用import导入的情况下,仍旧可以使用。 +在这个示例中,`test.groovy`包含JUnit `@Test`方法或Spock `Specification`类。所有的普通框架注解和静态方法在不使用`import`导入的情况下,仍旧可以使用。 下面是我们使用的`test.groovy`文件(含有一个JUnit测试): ```java @@ -19,4 +19,4 @@ class ApplicationTests { } ``` -**注**:如果有多个测试源文件,你可以倾向于使用一个test目录来组织它们。 +**注** 如果有多个测试源文件,你可能倾向于将它们放到`test`目录下。 diff --git a/VII. Spring Boot CLI/55.3. Applications with multiple source files.md b/VII. Spring Boot CLI/59.3 Applications with multiple source files.md similarity index 62% rename from VII. Spring Boot CLI/55.3. Applications with multiple source files.md rename to VII. Spring Boot CLI/59.3 Applications with multiple source files.md index 7f3d53ca..896b5568 100644 --- a/VII. Spring Boot CLI/55.3. Applications with multiple source files.md +++ b/VII. Spring Boot CLI/59.3 Applications with multiple source files.md @@ -1,10 +1,10 @@ -### 55.3. 多源文件应用 +### 59.3 多源文件应用 你可以在所有接收文件输入的命令中使用shell通配符。这允许你轻松处理来自一个目录下的多个文件,例如: ```shell $ spring run *.groovy ``` -如果你想将'test'或'spec'代码从主应用代码中分离,这项技术就十分有用了: +如果想将`test`或`spec`代码从主应用代码中分离,这项技术就十分有用了: ```shell $ spring test app/*.groovy test/*.groovy ``` diff --git a/VII. Spring Boot CLI/55.4. Packaging your application.md b/VII. Spring Boot CLI/59.4 Packaging your application.md similarity index 59% rename from VII. Spring Boot CLI/55.4. Packaging your application.md rename to VII. Spring Boot CLI/59.4 Packaging your application.md index 13003821..e9c81aa0 100644 --- a/VII. Spring Boot CLI/55.4. Packaging your application.md +++ b/VII. Spring Boot CLI/59.4 Packaging your application.md @@ -1,10 +1,10 @@ -### 55.4. 应用打包 +### 59.4 应用打包 -你可以使用`jar`命令打包应用程序为一个可执行的jar文件。例如: +你可以使用`jar`命令打包应用程序为一个可执行的jar文件,例如: ```shell $ spring jar my-app.jar *.groovy ``` -最终的jar包括编译应用产生的类和所有依赖,这样你就可以使用`java -jar`来执行它了。该jar文件也包括来自应用classpath的实体。你可以使用`--include`和`--exclude`添加明确的路径(两者都是用逗号分割,同样都接收值为'+'和'-'的前缀,'-'意味着它们将从默认设置中移除)。默认包含(includes): +最终的jar包括编译应用产生的类和所有依赖,这样你就可以使用`java -jar`来执行它了。该jar文件也包含了来自应用classpath的实体。你可以使用`--include`和`--exclude`添加明确的路径(两者都是用逗号分割,同样都接收值为'+'和'-'的前缀,'-'意味着它们将从默认设置中移除),默认包含(includes): ```shell public/**, resources/**, static/**, templates/**, META-INF/**, * ``` diff --git a/VII. Spring Boot CLI/55.5. Initialize a new project.md b/VII. Spring Boot CLI/59.5 Initialize a new project.md similarity index 86% rename from VII. Spring Boot CLI/55.5. Initialize a new project.md rename to VII. Spring Boot CLI/59.5 Initialize a new project.md index a6261c04..10252ce5 100644 --- a/VII. Spring Boot CLI/55.5. Initialize a new project.md +++ b/VII. Spring Boot CLI/59.5 Initialize a new project.md @@ -1,12 +1,12 @@ -### 55.5. 初始化新工程 +### 59.5 初始化新工程 -`init`命令允许你使用[start.spring.io](https://start.spring.io/)在不离开shell的情况下创建一个新的项目。例如: +`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`参数列出该服务的能力。 +这创建了一个`my-project`目录,它是一个基于Maven且依赖`spring-boot-starter-web`和`spring-boot-starter-data-jpa`的项目。你可以使用`--list`参数列出该服务的能力。 ```shell $ spring init --list ======================================= @@ -30,7 +30,7 @@ maven-project - Maven Project [format:project, build:maven] (default) ... ``` -`init`命令支持很多选项,查看`help`输出可以获得更多详情。例如,下面的命令创建一个使用Java8和war打包的gradle项目: +`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 diff --git a/VII. Spring Boot CLI/59.6 Using the embedded shell.md b/VII. Spring Boot CLI/59.6 Using the embedded shell.md new file mode 100644 index 00000000..47c61dbc --- /dev/null +++ b/VII. Spring Boot CLI/59.6 Using the embedded shell.md @@ -0,0 +1,13 @@ +### 59.6 使用内嵌shell +Spring Boot包括完整的BASH和zsh shells的命令行脚本,如果这两种你都不使用(可能你是一个Window用户),那你可以使用`shell`命令启用一个集成shell。 +```shell +$ spring shell +Spring Boot (v1.4.1.RELEASE) +Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit. +``` +从内嵌shell中可以直接运行其他命令: +```shell +$ version +Spring CLI v1.4.1.RELEASE +``` +内嵌shell支持ANSI彩色输出和tab补全,如果需要运行一个原生命令,你可以使用`!`前缀,点击`ctrl-c`将退出内嵌shell。 diff --git a/VII. Spring Boot CLI/59.7 Adding extensions to the CLI.md b/VII. Spring Boot CLI/59.7 Adding extensions to the CLI.md new file mode 100644 index 00000000..46c0338c --- /dev/null +++ b/VII. Spring Boot CLI/59.7 Adding extensions to the CLI.md @@ -0,0 +1,18 @@ +### 59.7 为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/60. Developing application with the Groovy beans DSL.md b/VII. Spring Boot CLI/60. Developing application with the Groovy beans DSL.md new file mode 100644 index 00000000..d1d991e8 --- /dev/null +++ b/VII. Spring Boot CLI/60. Developing application with the Groovy beans DSL.md @@ -0,0 +1,26 @@ +### 60. 使用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/61. Configuring the CLI with settings.xml.md b/VII. Spring Boot CLI/61. Configuring the CLI with settings.xml.md new file mode 100644 index 00000000..9a84896f --- /dev/null +++ b/VII. Spring Boot CLI/61. Configuring the CLI with settings.xml.md @@ -0,0 +1,16 @@ +### 61. 使用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/62. What to read next.md b/VII. Spring Boot CLI/62. What to read next.md new file mode 100644 index 00000000..62121f40 --- /dev/null +++ b/VII. Spring Boot CLI/62. What to read next.md @@ -0,0 +1,4 @@ +### 62. 接下来阅读什么 +GitHub仓库有一些[groovy脚本示例](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-cli/samples)可用于尝试Spring Boot CLI,[源码](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/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/README.md b/VII. Spring Boot CLI/README.md index f3f95c69..9934b328 100644 --- a/VII. Spring Boot CLI/README.md +++ b/VII. Spring Boot CLI/README.md @@ -1,3 +1,2 @@ ### Spring Boot CLI - -Spring Boot CLI是一个命令行工具,如果想使用Spring进行快速开发可以使用它。它允许你运行Groovy脚本,这意味着你可以使用熟悉的类Java语法,并且没有那么多的模板代码。你也可以启动一个新的项目或为Spring Boot CLI编写自己的命令。 +Spring Boot CLI是一个命令行工具,如果想使用Spring进行快速开发可以使用它。它允许你运行Groovy脚本,这意味着你可以使用熟悉的类Java语法,并且没有那么多的模板代码。你可以通过Spring Boot CLI启动新项目,或为它编写命令。 diff --git a/VIII. Build tool plugins/58. Spring Boot Maven plugin.md b/VIII. Build tool plugins/58. Spring Boot Maven plugin.md deleted file mode 100644 index 3e1b628e..00000000 --- a/VIII. Build tool plugins/58. Spring Boot Maven plugin.md +++ /dev/null @@ -1,5 +0,0 @@ -### 58. Spring Boot Maven插件 - -Spring Boot Maven插件为Maven提供Spring Boot支持,它允许你打包可执行jar或war存档,然后就地运行应用。为了使用它,你需要使用Maven 3.2 (或更高版本)。 - -**注**:参考[Spring Boot Maven Plugin Site](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/)可以获取全部的插件文档。 diff --git a/VIII. Build tool plugins/59.10. Publishing artifacts to a Maven repository using Gradle.md b/VIII. Build tool plugins/59.10. Publishing artifacts to a Maven repository using Gradle.md deleted file mode 100644 index 0517acd7..00000000 --- a/VIII. Build tool plugins/59.10. Publishing artifacts to a Maven repository using Gradle.md +++ /dev/null @@ -1,3 +0,0 @@ -### 59.10. 使用Gradle将artifacts发布到一个Maven仓库 - -如果你声明依赖但没有指定版本,且你想要将artifacts发布到一个Maven仓库,那你需要使用详细的Spring Boot依赖管理来配置Maven发布。通过配置它发布继承自`spring-boot-starter-parent`的poms或引入来自`spring-boot-dependencies`的依赖管理可以实现该需求。这种配置的具体细节取决于你如何使用Gradle及如何发布该artifacts的。 diff --git a/VIII. Build tool plugins/59.2. Declaring dependencies without versions.md b/VIII. Build tool plugins/59.2. Declaring dependencies without versions.md deleted file mode 100644 index c323ed77..00000000 --- a/VIII. Build tool plugins/59.2. Declaring dependencies without versions.md +++ /dev/null @@ -1,18 +0,0 @@ -### 59.2. 声明不带版本的依赖 - -`spring-boot`插件会为你的构建注册一个自定义的Gradle `ResolutionStrategy`,它允许你在声明对"神圣"的artifacts的依赖时获取版本号。为了充分使用该功能,只需要想通常那样声明依赖,但将版本号设置为空: -```gradle -dependencies { - compile("org.springframework.boot:spring-boot-starter-web") - compile("org.thymeleaf:thymeleaf-spring4") - compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect") -} -``` -**注**:你声明的`spring-boot` Gradle插件的版本决定了"blessed"依赖的实际版本(确保可以重复构建)。你最好总是将`spring-boot` gradle插件版本设置为你想用的Spring Boot实际版本。提供的版本详细信息可以在[附录](../X. Appendices/E. Dependency versions.md)中找到。 - -`spring-boot`插件对于没有指定版本的依赖只会提供一个版本。如果不想使用插件提供的版本,你可以像平常那样在声明依赖的时候指定版本。例如: -```gradle -dependencies { - compile("org.thymeleaf:thymeleaf-spring4:2.1.1.RELEASE") -} -``` diff --git a/VIII. Build tool plugins/59.2.1. Custom version management.md b/VIII. Build tool plugins/59.2.1. Custom version management.md deleted file mode 100644 index 7615ac4c..00000000 --- a/VIII. Build tool plugins/59.2.1. Custom version management.md +++ /dev/null @@ -1,14 +0,0 @@ -### 59.2.1. 自定义版本管理 - -如果你需要不同于Spring Boot的"blessed"依赖,有可能的话可以自定义`ResolutionStrategy`使用的版本。替代的版本元数据使用`versionManagement`配置。例如: -```gradle -dependencies { - versionManagement("com.mycorp:mycorp-versions:1.0.0.RELEASE@properties") - compile("org.springframework.data:spring-data-hadoop") -} -``` -版本信息需要作为一个`.properties`文件发布到一个仓库中。对于上面的示例,`mycorp-versions.properties`文件可能包含以下内容: -```java -org.springframework.data\:spring-data-hadoop=2.0.0.RELEASE -``` -属性文件优先于Spring Boot默认设置,如果有必要的话可以覆盖版本号。 diff --git a/VIII. Build tool plugins/59.3. Default exclude rules.md b/VIII. Build tool plugins/59.3. Default exclude rules.md deleted file mode 100644 index 71f5cd82..00000000 --- a/VIII. Build tool plugins/59.3. Default exclude rules.md +++ /dev/null @@ -1,33 +0,0 @@ -### 59.3. 默认排除规则 - -Gradle处理"exclude rules"的方式和Maven稍微有些不同,在使用starter POMs时这可能会引起无法预料的结果。特别地,当一个依赖可以通过不同的路径访问时,对该依赖声明的exclusions将不会生效。例如,如果一个starter POM声明以下内容: -```xml - - - org.springframework - spring-core - 4.0.5.RELEASE - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - 4.0.5.RELEASE - - -``` -`commons-logging` jar不会被Gradle排除,因为通过没有`exclusion`元素的`spring-context`可以传递性的拉取到它(spring-context → spring-core → commons-logging)。 - -为了确保正确的排除被实际应用,Spring Boot Gradle插件将自动添加排除规则。所有排除被定义在`spring-boot-dependencies` POM,并且针对"starter" POMs的隐式规则也会被添加。 - -如果不想自动应用排除规则,你可以使用以下配置: -```gradle -springBoot { - applyExcludeRules=false -} -``` diff --git a/VIII. Build tool plugins/59.5. Running a project in-place.md b/VIII. Build tool plugins/59.5. Running a project in-place.md deleted file mode 100644 index 5cc09cbb..00000000 --- a/VIII. Build tool plugins/59.5. Running a project in-place.md +++ /dev/null @@ -1,14 +0,0 @@ -### 59.5. 就地(in-place)运行项目 - -为了在不先构建jar的情况下运行项目,你可以使用"bootRun"任务: -```shell -$ gradle bootRun -``` -默认情况下,以这种方式运行项目可以让你的静态classpath资源(比如,默认位于`src/main/resources`下)在应用运行期间被重新加载。使静态资源可以重新加载意味着`bootRun`任务不会使用`processResources`任务的输出,比如,当调用`bootRun`时,你的应用将以资源未处理的形式来使用它们。 - -你可以禁止直接使用静态classpath资源。这意味着资源不再是可重新加载的,但`processResources`任务的输出将会被使用。想要这样做,只需将`bootRun`任务的`addResources`设为false: -```gradle -bootRun { - addResources = false -} -``` diff --git a/VIII. Build tool plugins/59.7. Repackage configuration.md b/VIII. Build tool plugins/59.7. Repackage configuration.md deleted file mode 100644 index 3e685f7e..00000000 --- a/VIII. Build tool plugins/59.7. Repackage configuration.md +++ /dev/null @@ -1,17 +0,0 @@ -### 59.7. Repackage配置 - -该插件添加了一个bootRepackage任务,你可以直接配置它,比如: -```gradle -bootRepackage { - mainClass = 'demo.Application' -} -``` -下面是可用的配置选项: - -|名称|描述| -|-------|:------| -|enabled|布尔值,用于控制repackager的开关(如果你只想要Boot的其他特性而不是这个,那它就派上用场了)| -|mainClass|要运行的main类。如果没有指定,则使用project属性mainClassName。如果没有定义mainClassName id,则搜索存档以寻找一个合适的类。"合适"意味着一个唯一的,具有良好格式的`main()`方法的类(如果找到多个则构建会失败)。你也可以通过"run"任务(main属性)指定main类的名称,和/或将"startScripts"(mainClassName属性)作为"springBoot"配置的替代。| -|classifier|添加到存档的一个文件名字段(在扩展之前),这样最初保存的存档仍旧存放在最初的位置。在存档被重新打包(repackage)的情况下,该属性默认为null。默认值适用于多数情况,但如果你想在另一个项目中使用原jar作为依赖,最好使用一个扩展来定义该可执行jar| -|withJarTask|Jar任务的名称或值,用于定位要被repackage的存档| -|customConfiguration|自定义配置的名称,用于填充内嵌的lib目录(不指定该属性,你将获取所有编译和运行时依赖)| diff --git a/VIII. Build tool plugins/59.8. Repackage with custom Gradle configuration.md b/VIII. Build tool plugins/59.8. Repackage with custom Gradle configuration.md deleted file mode 100644 index 2839d55b..00000000 --- a/VIII. Build tool plugins/59.8. Repackage with custom Gradle configuration.md +++ /dev/null @@ -1,28 +0,0 @@ -### 59.8. 使用Gradle自定义配置进行Repackage - -有时候不打包解析自compile,runtime和provided作用域的默认依赖可能更合适些。如果创建的可执行jar被原样运行,你需要将所有的依赖内嵌进该jar中;然而,如果目的是explode一个jar文件,并手动运行main类,你可能在CLASSPATH下已经有一些可用的库了。在这种情况下,你可以使用不同的依赖集重新打包(repackage)你的jar。 - -使用自定义的配置将自动禁用来自compile,runtime和provided作用域的依赖解析。自定义配置即可以定义为全局的(处于springBoot部分内),也可以定义为任务级的。 -```gradle -task clientJar(type: Jar) { - appendix = 'client' - from sourceSets.main.output - exclude('**/*Something*') -} - -task clientBoot(type: BootRepackage, dependsOn: clientJar) { - withJarTask = clientJar - customConfiguration = "mycustomconfiguration" -} -``` -在以上示例中,我们创建了一个新的clientJar Jar任务从你编译后的源中打包一个自定义文件集。然后我们创建一个新的clientBoot BootRepackage任务,并让它使用clientJar任务和mycustomconfiguration。 -```gradle -configurations { - mycustomconfiguration.exclude group: 'log4j' -} - -dependencies { - mycustomconfiguration configurations.runtime -} -``` -在BootRepackage中引用的配置是一个正常的[Gradle配置](http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.Configuration.html)。在上面的示例中,我们创建了一个新的名叫mycustomconfiguration的配置,指示它来自一个runtime,并排除对log4j的依赖。如果clientBoot任务被执行,重新打包的jar将含有所有来自runtime作用域的依赖,除了log4j jars。 diff --git a/VIII. Build tool plugins/59.8.1. Configuration options.md b/VIII. Build tool plugins/59.8.1. Configuration options.md deleted file mode 100644 index 4a1746c6..00000000 --- a/VIII. Build tool plugins/59.8.1. Configuration options.md +++ /dev/null @@ -1,12 +0,0 @@ -### 59.8.1. 配置选项 - -可用的配置选项如下: - -|名称|描述| -|-------|:--------| -|mainClass|可执行jar运行的main类| -|providedConfiguration|provided配置的名称(默认为providedRuntime)| -|backupSource|在重新打包之前,原先的存档是否备份(默认为true)| -|customConfiguration|自定义配置的名称| -|layout|存档类型,对应于内部依赖是如何制定的(默认基于存档类型进行推测)| -|requiresUnpack|一个依赖列表(格式为"groupId:artifactId",为了运行,它们需要从fat jars中解压出来。)所有节点被打包进胖jar,但运行的时候它们将被自动解压| diff --git a/VIII. Build tool plugins/60.1. Repackaging archives.md b/VIII. Build tool plugins/60.1. Repackaging archives.md deleted file mode 100644 index 12d8e09c..00000000 --- a/VIII. Build tool plugins/60.1. Repackaging archives.md +++ /dev/null @@ -1,3 +0,0 @@ -### 60.1. 重新打包存档 - -使用`org.springframework.boot.loader.tools.Repackager`可以将一个存在的存档重新打包,这样它就变成一个自包含的可执行存档。`Repackager`类需要提供单一的构造器参数,它引用一个存在的jar或war包。使用两个可用的`repackage()`方法中的一个来替换原始的文件或写入一个新的目标。在repackager运行前还可以设置各种配置。 diff --git a/VIII. Build tool plugins/60.2. Nested libraries.md b/VIII. Build tool plugins/60.2. Nested libraries.md deleted file mode 100644 index 9bf8a3fc..00000000 --- a/VIII. Build tool plugins/60.2. Nested libraries.md +++ /dev/null @@ -1,5 +0,0 @@ -### 60.2. 内嵌的库 - -当重新打包一个存档时,你可以使用`org.springframework.boot.loader.tools.Libraries`接口来包含对依赖文件的引用。在这里我们不提供任何该Libraries接口的具体实现,因为它们通常跟具体的构建系统相关。 - -如果你的存档已经包含libraries,你可以使用`Libraries.NONE`。 diff --git a/VIII. Build tool plugins/61. What to read next.md b/VIII. Build tool plugins/61. What to read next.md deleted file mode 100644 index 8204d7a1..00000000 --- a/VIII. Build tool plugins/61. What to read next.md +++ /dev/null @@ -1 +0,0 @@ -### 61. 接下来阅读什么 diff --git a/VIII. Build tool plugins/63. Spring Boot Maven plugin.md b/VIII. Build tool plugins/63. Spring Boot Maven plugin.md new file mode 100644 index 00000000..04f554da --- /dev/null +++ b/VIII. Build tool plugins/63. Spring Boot Maven plugin.md @@ -0,0 +1,5 @@ +### 63. Spring Boot Maven插件 + +[Spring Boot Maven插件](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/maven-plugin/)为Maven提供Spring Boot支持,它允许你打包可执行jar或war存档,然后就地运行应用。为了使用它,你需要使用Maven 3.2(或更高版本)。 + +**注** 参考[Spring Boot Maven Plugin Site](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/maven-plugin/)可以获取全部的插件文档。 diff --git a/VIII. Build tool plugins/58.1. Including the plugin.md b/VIII. Build tool plugins/63.1 Including the plugin.md similarity index 87% rename from VIII. Build tool plugins/58.1. Including the plugin.md rename to VIII. Build tool plugins/63.1 Including the plugin.md index a8a7597e..f7f175f5 100644 --- a/VIII. Build tool plugins/58.1. Including the plugin.md +++ b/VIII. Build tool plugins/63.1 Including the plugin.md @@ -1,4 +1,4 @@ -### 58.1. 包含该插件 +### 63.1 包含该插件 想要使用Spring Boot Maven插件只需简单地在你的pom.xml的`plugins`部分包含相应的XML: ```xml @@ -12,7 +12,7 @@ org.springframework.boot spring-boot-maven-plugin - 1.3.0.BUILD-SNAPSHOT + 1.4.1.RELEASE @@ -25,19 +25,19 @@ ``` -该配置会在Maven生命周期的`package`阶段重新打包一个jar或war。下面的示例显示在`target`目录下既有重新打包后的jar,也有原始的jar: +该配置会在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目标也被使用的情况)。例如: +如果不包含像上面那样的``,你可以自己运行该插件(但只有在package目标也被使用的情况),例如: ```shell $ mvn package spring-boot:repackage $ ls target/*.jar target/myproject-1.0.0.jar target/myproject-1.0.0.jar.original ``` -如果使用一个里程碑或快照版本,你还需要添加正确的pluginRepository元素: +如果使用一个里程碑或快照版本,你还需要添加正确的`pluginRepository`元素: ```xml diff --git a/VIII. Build tool plugins/58.2. Packaging executable jar and war files.md b/VIII. Build tool plugins/63.2 Packaging executable jar and war files.md similarity index 67% rename from VIII. Build tool plugins/58.2. Packaging executable jar and war files.md rename to VIII. Build tool plugins/63.2 Packaging executable jar and war files.md index e81eaf0a..e41a3c53 100644 --- a/VIII. Build tool plugins/58.2. Packaging executable jar and war files.md +++ b/VIII. Build tool plugins/63.2 Packaging executable jar and war files.md @@ -1,6 +1,6 @@ -### 58.2. 打包可执行jar和war文件 +### 63.2 打包可执行jar和war文件 -一旦`spring-boot-maven-plugin`被包含到你的pom.xml中,它就会自动尝试使用`spring-boot:repackage`目标重写存档以使它们能够执行。为了构建一个jar或war,你应该使用常规的packaging元素配置你的项目: +一旦`spring-boot-maven-plugin`被包含到你的`pom.xml`中,Spring Boot就会自动尝试使用`spring-boot:repackage`目标重写存档以使它们能够执行。为了构建一个jar或war,你应该使用常规的`packaging`元素配置你的项目: ```xml ``` -**注**:具体参考[“Section 74.1, “Create a deployable war file”” ](../IX. ‘How-to’ guides/74.1. Create a deployable war file.md)章节。 +**注** 具体参考[“Section 81.1, “Create a deployable war file”” ](../IX. ‘How-to’ guides/81.1. Create a deployable war file.md)章节。 -在[插件信息页面](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/)有高级的配置选项和示例。 +高级配置选项和示例可在[插件信息页面](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/maven-plugin/)获取。 diff --git a/VIII. Build tool plugins/59. Spring Boot Gradle plugin.md b/VIII. Build tool plugins/64. Spring Boot Gradle plugin.md similarity index 52% rename from VIII. Build tool plugins/59. Spring Boot Gradle plugin.md rename to VIII. Build tool plugins/64. Spring Boot Gradle plugin.md index a0049112..bf98746b 100644 --- a/VIII. Build tool plugins/59. Spring Boot Gradle plugin.md +++ b/VIII. Build tool plugins/64. Spring Boot Gradle plugin.md @@ -1,3 +1,3 @@ -### 59. Spring Boot Gradle插件 +### 64. Spring Boot Gradle插件 -Spring Boot Gradle插件为Gradle提供Spring Boot支持,它允许你打包可执行jar或war存档,运行Spring Boot应用,对于"神圣的"依赖可以在你的build.gradle文件中省略版本信息。 +Spring Boot Gradle插件为Gradle提供Spring Boot支持,它允许你打包可执行jar或war存档,运行Spring Boot应用,使用`spring-boot-dependencies`提供的依赖管理。 diff --git a/VIII. Build tool plugins/59.1. Including the plugin.md b/VIII. Build tool plugins/64.1 Including the plugin.md similarity index 72% rename from VIII. Build tool plugins/59.1. Including the plugin.md rename to VIII. Build tool plugins/64.1 Including the plugin.md index 539c156b..2bfd41f8 100644 --- a/VIII. Build tool plugins/59.1. Including the plugin.md +++ b/VIII. Build tool plugins/64.1 Including the plugin.md @@ -1,15 +1,15 @@ -### 59.1. 包含该插件 +### 64.1 包含该插件 想要使用Spring Boot Gradle插件,你只需简单的包含一个`buildscript`依赖,并应用`spring-boot`插件: ```gradle buildscript { dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.BUILD-SNAPSHOT") + classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE") } } apply plugin: 'spring-boot' ``` -如果想使用一个里程碑或快照版本,你可以添加相应的repositories引用: +如果使用的是一个里程碑或快照版本,你需要添加相应的`repositories`引用: ```gradle buildscript { repositories { diff --git a/VIII. Build tool plugins/64.2 Gradle dependency management.md b/VIII. Build tool plugins/64.2 Gradle dependency management.md new file mode 100644 index 00000000..980fd329 --- /dev/null +++ b/VIII. Build tool plugins/64.2 Gradle dependency management.md @@ -0,0 +1,18 @@ +### 64.2 Gradle依赖管理 + +`spring-boot`插件自动应用[Dependency Management Plugin](https://github.com/spring-gradle-plugins/dependency-management-plugin/),并配置它导入`spring-boot-starter-parent` bom。这提供了跟Maven用户喜欢的相似依赖管理体验,例如,如果声明的依赖在bom中被管理的话,你就可以省略版本。为了充分使用该功能,只需要想通常那样声明依赖,但将版本号设置为空: +```gradle +dependencies { + compile("org.springframework.boot:spring-boot-starter-web") + compile("org.thymeleaf:thymeleaf-spring4") + compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect") +} +``` +**注** 你声明的`spring-boot` Gradle插件的版本决定了`spring-boot-starter-parent` bom导入的版本(确保可以重复构建)。你最好将`spring-boot` gradle插件版本跟Spring Boot版本保持一致,版本详细信息可以在[附录](../X. Appendices/E. Dependency versions.md)中查看。 + +`spring-boot`插件对于没有指定版本的依赖只会提供一个版本。如果不想使用插件提供的版本,你可以像平常那样在声明依赖的时候指定版本。例如: +```gradle +dependencies { + compile("org.thymeleaf:thymeleaf-spring4:2.1.1.RELEASE") +} +``` diff --git a/VIII. Build tool plugins/59.4. Packaging executable jar and war files.md b/VIII. Build tool plugins/64.3 Packaging executable jar and war files.md similarity index 78% rename from VIII. Build tool plugins/59.4. Packaging executable jar and war files.md rename to VIII. Build tool plugins/64.3 Packaging executable jar and war files.md index 07a04240..5b73c729 100644 --- a/VIII. Build tool plugins/59.4. Packaging executable jar and war files.md +++ b/VIII. Build tool plugins/64.3 Packaging executable jar and war files.md @@ -1,4 +1,4 @@ -### 59.4. 打包可执行jar和war文件 +### 64.3 打包可执行jar和war文件 一旦`spring-boot`插件被应用到你的项目,它将使用`bootRepackage`任务自动尝试重写存档以使它们能够执行。为了构建一个jar或war,你需要按通常的方式配置项目。 @@ -9,7 +9,7 @@ $ gradle build $ java -jar build/libs/mymodule-0.0.1-SNAPSHOT.jar ``` -为了构建一个即能执行也可以部署到外部容器的war包,你需要将内嵌容器依赖标记为"providedRuntime",比如: +为了构建一个即能执行也可以部署到外部容器的war包,你需要将内嵌容器依赖标记为`providedRuntime`,比如: ```gradle ... apply plugin: 'war' @@ -34,4 +34,4 @@ dependencies { ... } ``` -**注**:具体参考[“Section 74.1, “Create a deployable war file””](../IX. ‘How-to’ guides/74.1. Create a deployable war file.md)。 +**注** 具体参考[“Section 81.1, “Create a deployable war file””](../IX. ‘How-to’ guides/81.1. Create a deployable war file.md)。 diff --git a/VIII. Build tool plugins/64.4 Running a project in-place.md b/VIII. Build tool plugins/64.4 Running a project in-place.md new file mode 100644 index 00000000..a4757e57 --- /dev/null +++ b/VIII. Build tool plugins/64.4 Running a project in-place.md @@ -0,0 +1,13 @@ +### 64.4 就地(in-place)运行项目 + +为了在不先构建jar的情况下运行项目,你可以使用`bootRun`任务: +```shell +$ gradle bootRun +``` +如果项目中添加了[devtools](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#using-boot-devtools),它将自动监控你的应用变动。此外,你可以运行应用,这样静态classpath资源(比如,默认位于`src/main/resources`下)在应用运行期间将能够重新加载,这在开发期间是非常有用的: +```gradle +bootRun { + addResources = true +} +``` +让静态classpath资源可加载意味着`bootRun`不使用`processResources`任务的输出,例如,当使用`bootRun`调用时,你的应用将以未经处理的形式使用资源。 diff --git a/VIII. Build tool plugins/59.6. Spring Boot plugin configuration.md b/VIII. Build tool plugins/64.5 Spring Boot plugin configuration.md similarity index 87% rename from VIII. Build tool plugins/59.6. Spring Boot plugin configuration.md rename to VIII. Build tool plugins/64.5 Spring Boot plugin configuration.md index 32b26f07..83fc9300 100644 --- a/VIII. Build tool plugins/59.6. Spring Boot plugin configuration.md +++ b/VIII. Build tool plugins/64.5 Spring Boot plugin configuration.md @@ -1,4 +1,4 @@ -### 59.6. Spring Boot插件配置 +### 64.5 Spring Boot插件配置 Gradle插件自动扩展你的构建脚本DSL,它为脚本添加一个`springBoot`元素以此作为Boot插件的全局配置。你可以像配置其他Gradle扩展那样为`springBoot`设置相应的属性(下面有配置选项列表)。 ```gradle diff --git a/VIII. Build tool plugins/64.6 Repackage configuration.md b/VIII. Build tool plugins/64.6 Repackage configuration.md new file mode 100644 index 00000000..8c3942ae --- /dev/null +++ b/VIII. Build tool plugins/64.6 Repackage configuration.md @@ -0,0 +1,21 @@ +### 64.6 Repackage配置 + +该插件添加了一个`bootRepackage`任务,你可以直接配置它,比如: +```gradle +bootRepackage { + mainClass = 'demo.Application' +} +``` +下面是可用的配置选项: + +|名称|描述| +|-------|:------| +|`enabled`|布尔值,用于控制repackager的开关(如果你只想要Boot的其他特性而不是这个,那它就派上用场了)| +|`mainClass`|要运行的main类。如果没有指定,则使用project属性`mainClassName`。如果该应用插件没有使用或没有定义`mainClassName`,则搜索存档以寻找一个合适的类。"合适"意味着一个唯一的,具有良好格式的`main()`方法的类(如果找到多个则构建会失败)。你也可以通过`run`任务(`main`属性)指定`main`类的名称,和/或将"startScripts"(`mainClassName`属性)作为"springBoot"配置的替代。| +|`classifier`|添加到存档的一个文件名字段(在扩展之前),这样最初保存的存档仍旧存放在最初的位置。在存档被重新打包(repackage)的情况下,该属性默认为`null`。默认值适用于多数情况,但如果你想在另一个项目中使用原jar作为依赖,最好使用一个扩展来定义该可执行jar| +|`withJarTask`|Jar任务的名称或值,用于定位要被repackage的存档| +|`customConfiguration`|自定义配置的名称,用于填充内嵌的lib目录(不指定该属性,你将获取所有编译和运行时依赖)| +|`executable`|布尔值标识,表示jar文件在类Unix系统上是否完整可执行,默认为`false`| +|`embeddedLaunchScript`|如果jar是完整可执行的,该内嵌启动脚本将添加到jar。如果没有指定,将使用Spring Boot默认的脚本| +|`embeddedLaunchScriptProperties`|启动脚本暴露的其他属性,默认脚本支持`mode`属性,值可以是`auto`,`service`或`run`| +|`excludeDevtools`|布尔值标识,表示devtools jar是否应该从重新打包的存档中排除出去,默认为`false`| diff --git a/VIII. Build tool plugins/64.7 Repackage with custom Gradle configuration.md b/VIII. Build tool plugins/64.7 Repackage with custom Gradle configuration.md new file mode 100644 index 00000000..09d2d8d7 --- /dev/null +++ b/VIII. Build tool plugins/64.7 Repackage with custom Gradle configuration.md @@ -0,0 +1,28 @@ +### 64.7 使用Gradle自定义配置进行Repackage + +有时候不打包解析自`compile`,`runtime`和`provided`作用域的默认依赖可能更合适些。如果创建的可执行jar被原样运行,你需要将所有的依赖内嵌进该jar中;然而,如果目的是explode一个jar文件,并手动运行main类,你可能在`CLASSPATH`下已经有一些可用的库了。在这种情况下,你可以使用不同的依赖集重新打包(repackage)你的jar。 + +使用自定义的配置将自动禁用来自`compile`,`runtime`和`provided`作用域的依赖解析。自定义配置即可以定义为全局的(处于`springBoot`部分内),也可以定义为任务级的。 +```gradle +task clientJar(type: Jar) { + appendix = 'client' + from sourceSets.main.output + exclude('**/*Something*') +} + +task clientBoot(type: BootRepackage, dependsOn: clientJar) { + withJarTask = clientJar + customConfiguration = "mycustomconfiguration" +} +``` +在以上示例中,我们创建了一个新的`clientJar` Jar任务从你编译后的源中打包一个自定义文件集。然后我们创建一个新的`clientBoot` BootRepackage任务,并让它使用`clientJar`任务和`mycustomconfiguration`。 +```gradle +configurations { + mycustomconfiguration.exclude group: 'log4j' +} + +dependencies { + mycustomconfiguration configurations.runtime +} +``` +在`BootRepackage`中引用的配置是一个正常的[Gradle配置](http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.Configuration.html)。在以上示例中,我们创建了一个新的名叫`mycustomconfiguration`的配置,指示它来自一个`runtime`,并排除对`log4j`的依赖。如果`clientBoot`任务被执行,重新打包的jar将含有所有来自`runtime`作用域的依赖,除了`log4j` jars。 diff --git a/VIII. Build tool plugins/64.7.1 Configuration options.md b/VIII. Build tool plugins/64.7.1 Configuration options.md new file mode 100644 index 00000000..aaa73268 --- /dev/null +++ b/VIII. Build tool plugins/64.7.1 Configuration options.md @@ -0,0 +1,12 @@ +### 64.7.1 配置选项 + +可用的配置选项如下: + +|名称|描述| +|-------|:--------| +|`mainClass`|可执行jar运行的main类| +|`providedConfiguration`|provided配置的名称(默认为`providedRuntime`)| +|`backupSource`|在重新打包之前,原先的存档是否备份(默认为`true`)| +|`customConfiguration`|自定义配置的名称| +|`layout`|存档类型,对应于内部依赖是如何制定的(默认基于存档类型进行推测),具体查看[available layouts](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#build-tool-plugins-gradle-configuration-layouts)| +|`requiresUnpack`|一个依赖列表(格式为"groupId:artifactId",为了运行,它们需要从fat jars中解压出来。)所有节点被打包进胖jar,但运行的时候它们将被自动解压| diff --git a/VIII. Build tool plugins/64.7.2 Available layouts.md b/VIII. Build tool plugins/64.7.2 Available layouts.md new file mode 100644 index 00000000..e366c39d --- /dev/null +++ b/VIII. Build tool plugins/64.7.2 Available layouts.md @@ -0,0 +1,11 @@ +###64.7.2 可用的layouts + +`layout`属性用于配置存档格式及启动加载器是否包含,以下为可用的layouts: + +|名称|描述|可执行| +|:----|:------|:-----| +|`JAR`|常规的可执行[JAR layout](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#executable-jar-jar-file-structure)|是| +|`WAR`|可执行[WAR layout](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#executable-jar-war-file-structure),`provided`依赖放置到`WEB-INF/lib-provided`,以免`war`部署到servlet容器时造成冲突|是| +|`ZIP`(别名`DIR`)|跟`JAR` layout类似,使用[PropertiesLauncher](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#executable-jar-property-launcher-features)|是| +|`MODULE`|捆绑(Bundle)依赖(排除那些`provided`作用域的依赖)和项目资源|否| +|`NONE`|捆绑(Bundle)所有依赖和项目资源|否| diff --git a/VIII. Build tool plugins/59.9. Understanding how the Gradle plugin works.md b/VIII. Build tool plugins/64.8 Understanding how the Gradle plugin works.md similarity index 57% rename from VIII. Build tool plugins/59.9. Understanding how the Gradle plugin works.md rename to VIII. Build tool plugins/64.8 Understanding how the Gradle plugin works.md index 3165a0c5..e61f1ea8 100644 --- a/VIII. Build tool plugins/59.9. Understanding how the Gradle plugin works.md +++ b/VIII. Build tool plugins/64.8 Understanding how the Gradle plugin works.md @@ -1,8 +1,8 @@ -### 59.9. 理解Gradle插件是如何工作的 +### 64.8 理解Gradle插件是如何工作的 -当`spring-boot`被应用到你的Gradle项目,一个默认的名叫`bootRepackage`的任务被自动创建。`bootRepackage`任务依赖于Gradle `assemble`任务,当执行时,它会尝试找到所有限定符为空的jar artifacts(也就是说,tests和sources jars被自动跳过)。 +当`spring-boot`应用到你的Gradle项目,一个默认的名叫`bootRepackage`的任务被自动创建。`bootRepackage`任务依赖于Gradle `assemble`任务,当执行时,它会尝试找到所有限定符为空的jar artifacts(也就是说,tests和sources jars被自动跳过)。 -由于`bootRepackage`查找'所有'创建jar artifacts的事实,Gradle任务执行的顺序就非常重要了。多数项目只创建一个单一的jar文件,所以通常这不是一个问题。然而,如果你正打算创建一个更复杂的,使用自定义`jar`和`BootRepackage`任务的项目setup,有几个方面需要考虑。 +由于`bootRepackage`会查找'所有'创建的jar artifacts,Gradle任务执行的顺序就非常重要了。多数项目只创建一个单一的jar文件,所以通常这不是一个问题。然而,如果你正打算创建一个更复杂的,使用自定义`jar`和`BootRepackage`任务的项目setup,有几个方面需要考虑。 如果'仅仅'从项目创建自定义jar文件,你可以简单地禁用默认的`jar`和`bootRepackage`任务: ```gradle diff --git a/VIII. Build tool plugins/64.9 Publishing artifacts to a Maven repository using Gradle.md b/VIII. Build tool plugins/64.9 Publishing artifacts to a Maven repository using Gradle.md new file mode 100644 index 00000000..503262e9 --- /dev/null +++ b/VIII. Build tool plugins/64.9 Publishing artifacts to a Maven repository using Gradle.md @@ -0,0 +1,3 @@ +### 64.9 使用Gradle将artifacts发布到Maven仓库 + +如果声明依赖但没有指定版本,且想要将artifacts发布到一个Maven仓库,那你需要使用详细的Spring Boot依赖管理来配置Maven发布。通过配置它发布继承自`spring-boot-starter-parent`的poms或引入来自`spring-boot-dependencies`的依赖管理可以实现该需求。这种配置的具体细节取决于你如何使用Gradle及如何发布该artifacts。 diff --git a/VIII. Build tool plugins/59.10.1. Configuring Gradle to produce a pom that inherits dependency management.md b/VIII. Build tool plugins/64.9.1 Configuring Gradle to produce a pom that inherits dependency management.md similarity index 58% rename from VIII. Build tool plugins/59.10.1. Configuring Gradle to produce a pom that inherits dependency management.md rename to VIII. Build tool plugins/64.9.1 Configuring Gradle to produce a pom that inherits dependency management.md index 9ed918c5..a8338293 100644 --- a/VIII. Build tool plugins/59.10.1. Configuring Gradle to produce a pom that inherits dependency management.md +++ b/VIII. Build tool plugins/64.9.1 Configuring Gradle to produce a pom that inherits dependency management.md @@ -1,6 +1,6 @@ -### 59.10.1. 自定义Gradle,用于产生一个继承依赖管理的pom +### 64.9.1 自定义Gradle,用于产生一个继承依赖管理的pom -下面示例展示了如何配置Gradle去产生一个继承自`spring-boot-starter-parent`的pom。请参考[Gradle用户指南](http://gradle.org/docs/current/userguide/userguide.html)获取更多信息。 +下面示例展示了如何配置Gradle去产生一个继承自`spring-boot-starter-parent`的pom,更多信息请参考[Gradle用户指南](http://gradle.org/docs/current/userguide/userguide.html)。 ```gradle uploadArchives { repositories { @@ -10,7 +10,7 @@ uploadArchives { parent { groupId "org.springframework.boot" artifactId "spring-boot-starter-parent" - version "1.3.0.BUILD-SNAPSHOT" + version "1.4.1.RELEASE" } } } diff --git a/VIII. Build tool plugins/59.10.2. Configuring Gradle to produce a pom that imports dependency management.md b/VIII. Build tool plugins/64.9.2 Configuring Gradle to produce a pom that imports dependency management.md similarity index 60% rename from VIII. Build tool plugins/59.10.2. Configuring Gradle to produce a pom that imports dependency management.md rename to VIII. Build tool plugins/64.9.2 Configuring Gradle to produce a pom that imports dependency management.md index fea97647..014d3f07 100644 --- a/VIII. Build tool plugins/59.10.2. Configuring Gradle to produce a pom that imports dependency management.md +++ b/VIII. Build tool plugins/64.9.2 Configuring Gradle to produce a pom that imports dependency management.md @@ -1,6 +1,6 @@ -### 59.10.2. 自定义Gradle,用于产生一个导入依赖管理的pom +### 64.9.2 自定义Gradle,用于产生一个导入依赖管理的pom -以下示例展示了如何配置Gradle去产生一个导入`spring-boot-dependencies`提供的依赖管理的pom。请参考[Gradle用户指南](http://gradle.org/docs/current/userguide/userguide.html)获取更多信息。 +以下示例展示了如何配置Gradle产生一个导入`spring-boot-dependencies`提供的依赖管理的pom,更多信息请参考[Gradle用户指南](http://gradle.org/docs/current/userguide/userguide.html)。 ```gradle uploadArchives { repositories { @@ -12,7 +12,7 @@ uploadArchives { dependency { groupId "org.springframework.boot" artifactId "spring-boot-dependencies" - version "1.3.0.BUILD-SNAPSHOT" + version "1.4.1.RELEASE" type "pom" scope "import" } diff --git a/VIII. Build tool plugins/65. Spring Boot AntLib module.md b/VIII. Build tool plugins/65. Spring Boot AntLib module.md new file mode 100644 index 00000000..b768c9a4 --- /dev/null +++ b/VIII. Build tool plugins/65. Spring Boot AntLib module.md @@ -0,0 +1,16 @@ +###65. 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` +](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#using-boot-ant)。 diff --git a/VIII. Build tool plugins/65.1. Spring Boot Ant tasks.md b/VIII. Build tool plugins/65.1. Spring Boot Ant tasks.md new file mode 100644 index 00000000..5164e508 --- /dev/null +++ b/VIII. Build tool plugins/65.1. Spring Boot Ant tasks.md @@ -0,0 +1,2 @@ +###65.1. Spring Boot Ant任务 +一旦声明`spring-boot-antlib`命名空间,以下任务就可用了。 diff --git a/VIII. Build tool plugins/65.1.1. spring-boot:exejar.md b/VIII. Build tool plugins/65.1.1. spring-boot:exejar.md new file mode 100644 index 00000000..2a0317aa --- /dev/null +++ b/VIII. Build tool plugins/65.1.1. spring-boot:exejar.md @@ -0,0 +1,16 @@ +###65.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/65.1.2. Examples.md b/VIII. Build tool plugins/65.1.2. Examples.md new file mode 100644 index 00000000..4fb56473 --- /dev/null +++ b/VIII. Build tool plugins/65.1.2. Examples.md @@ -0,0 +1,23 @@ +### 65.1.2. 示例 + +**指定start-class** +```xml + + + + + + + + +``` + +**探测start-class** +```xml + + + + + +``` diff --git a/VIII. Build tool plugins/65.2. spring-boot:findmainclass.md b/VIII. Build tool plugins/65.2. spring-boot:findmainclass.md new file mode 100644 index 00000000..d22d3dff --- /dev/null +++ b/VIII. Build tool plugins/65.2. spring-boot:findmainclass.md @@ -0,0 +1,9 @@ +###65.2. spring-boot:findmainclass + +`findmainclass`任务是`exejar`内部用于定位声明`main`方法类的,如果构建需要,你可以直接使用该任务,支持属性如下: + +|属性|描述|是否必需| +|:-----|:-----|:------| +|`classesroot`|Java类文件的根目录|是(除非指定`mainclass`)| +|`mainclass`|可用于缩减`main`类的查找|否| +|`property`|Ant属性必须使用result设值|否(没有指定则result会记录日志中)| diff --git a/VIII. Build tool plugins/65.2.1. Examples.md b/VIII. Build tool plugins/65.2.1. Examples.md new file mode 100644 index 00000000..3b2ebc49 --- /dev/null +++ b/VIII. Build tool plugins/65.2.1. Examples.md @@ -0,0 +1,14 @@ +###65.2.1. 示例 +**查找并记录** +```xml + +``` +**查找并设置** +```xml + +``` + +**覆盖并设置** +```xml + +``` diff --git a/VIII. Build tool plugins/60. Supporting other build systems.md b/VIII. Build tool plugins/66. Supporting other build systems.md similarity index 63% rename from VIII. Build tool plugins/60. Supporting other build systems.md rename to VIII. Build tool plugins/66. Supporting other build systems.md index 748b9c32..b8dfb1a9 100644 --- a/VIII. Build tool plugins/60. Supporting other build systems.md +++ b/VIII. Build tool plugins/66. Supporting other build systems.md @@ -1,5 +1,5 @@ -### 60. 对其他构建系统的支持 +### 66. 对其他构建系统的支持 如果想使用除了Maven和Gradle之外的构建工具,你可能需要开发自己的插件。可执行jars需要遵循一个特定格式,并且一些实体需要以不压缩的方式写入(详情查看附录中的[可执行jar格式](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#executable-jar)章节)。 -Spring Boot Maven和Gradle插件都利用`spring-boot-loader-tools`来实际地产生jars。如果需要,你也可以自由地直接使用该库。 +Spring Boot Maven和Gradle插件在实际生成jars的过程中会使用`spring-boot-loader-tools`,如果需要,你也可以自由地使用该library。 diff --git a/VIII. Build tool plugins/66.1. Repackaging archives.md b/VIII. Build tool plugins/66.1. Repackaging archives.md new file mode 100644 index 00000000..577735d0 --- /dev/null +++ b/VIII. Build tool plugins/66.1. Repackaging archives.md @@ -0,0 +1,3 @@ +### 66.1. 重新打包存档 + +使用`org.springframework.boot.loader.tools.Repackager`可以将一个存在的存档重新打包,这样它就变成一个自包含的可执行存档。`Repackager`类需要提供单一的构造器参数,该参数指向一个存在的jar或war包。你可以使用两个可用的`repackage()`方法中的一个来替换原始的文件或写入新的目标,在repackager运行前还可以指定各种配置。 diff --git a/VIII. Build tool plugins/66.2.Nested libraries.md b/VIII. Build tool plugins/66.2.Nested libraries.md new file mode 100644 index 00000000..b52beeb3 --- /dev/null +++ b/VIII. Build tool plugins/66.2.Nested libraries.md @@ -0,0 +1,5 @@ +### 66.2. 内嵌库 + +当重新打包一个存档时,你可以使用`org.springframework.boot.loader.tools.Libraries`接口来包含对依赖文件的引用。在这里我们不提供任何该`Libraries`接口的具体实现,因为它们通常跟具体的构建系统相关。 + +如果存档已经包含libraries,你可以使用`Libraries.NONE`。 diff --git a/VIII. Build tool plugins/60.3. Finding a main class.md b/VIII. Build tool plugins/66.3. Finding a main class.md similarity index 91% rename from VIII. Build tool plugins/60.3. Finding a main class.md rename to VIII. Build tool plugins/66.3. Finding a main class.md index db6f3eb4..3dbc734e 100644 --- a/VIII. Build tool plugins/60.3. Finding a main class.md +++ b/VIII. Build tool plugins/66.3. Finding a main class.md @@ -1,3 +1,3 @@ -### 60.3. 查找main类 +### 66.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/60.4. Example repackage implementation.md b/VIII. Build tool plugins/66.4. Example repackage implementation.md similarity index 83% rename from VIII. Build tool plugins/60.4. Example repackage implementation.md rename to VIII. Build tool plugins/66.4. Example repackage implementation.md index dd163b20..732c9c32 100644 --- a/VIII. Build tool plugins/60.4. Example repackage implementation.md +++ b/VIII. Build tool plugins/66.4. Example repackage implementation.md @@ -1,6 +1,6 @@ -### 60.4. repackage实现示例 +### 66.4. repackage实现示例 -这里是一个传统的repackage示例: +这是一个典型的repackage示例: ```java Repackager repackager = new Repackager(sourceJarFile); repackager.setBackupSource(false); diff --git a/VIII. Build tool plugins/67. What to read next.md b/VIII. Build tool plugins/67. What to read next.md new file mode 100644 index 00000000..c19f66c3 --- /dev/null +++ b/VIII. Build tool plugins/67. What to read next.md @@ -0,0 +1,5 @@ +### 67. 接下来阅读什么 + +如果对构建工具插件如何工作感兴趣,你可以查看GitHub上的[spring-boot-tools](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-tools)模块,附加中有详细的[可执行jar格式](https://github.com/spring-projects/spring-boot/tree/v1.4.1.RELEASE/spring-boot-tools)。 + +如果有特定构建相关的问题,可以查看[how-to](../IX. ‘How-to’ guides/README.md)指南。 diff --git a/VIII. Build tool plugins/README.md b/VIII. Build tool plugins/README.md index d71f062b..a726c8bf 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”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot)章节的[“Chapter 13, Build systems”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-build-systems)。 +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)。 diff --git a/X. Appendices/A. Common application properties.md b/X. Appendices/A. Common application properties.md index 551aef12..16986aa0 100644 --- a/X. Appendices/A. Common application properties.md +++ b/X. Appendices/A. Common application properties.md @@ -2,9 +2,9 @@ 你可以在`application.properties/application.yml`文件内部或通过命令行开关来指定各种属性。本章节提供了一个常见Spring Boot属性的列表及使用这些属性的底层类的引用。 -**注**:属性可以来自classpath下的其他jar文件中,所以你不应该把它当成详尽的列表。定义你自己的属性也是相当合法的。 +**注** 属性可以来自classpath下的其他jar文件中,所以你不应该把它当成详尽的列表。定义你自己的属性也是相当合法的。 -**注**:示例文件只是一个指导。不要拷贝/粘贴整个内容到你的应用,而是只提取你需要的属性。 +**注** 示例文件只是一个指导。不要拷贝/粘贴整个内容到你的应用,而是只提取你需要的属性。 ```properties # =================================================================== @@ -14,582 +14,1112 @@ # entirety to your own application. ^^^ # =================================================================== + # ---------------------------------------- # CORE PROPERTIES # ---------------------------------------- -# SPRING CONFIG (ConfigFileApplicationListener) -spring.config.name= # config file name (default to 'application') -spring.config.location= # location of config file +# 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) -# PROFILES -spring.profiles.active= # comma list of active profiles -spring.profiles.include= # unconditionally activate the specified comma separated profiles +# LOGGING +logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback +logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions. +logging.file= # Log file name. For instance `myapp.log` +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.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=false # 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.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. + +# SPRING CORE +spring.beaninfo.ignore=true # 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.ehcache.config= # The location of the configuration file to use to initialize EhCache. +spring.cache.guava.spec= # The spec to use to create caches. Check CacheBuilderSpec for more details on the spec format. +spring.cache.hazelcast.config= # The location of the configuration file to use to initialize Hazelcast. +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 CONFIG - using environment property only (ConfigFileApplicationListener) +spring.config.location= # Config file locations. +spring.config.name=application # Config file name. + +# HAZELCAST (HazelcastProperties) +spring.hazelcast.config= # The location of the configuration file to use to initialize Hazelcast. + +# PROJECT INFORMATION (ProjectInfoProperties) +spring.info.build.location=classpath:META-INF/build-info.properties # Location of the generated build-info.properties file. +spring.info.git.location=classpath:git.properties # Location of the generated git.properties file. + +# JMX +spring.jmx.default-domain= # JMX domain name. +spring.jmx.enabled=true # Expose management beans to the JMX domain. +spring.jmx.server=mbeanServer # MBeanServer bean name. + +# 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.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.username= # Login user of the SMTP server. # APPLICATION SETTINGS (SpringApplication) -spring.main.sources= -spring.main.web-environment= # detect by default -spring.main.show-banner=true -spring.main....= # see class for all properties +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-environment= # Run the application in a web environment (auto-detected by default). -# LOGGING -logging.path=/var/logs -logging.file=myapp.log -logging.config= # location of config file (default classpath:logback.xml for logback) -logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF) +# FILE ENCODING (FileEncodingApplicationListener) +spring.mandatory-file-encoding= # Expected character encoding the application must use. -# IDENTITY (ContextIdApplicationContextInitializer) -spring.application.name= -spring.application.index= +# 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. +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. + +# OUTPUT +spring.output.ansi.enabled=detect # Configure 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.file= # Location of the PID file to write (if ApplicationPidFileWriter is used). + +# PROFILES +spring.profiles.active= # Comma-separated list of active profiles. +spring.profiles.include= # Unconditionally activate the specified comma separated profiles. + +# SENDGRID (SendGridAutoConfiguration) +spring.sendgrid.api-key= # SendGrid api key (alternative to username/password) +spring.sendgrid.username= # SendGrid account username +spring.sendgrid.password= # SendGrid account password +spring.sendgrid.proxy.host= # SendGrid proxy host +spring.sendgrid.proxy.port= # SendGrid proxy port + + +# ---------------------------------------- +# WEB PROPERTIES +# ---------------------------------------- # EMBEDDED SERVER CONFIGURATION (ServerProperties) -server.port=8080 -server.address= # bind to a specific NIC -server.session-timeout= # session timeout in seconds -server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha -server.context-path= # the context path, defaults to '/' -server.servlet-path= # the servlet path, defaults to '/' -server.ssl.enabled=true # if SSL support is enabled -server.ssl.client-auth= # want or need -server.ssl.key-alias= -server.ssl.ciphers= # supported SSL ciphers -server.ssl.key-password= -server.ssl.key-store= -server.ssl.key-store-password= -server.ssl.key-store-provider= -server.ssl.key-store-type= -server.ssl.protocol=TLS -server.ssl.trust-store= -server.ssl.trust-store-password= -server.ssl.trust-store-provider= -server.ssl.trust-store-type= -server.tomcat.access-log-pattern= # log pattern of the access log -server.tomcat.access-log-enabled=false # is access logging enabled -server.tomcat.compression=off # is compression enabled (off, on, or an integer content length limit) -server.tomcat.compressable-mime-types=text/html,text/xml,text/plain # comma-separated list of mime types that Tomcat will compress +server.address= # Network address to which the server should bind to. +server.compression.enabled=false # If 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.context-parameters.*= # Servlet context init parameters. For instance `server.context-parameters.a=alpha` +server.context-path= # Context path of the application. +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.max-http-post-size=0 # Maximum size in bytes of the HTTP post content. +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.jetty.acceptors= # Number of acceptor threads to use. +server.jetty.selectors= # Number of selector threads to use. +server.jsp-servlet.class-name=org.apache.jasper.servlet.JspServlet # The class name of the JSP servlet. +server.jsp-servlet.init-parameters.*= # Init parameters used to configure the JSP servlet +server.jsp-servlet.registered=true # Whether or not the JSP servlet is registered +server.port=8080 # Server HTTP port. +server.server-header= # Value to use for the Server response header (no header is sent if empty) +server.servlet-path=/ # Path of the main dispatcher servlet. +server.use-forward-headers= # If X-Forwarded-* headers should be applied to the HttpRequest. +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.ssl.ciphers= # Supported SSL ciphers. +server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. +server.ssl.enabled= # Enable SSL support. +server.ssl.enabled-protocols= # Enabled SSL protocols. +server.ssl.key-alias= # Alias that identifies the key in the key store. +server.ssl.key-password= # Password used to access the key in the key store. +server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file). +server.ssl.key-store-password= # Password used to access the key store. +server.ssl.key-store-provider= # Provider for the key store. +server.ssl.key-store-type= # Type of the key store. +server.ssl.protocol=TLS # SSL protocol to use. +server.ssl.trust-store= # Trust store that holds SSL certificates. +server.ssl.trust-store-password= # Password used to access the trust store. +server.ssl.trust-store-provider= # Provider for the trust store. +server.ssl.trust-store-type= # Type of the trust store. +server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be relative to the tomcat base dir or absolute. +server.tomcat.accesslog.enabled=false # Enable access log. +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.suffix=.log # Log file name suffix. +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.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} # regular expression matching trusted IP addresses -server.tomcat.protocol-header=x-forwarded-proto # front end proxy forward header -server.tomcat.port-header= # front end proxy port header -server.tomcat.remote-ip-header=x-forwarded-for -server.tomcat.basedir=/tmp # base dir (usually not needed, defaults to tmp) -server.tomcat.background-processor-delay=30; # in seconds -server.tomcat.max-http-header-size= # maximum size in bytes of the HTTP message header -server.tomcat.max-threads = 0 # number of threads in protocol handler -server.tomcat.uri-encoding = UTF-8 # character encoding to use for URL decoding - -# SPRING MVC (WebMvcProperties) -spring.mvc.locale= # set fixed locale, e.g. en_UK -spring.mvc.date-format= # set fixed date format, e.g. dd/MM/yyyy -spring.mvc.favicon.enabled=true -spring.mvc.message-codes-resolver-format= # PREFIX_ERROR_CODE / POSTFIX_ERROR_CODE -spring.mvc.ignore-default-model-on-redirect=true # If the the content of the "default" model should be ignored redirects -spring.view.prefix= # MVC view prefix -spring.view.suffix= # ... and suffix + 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-threads=0 # Maximum amount of worker threads. +server.tomcat.min-spare-threads=0 # Minimum amount of worker threads. +server.tomcat.port-header=X-Forwarded-Port # Name of the HTTP header used to override the original port value. +server.tomcat.protocol-header= # Header that holds the incoming protocol, usually named "X-Forwarded-Proto". +server.tomcat.protocol-header-https-value=https # Value of the protocol header that indicates that 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.uri-encoding=UTF-8 # Character encoding to use to decode the URI. +server.undertow.accesslog.dir= # Undertow access log directory. +server.undertow.accesslog.enabled=false # Enable 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.suffix=log # Log file name suffix. +server.undertow.buffer-size= # Size of each buffer in bytes. +server.undertow.buffers-per-region= # Number of buffer per region. +server.undertow.direct-buffers= # Allocate buffers outside the Java heap. +server.undertow.io-threads= # Number of I/O threads to create for the worker. +server.undertow.worker-threads= # Number of worker threads. -# SPRING RESOURCES HANDLING (ResourceProperties) -spring.resources.cache-period= # cache timeouts in headers sent to browser -spring.resources.add-mappings=true # if default mappings should be added +# 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. +spring.freemarker.charset=UTF-8 # Template encoding. +spring.freemarker.check-template-location=true # 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.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.template-loader-path=classpath:/templates/ # Comma-separated list of template paths. +spring.freemarker.view-names= # White list of view names that can be resolved. -# MULTIPART (MultipartProperties) -multipart.enabled=true -multipart.file-size-threshold=0 # Threshold after which files will be written to disk. -multipart.location= # Intermediate location of uploaded files. -multipart.max-file-size=1Mb # Max file size. -multipart.max-request-size=10Mb # Max request size. +# 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. +spring.groovy.template.charset=UTF-8 # Template encoding. +spring.groovy.template.check-template-location=true # 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.prefix= # Prefix that gets prepended to view names when building a URL. +spring.groovy.template.request-context-attribute= # Name of the RequestContext attribute for all views. +spring.groovy.template.resource-loader-path=classpath:/templates/ # Template path. +spring.groovy.template.suffix=.tpl # Suffix that gets appended to view names when building a URL. +spring.groovy.template.view-names= # White list of view names that can be resolved. # SPRING HATEOAS (HateoasProperties) -spring.hateoas.apply-to-primary-object-mapper=true # if the primary mapper should also be configured +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. + +# 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. # HTTP encoding (HttpEncodingProperties) -spring.http.encoding.charset=UTF-8 # the encoding of HTTP requests/responses -spring.http.encoding.enabled=true # enable http encoding support -spring.http.encoding.force=true # force the configured encoding +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. -# HTTP message conversion -spring.http.converters.preferred-json-mapper= # the 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. - -# HTTP response compression (GzipFilterProperties) -spring.http.gzip.buffer-size= # size of the output buffer in bytes -spring.http.gzip.deflate-compression-level= # the level used for deflate compression (0-9) -spring.http.gzip.deflate-no-wrap= # noWrap setting for deflate compression (true or false) -spring.http.gzip.enabled=true # enable gzip filter support -spring.http.gzip.excluded-agents= # comma-separated list of user agents to exclude from compression -spring.http.gzip.excluded-agent-patterns= # comma-separated list of regular expression patterns to control user agents excluded from compression -spring.http.gzip.excluded-paths= # comma-separated list of paths to exclude from compression -spring.http.gzip.excluded-path-patterns= # comma-separated list of regular expression patterns to control the paths that are excluded from compression -spring.http.gzip.methods= # comma-separated list of HTTP methods for which compression is enabled -spring.http.gzip.mime-types= # comma-separated list of MIME types which should be compressed -spring.http.gzip.min-gzip-size= # minimum content length required for compression to occur -spring.http.gzip.vary= # Vary header to be sent on responses that may be compressed +# MULTIPART (MultipartProperties) +spring.http.multipart.enabled=true # Enable support of multi-part uploads. +spring.http.multipart.file-size-threshold=0 # Threshold after which files will be written to disk. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. +spring.http.multipart.location= # Intermediate location of uploaded files. +spring.http.multipart.max-file-size=1Mb # Max file size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. +spring.http.multipart.max-request-size=10Mb # Max request size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. +spring.http.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 (e.g. yyyy-MM-dd HH:mm:ss), or a fully-qualified date format class name (e.g. com.fasterxml.jackson.databind.util.ISO8601DateFormat) -spring.jackson.property-naming-strategy= # One of the constants on Jackson's PropertyNamingStrategy (e.g. CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) or the fully-qualified class name of a PropertyNamingStrategy subclass -spring.jackson.deserialization.*= # see Jackson's DeserializationFeature -spring.jackson.generator.*= # see Jackson's JsonGenerator.Feature -spring.jackson.mapper.*= # see Jackson's MapperFeature -spring.jackson.parser.*= # see Jackson's JsonParser.Feature -spring.jackson.serialization.*= # see Jackson's SerializationFeature -spring.jackson.serialization-inclusion= # Controls the inclusion of properties during serialization (see Jackson's JsonInclude.Include) +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.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.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.serialization-inclusion= # Controls the inclusion of properties during serialization. Configured with one of the values in Jackson's JsonInclude.Include enumeration. +spring.jackson.time-zone= # Time zone used when formatting dates. For instance `America/Los_Angeles` -# THYMELEAF (ThymeleafAutoConfiguration) -spring.thymeleaf.check-template-location=true -spring.thymeleaf.prefix=classpath:/templates/ -spring.thymeleaf.excluded-view-names= # comma-separated list of view names that should be excluded from resolution -spring.thymeleaf.view-names= # comma-separated list of view names that can be resolved -spring.thymeleaf.suffix=.html -spring.thymeleaf.mode=HTML5 -spring.thymeleaf.encoding=UTF-8 -spring.thymeleaf.content-type=text/html # ;charset= is added -spring.thymeleaf.cache=true # set to false for hot refresh - -# FREEMARKER (FreeMarkerAutoConfiguration) -spring.freemarker.allow-request-override=false -spring.freemarker.cache=true -spring.freemarker.check-template-location=true -spring.freemarker.charset=UTF-8 -spring.freemarker.content-type=text/html -spring.freemarker.expose-request-attributes=false -spring.freemarker.expose-session-attributes=false -spring.freemarker.expose-spring-macro-helpers=false -spring.freemarker.prefix= -spring.freemarker.request-context-attribute= -spring.freemarker.settings.*= -spring.freemarker.suffix=.ftl -spring.freemarker.template-loader-path=classpath:/templates/ # comma-separated list -spring.freemarker.view-names= # whitelist of view names that can be resolved +# 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.filter.order=0 # Jersey filter chain order. +spring.jersey.init.*= # Init parameters to pass to Jersey via 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. -# GROOVY TEMPLATES (GroovyTemplateAutoConfiguration) -spring.groovy.template.cache=true -spring.groovy.template.charset=UTF-8 -spring.groovy.template.configuration.*= # See Groovy's TemplateConfiguration -spring.groovy.template.content-type=text/html -spring.groovy.template.prefix=classpath:/templates/ -spring.groovy.template.suffix=.tpl -spring.groovy.template.view-names= # whitelist of view names that can be resolved +# 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. -# VELOCITY TEMPLATES (VelocityAutoConfiguration) -spring.velocity.allow-request-override=false -spring.velocity.cache=true -spring.velocity.check-template-location=true -spring.velocity.charset=UTF-8 -spring.velocity.content-type=text/html -spring.velocity.date-tool-attribute= -spring.velocity.expose-request-attributes=false -spring.velocity.expose-session-attributes=false -spring.velocity.expose-spring-macro-helpers=false -spring.velocity.number-tool-attribute= -spring.velocity.prefer-file-system-access=true # prefer file system access for template loading -spring.velocity.prefix= -spring.velocity.properties.*= -spring.velocity.request-context-attribute= -spring.velocity.resource-loader-path=classpath:/templates/ -spring.velocity.suffix=.vm -spring.velocity.toolbox-config-location= # velocity Toolbox config location, for example "/WEB-INF/toolbox.xml" -spring.velocity.view-names= # whitelist of view names that can be resolved +# 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.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=.html # Suffix to apply to template names. +spring.mustache.view-names= # White list of view names that can be resolved. -# JERSEY (JerseyProperties) -spring.jersey.type=servlet # servlet or filter -spring.jersey.init= # init params -spring.jersey.filter.order= +# 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.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.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.view.prefix= # Spring MVC view prefix. +spring.mvc.view.suffix= # Spring MVC view suffix. -# INTERNATIONALIZATION (MessageSourceAutoConfiguration) -spring.messages.basename=messages -spring.messages.cache-seconds=-1 -spring.messages.encoding=UTF-8 +# 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.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ # Locations of static resources. + +# SPRING SESSION (SessionProperties) +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.mongo.collection-name=sessions # Collection name used to store sessions. +spring.session.redis.flush-mode= # Flush mode for the Redis sessions. +spring.session.redis.namespace= # Namespace for keys used to store sessions. +spring.session.store-type= # Session store type. +# SPRING SOCIAL (SocialWebAutoConfiguration) +spring.social.auto-connection-views=false # Enable the connection status view for supported providers. -# SECURITY (SecurityProperties) -security.user.name=user # login username -security.user.password= # login password -security.user.role=USER # role assigned to the user -security.require-ssl=false # advanced settings ... -security.enable-csrf=false -security.basic.enabled=true -security.basic.realm=Spring -security.basic.path= # /** -security.basic.authorize-mode= # ROLE, AUTHENTICATED, NONE -security.filter-order=0 -security.headers.xss=false -security.headers.cache=false -security.headers.frame=false -security.headers.content-type=false -security.headers.hsts=all # none / domain / all -security.sessions=stateless # always / never / if_required / stateless -security.ignored= # Comma-separated list of paths to exclude from the default secured paths +# 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 -# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) -spring.datasource.name= # name of the data source -spring.datasource.initialize=true # populate using data.sql -spring.datasource.schema= # a schema (DDL) script resource reference -spring.datasource.data= # a data (DML) script resource reference -spring.datasource.sql-script-encoding= # a charset for reading SQL scripts -spring.datasource.platform= # the platform to use in the schema resource (schema-${platform}.sql) -spring.datasource.continue-on-error=false # continue even if can't be initialized -spring.datasource.separator=; # statement separator in SQL initialization scripts -spring.datasource.driver-class-name= # JDBC Settings... -spring.datasource.url= -spring.datasource.username= -spring.datasource.password= -spring.datasource.jndi-name= # For JNDI lookup (class, url, username & password are ignored when set) -spring.datasource.max-active=100 # Advanced configuration... -spring.datasource.max-idle=8 -spring.datasource.min-idle=8 -spring.datasource.initial-size=10 -spring.datasource.validation-query= -spring.datasource.test-on-borrow=false -spring.datasource.test-on-return=false -spring.datasource.test-while-idle= -spring.datasource.time-between-eviction-runs-millis= -spring.datasource.min-evictable-idle-time-millis= -spring.datasource.max-wait= -spring.datasource.jmx-enabled=false # Export JMX MBeans (if supported) +# 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 -# DAO (PersistenceExceptionTranslationAutoConfiguration) -spring.dao.exceptiontranslation.enabled=true +# 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 -# MONGODB (MongoProperties) -spring.data.mongodb.host= # the db host -spring.data.mongodb.port=27017 # the connection port (defaults to 27107) -spring.data.mongodb.uri=mongodb://localhost/test # connection URL -spring.data.mongodb.database= -spring.data.mongodb.authentication-database= -spring.data.mongodb.grid-fs-database= -spring.data.mongodb.username= -spring.data.mongodb.password= -spring.data.mongodb.repositories.enabled=true # if spring data repository support is enabled +# 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.content-type=text/html # Content-Type value. +spring.thymeleaf.enabled=true # Enable MVC Thymeleaf view resolution. +spring.thymeleaf.encoding=UTF-8 # Template 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.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL. +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. -# JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) -spring.jpa.properties.*= # properties to set on the JPA connection -spring.jpa.open-in-view=true -spring.jpa.show-sql=true -spring.jpa.database-platform= -spring.jpa.database= -spring.jpa.generate-ddl=false # ignored by Hibernate, might be useful for other vendors -spring.jpa.hibernate.naming-strategy= # naming classname -spring.jpa.hibernate.ddl-auto= # defaults to create-drop for embedded dbs -spring.data.jpa.repositories.enabled=true # if spring data repository support is enabled +# VELOCITY TEMPLATES (VelocityAutoConfiguration) +spring.velocity.allow-request-override=false # Set whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.velocity.allow-session-override=false # Set whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. +spring.velocity.cache= # Enable template caching. +spring.velocity.charset=UTF-8 # Template encoding. +spring.velocity.check-template-location=true # Check that the templates location exists. +spring.velocity.content-type=text/html # Content-Type value. +spring.velocity.date-tool-attribute= # Name of the DateTool helper object to expose in the Velocity context of the view. +spring.velocity.enabled=true # Enable MVC view resolution for this technology. +spring.velocity.expose-request-attributes=false # Set whether all request attributes should be added to the model prior to merging with the template. +spring.velocity.expose-session-attributes=false # Set whether all HttpSession attributes should be added to the model prior to merging with the template. +spring.velocity.expose-spring-macro-helpers=true # Set whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext". +spring.velocity.number-tool-attribute= # Name of the NumberTool helper object to expose in the Velocity context of the view. +spring.velocity.prefer-file-system-access=true # Prefer file system access for template loading. File system access enables hot detection of template changes. +spring.velocity.prefix= # Prefix that gets prepended to view names when building a URL. +spring.velocity.properties.*= # Additional velocity properties. +spring.velocity.request-context-attribute= # Name of the RequestContext attribute for all views. +spring.velocity.resource-loader-path=classpath:/templates/ # Template path. +spring.velocity.suffix=.vm # Suffix that gets appended to view names when building a URL. +spring.velocity.toolbox-config-location= # Velocity Toolbox config location. For instance `/WEB-INF/toolbox.xml` +spring.velocity.view-names= # White list of view names that can be resolved. + +# 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. -# JTA (JtaAutoConfiguration) -spring.jta.log-dir= # transaction log dir -spring.jta.*= # technology specific configuration - -# ATOMIKOS -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.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread -spring.jta.atomikos.connectionfactory.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool -spring.jta.atomikos.connectionfactory.max-lifetime=0 # The time, in seconds, that a connection can be pooled for before being destroyed. 0 denotes no limit. -spring.jta.atomikos.connectionfactory.max-pool-size=1 # The maximum size of the pool -spring.jta.atomikos.connectionfactory.min-pool-size=1 # The minimum size of the pool -spring.jta.atomikos.connectionfactory.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. -spring.jta.atomikos.connectionfactory.unique-resource-name=jmsConnectionFactory # The unique name used to identify the resource during recovery -spring.jta.atomikos.datasource.borrow-connection-timeout=30 # Timeout, in seconds, for borrowing connections from the pool -spring.jta.atomikos.datasource.default-isolation-level= # Default isolation level of connections provided by the pool -spring.jta.atomikos.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection -spring.jta.atomikos.datasource.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread -spring.jta.atomikos.datasource.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool -spring.jta.atomikos.datasource.max-lifetime=0 # The time, in seconds, that a connection can be pooled for before being destroyed. 0 denotes no limit. -spring.jta.atomikos.datasource.max-pool-size=1 # The maximum size of the pool -spring.jta.atomikos.datasource.min-pool-size=1 # The minimum size of the pool -spring.jta.atomikos.datasource.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. -spring.jta.atomikos.datasource.test-query= # SQL query or statement used to validate a connection before returning it -spring.jta.atomikos.datasource.unique-resource-name=dataSource # The unique name used to identify the resource during recovery -# 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.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.two-pc-ordering-position=1 # The postion 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.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.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.isolation-level= # The default isolation level for connections -spring.jta.bitronix.datasource.local-auto-commit # The default auto-commit mode for local transactions -spring.jta.bitronix.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection -spring.jta.bitronix.datasource.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool -spring.jta.bitronix.datasource.max-pool-size=10 # The maximum size of the pool. 0 denotes no limit -spring.jta.bitronix.datasource.min-pool-size=0 # The minimum size of the pool -spring.jta.bitronix.datasource.prepared-statement-cache-size=0 # The target size of the prepared statement cache. 0 disables the cache -spring.jta.bitronix.datasource.share-transaction-connections=false # Whether or not 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.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 -# SOLR (SolrProperties) -spring.data.solr.host=http://127.0.0.1:8983/solr -spring.data.solr.zk-host= -spring.data.solr.repositories.enabled=true # if spring data repository support is enabled +# ---------------------------------------- +# 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-type=true # Enable "X-Content-Type-Options" header. +security.headers.frame=true # Enable "X-Frame-Options" header. +security.headers.hsts= # 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. + +# 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.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 -# ELASTICSEARCH (ElasticsearchProperties) -spring.data.elasticsearch.cluster-name= # The cluster name (defaults to elasticsearch) -spring.data.elasticsearch.cluster-nodes= # The address(es) of the server node (comma-separated; if not specified starts a client node) -spring.data.elasticsearch.properties.*= # Additional properties used to configure the client -spring.data.elasticsearch.repositories.enabled=true # if spring data repository support is enabled -# DATA REST (RepositoryRestConfiguration) -spring.data.rest.base-uri= # base URI against which the exporter should calculate its links +# ---------------------------------------- +# DATA PROPERTIES +# ---------------------------------------- # FLYWAY (FlywayProperties) -flyway.*= # Any public property available on the auto-configured `Flyway` object -flyway.check-location=false # check that migration scripts location exists +flyway.baseline-description= # +flyway.baseline-version=1 # version to start migration +flyway.baseline-on-migrate= # +flyway.check-location=false # Check that migration scripts location exists. +flyway.clean-on-validation-error= # +flyway.enabled=true # Enable flyway. +flyway.encoding= # +flyway.ignore-failed-future-migration= # +flyway.init-sqls= # SQL statements to execute to initialize a connection immediately after obtaining it. flyway.locations=classpath:db/migration # locations of migrations scripts -flyway.schemas= # schemas to update -flyway.init-version= 1 # version to start migration -flyway.init-sqls= # SQL statements to execute to initialize a connection immediately after obtaining it -flyway.sql-migration-prefix=V -flyway.sql-migration-suffix=.sql -flyway.enabled=true -flyway.url= # JDBC url if you want Flyway to create its own DataSource -flyway.user= # JDBC username if you want Flyway to create its own DataSource +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.schemas= # schemas to update +flyway.sql-migration-prefix=V # +flyway.sql-migration-separator= # +flyway.sql-migration-suffix=.sql # +flyway.table= # +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= # # LIQUIBASE (LiquibaseProperties) -liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml -liquibase.check-change-log-location=true # check the change log location exists -liquibase.contexts= # runtime contexts to use -liquibase.default-schema= # default database schema to use -liquibase.drop-first=false -liquibase.enabled=true -liquibase.url= # specific JDBC url (if not set the default datasource is used) -liquibase.user= # user name for liquibase.url -liquibase.password= # password for liquibase.url +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. + +# 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.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.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. -# JMX -spring.jmx.enabled=true # Expose MBeans from Spring +# DAO (PersistenceExceptionTranslationAutoConfiguration) +spring.dao.exceptiontranslation.enabled=true # Enable the PersistenceExceptionTranslationPostProcessor. + +# CASSANDRA (CassandraProperties) +spring.data.cassandra.cluster-name= # Name of the Cassandra cluster. +spring.data.cassandra.compression= # Compression supported by the Cassandra binary protocol. +spring.data.cassandra.connect-timeout-millis= # 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.fetch-size= # Queries default fetch size. +spring.data.cassandra.keyspace-name= # Keyspace name to use. +spring.data.cassandra.load-balancing-policy= # Class name of the load balancing policy. +spring.data.cassandra.port= # Port of the Cassandra server. +spring.data.cassandra.password= # Login password of the server. +spring.data.cassandra.read-timeout-millis= # Socket option: read time out. +spring.data.cassandra.reconnection-policy= # Reconnection policy class. +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. +spring.data.cassandra.ssl=false # Enable SSL support. +spring.data.cassandra.username= # Login user of the server. + +# DATA COUCHBASE (CouchbaseDataProperties) +spring.data.couchbase.auto-index=false # Automatically create views and indexes. +spring.data.couchbase.consistency=read-your-own-writes # Consistency to apply by default on generated queries. +spring.data.couchbase.repositories.enabled=true # Enable Couchbase repositories. -# RABBIT (RabbitProperties) -spring.rabbitmq.host= # connection host -spring.rabbitmq.port= # connection port -spring.rabbitmq.addresses= # connection addresses (e.g. myhost:9999,otherhost:1111) -spring.rabbitmq.username= # login user -spring.rabbitmq.password= # login password -spring.rabbitmq.virtual-host= -spring.rabbitmq.dynamic= +# ELASTICSEARCH (ElasticsearchProperties) +spring.data.elasticsearch.cluster-name=elasticsearch # Elasticsearch cluster name. +spring.data.elasticsearch.cluster-nodes= # Comma-separated list of cluster node addresses. If not specified, starts a client node. +spring.data.elasticsearch.properties.*= # Additional properties used to configure the client. +spring.data.elasticsearch.repositories.enabled=true # Enable Elasticsearch repositories. -# REDIS (RedisProperties) -spring.redis.database= # database name -spring.redis.host=localhost # server host -spring.redis.password= # server password -spring.redis.port=6379 # connection port -spring.redis.pool.max-idle=8 # pool settings ... -spring.redis.pool.min-idle=0 -spring.redis.pool.max-active=8 -spring.redis.pool.max-wait=-1 -spring.redis.sentinel.master= # name of Redis server -spring.redis.sentinel.nodes= # comma-separated list of host:port pairs +# MONGODB (MongoProperties) +spring.data.mongodb.authentication-database= # Authentication database name. +spring.data.mongodb.database=test # 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. +spring.data.mongodb.password= # Login password of the mongo server. +spring.data.mongodb.port=27017 # Mongo server port. +spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories. +spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. When set, host and port are ignored. +spring.data.mongodb.username= # Login user of the mongo server. + +# DATA REDIS +spring.data.redis.repositories.enabled=true # Enable Redis repositories. + +# NEO4J (Neo4jProperties) +spring.data.neo4j.compiler= # Compiler to use. +spring.data.neo4j.embedded.enabled=true # Enable embedded mode if the embedded driver is available. +spring.data.neo4j.password= # Login password of the server. +spring.data.neo4j.repositories.enabled=true # Enable Neo4j repositories. +spring.data.neo4j.session.scope=singleton # Scope (lifetime) of the session. +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-page-size= # Default size of pages. +spring.data.rest.enable-enum-translation= # Enable enum value translation via 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.sort-param-name= # Name of the URL query string parameter that indicates what direction to sort results. -# ACTIVEMQ (ActiveMQProperties) -spring.activemq.broker-url=tcp://localhost:61616 # connection URL -spring.activemq.user= -spring.activemq.password= -spring.activemq.in-memory=true # broker kind to create if no broker-url is specified -spring.activemq.pooled=false - -# HornetQ (HornetQProperties) -spring.hornetq.mode= # connection mode (native, embedded) -spring.hornetq.host=localhost # hornetQ host (native mode) -spring.hornetq.port=5445 # hornetQ port (native mode) -spring.hornetq.embedded.enabled=true # if the embedded server is enabled (needs hornetq-jms-server.jar) -spring.hornetq.embedded.server-id= # auto-generated id of the embedded server (integer) -spring.hornetq.embedded.persistent=false # message persistence -spring.hornetq.embedded.data-directory= # location of data content (when persistence is enabled) -spring.hornetq.embedded.queues= # comma-separated queues to create on startup -spring.hornetq.embedded.topics= # comma-separated topics to create on startup -spring.hornetq.embedded.cluster-password= # customer password (randomly generated by default) +# 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.zk-host= # ZooKeeper host address in the form HOST:PORT. -# JMS (JmsProperties) -spring.jms.jndi-name= # JNDI location of a JMS ConnectionFactory -spring.jms.pub-sub-domain= # false for queue (default), true for topic +# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) +spring.datasource.continue-on-error=false # Do not stop if an error occurs while initializing the database. +spring.datasource.data= # Data (DML) script resource reference. +spring.datasource.data-username= # User 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.dbcp.*= # Commons DBCP specific settings +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.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.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.password= # Login password of the database. +spring.datasource.platform=all # Platform to use in the schema resource (schema-${platform}.sql). +spring.datasource.schema= # Schema (DDL) script resource reference. +spring.datasource.schema-username= # User 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= -# Email (MailProperties) -spring.mail.host=smtp.acme.org # mail server host -spring.mail.port= # mail server port -spring.mail.username= -spring.mail.password= -spring.mail.default-encoding=UTF-8 # encoding to use for MimeMessages -spring.mail.properties.*= # properties to set on the JavaMail session - -# SPRING BATCH (BatchDatabaseInitializer) -spring.batch.job.names=job1,job2 -spring.batch.job.enabled=true -spring.batch.initializer.enabled=true -spring.batch.schema= # batch schema to load +# JEST (Elasticsearch HTTP client) (JestProperties) +spring.elasticsearch.jest.connection-timeout=3000 # Connection timeout in milliseconds. +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.uris=http://localhost:9200 # Comma-separated list of the Elasticsearch instances to use. +spring.elasticsearch.jest.username= # Login user. -# SPRING CACHE (CacheProperties) -spring.cache.type= # generic, ehcache, hazelcast, jcache, redis, guava, simple, none -spring.cache.config= # -spring.cache.cache-names= # cache names to create on startup -spring.cache.jcache.provider= # fully qualified name of the CachingProvider implementation to use -spring.cache.guava.spec= # guava specs +# 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. -# AOP -spring.aop.auto= -spring.aop.proxy-target-class= +# JOOQ (JooqAutoConfiguration) +spring.jooq.sql-dialect= # SQLDialect JOOQ used when communicating with the configured datasource. For instance `POSTGRES` -# FILE ENCODING (FileEncodingApplicationListener) -spring.mandatory-file-encoding= # Expected character encoding the application must use +# JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) +spring.data.jpa.repositories.enabled=true # 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.naming.strategy= # Hibernate 4 naming strategy fully qualified name. Not supported with Hibernate 5. +spring.jpa.hibernate.use-new-id-generator-mappings= # Use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE. +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 SOCIAL (SocialWebAutoConfiguration) -spring.social.auto-connection-views=true # Set to true for default connection views or false if you provide your own +# JTA (JtaAutoConfiguration) +spring.jta.enabled=true # 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.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread. +spring.jta.atomikos.connectionfactory.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. +spring.jta.atomikos.connectionfactory.max-lifetime=0 # The time, in seconds, that a connection can be pooled for before being destroyed. 0 denotes no limit. +spring.jta.atomikos.connectionfactory.max-pool-size=1 # The maximum size of the pool. +spring.jta.atomikos.connectionfactory.min-pool-size=1 # The minimum size of the pool. +spring.jta.atomikos.connectionfactory.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. +spring.jta.atomikos.connectionfactory.unique-resource-name=jmsConnectionFactory # The unique name used to identify the resource during recovery. +spring.jta.atomikos.datasource.borrow-connection-timeout=30 # Timeout, in seconds, for borrowing connections from the pool. +spring.jta.atomikos.datasource.default-isolation-level= # Default isolation level of connections provided by the pool. +spring.jta.atomikos.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection. +spring.jta.atomikos.datasource.maintenance-interval=60 # The time, in seconds, between runs of the pool's maintenance thread. +spring.jta.atomikos.datasource.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. +spring.jta.atomikos.datasource.max-lifetime=0 # The time, in seconds, that a connection can be pooled for before being destroyed. 0 denotes no limit. +spring.jta.atomikos.datasource.max-pool-size=1 # The maximum size of the pool. +spring.jta.atomikos.datasource.min-pool-size=1 # The minimum size of the pool. +spring.jta.atomikos.datasource.reap-timeout=0 # The reap timeout, in seconds, for borrowed connections. 0 denotes no limit. +spring.jta.atomikos.datasource.test-query= # SQL query or statement used to validate a connection before returning it. +spring.jta.atomikos.datasource.unique-resource-name=dataSource # The unique name used to identify the resource during recovery. +spring.jta.atomikos.properties.checkpoint-interval=500 # Interval between checkpoints. +spring.jta.atomikos.properties.console-file-count=1 # Number of debug logs files that can be created. +spring.jta.atomikos.properties.console-file-limit=-1 # How many bytes can be stored at most in debug logs files. +spring.jta.atomikos.properties.console-file-name=tm.out # Debug logs file name. +spring.jta.atomikos.properties.console-log-level= # Console log level. +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.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.output-dir= # Directory in which to store the debug log files. +spring.jta.atomikos.properties.serial-jta-transactions=true # Specify if 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=true # 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 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 +# 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.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.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.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.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.isolation-level= # The default isolation level for connections. +spring.jta.bitronix.datasource.local-auto-commit= # The default auto-commit mode for local transactions. +spring.jta.bitronix.datasource.login-timeout= # Timeout, in seconds, for establishing a database connection. +spring.jta.bitronix.datasource.max-idle-time=60 # The time, in seconds, after which connections are cleaned up from the pool. +spring.jta.bitronix.datasource.max-pool-size=10 # The maximum size of the pool. 0 denotes no limit. +spring.jta.bitronix.datasource.min-pool-size=0 # The minimum size of the pool. +spring.jta.bitronix.datasource.prepared-statement-cache-size=0 # The target size of the prepared statement cache. 0 disables the cache. +spring.jta.bitronix.datasource.share-transaction-connections=false # Whether or not 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.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.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.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.jndi-transaction-synchronization-registry-name= # JNDI name of the TransactionSynchronizationRegistry. +spring.jta.bitronix.properties.jndi-user-transaction-name= # JNDI name of the UserTransaction. +spring.jta.bitronix.properties.journal=disk # Name of the journal. Can be 'disk', 'null' or a class name. +spring.jta.bitronix.properties.log-part1-filename=btm1.tlog # Name of the first fragment of the journal. +spring.jta.bitronix.properties.log-part2-filename=btm2.tlog # Name of the second fragment of the journal. +spring.jta.bitronix.properties.max-log-size-in-mb=2 # Maximum size in megabytes of the journal fragments. +spring.jta.bitronix.properties.resource-configuration-filename= # ResourceLoader configuration file name. +spring.jta.bitronix.properties.server-id= # ASCII ID that must uniquely identify this TM instance. Default 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. + +# NARAYANA (NarayanaProperties) +spring.jta.narayana.default-timeout=60 # Transaction timeout in seconds. +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.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.storage.databaseDir= # Directory used for data storage. +spring.mongodb.embedded.storage.oplogSize= # Maximum size of the oplog in megabytes. +spring.mongodb.embedded.storage.replSetName= # Name of the replica set. +spring.mongodb.embedded.version=2.6.10 # Version of Mongo to use. -# 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 +# 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.host=localhost # Redis server host. +spring.redis.password= # Login password of the redis server. +spring.redis.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.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.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.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.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.timeout=0 # Connection timeout in milliseconds. -# 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 MOBILE SITE PREFERENCE (SitePreferenceAutoConfiguration) -spring.mobile.sitepreference.enabled=true # enabled by default +# ---------------------------------------- +# INTEGRATION PROPERTIES +# ---------------------------------------- + +# 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.password= # Login password of the broker. +spring.activemq.user= # Login user of the broker. +spring.activemq.packages.trust-all=false # 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.max-connections=1 # Maximum number of pooled connections. + +# 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.queues= # Comma-separated list of queues to create on startup. +spring.artemis.embedded.server-id= # Server id. By default, an auto-incremented counter is used. +spring.artemis.embedded.topics= # Comma-separated list of topics to create on startup. +spring.artemis.host=localhost # Artemis broker host. +spring.artemis.mode= # Artemis deployment mode, auto-detected by default. +spring.artemis.password= # Login password of the broker. +spring.artemis.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.job.enabled=true # Execute all Spring Batch jobs in the context on startup. +spring.batch.job.names= # Comma-separated list of job names to execute on startup (For instance `job1,job2`). By default, all Jobs found in the context are executed. +spring.batch.schema=classpath:org/springframework/batch/core/schema-@@platform@@.sql # Path to the SQL file to use to initialize the database schema. +spring.batch.table-prefix= # Table prefix for all the batch meta-data tables. + +# HORNETQ (HornetQProperties) +spring.hornetq.embedded.cluster-password= # Cluster password. Randomly generated on startup by default. +spring.hornetq.embedded.data-directory= # Journal file directory. Not necessary if persistence is turned off. +spring.hornetq.embedded.enabled=true # Enable embedded mode if the HornetQ server APIs are available. +spring.hornetq.embedded.persistent=false # Enable persistent store. +spring.hornetq.embedded.queues= # Comma-separated list of queues to create on startup. +spring.hornetq.embedded.server-id= # Server id. By default, an auto-incremented counter is used. +spring.hornetq.embedded.topics= # Comma-separated list of topics to create on startup. +spring.hornetq.host=localhost # HornetQ broker host. +spring.hornetq.mode= # HornetQ deployment mode, auto-detected by default. +spring.hornetq.password= # Login password of the broker. +spring.hornetq.port=5445 # HornetQ broker port. +spring.hornetq.user= # Login user of the broker. + +# JMS (JmsProperties) +spring.jms.jndi-name= # Connection factory JNDI name. When set, takes precedence to others connection factory auto-configurations. +spring.jms.listener.acknowledge-mode= # Acknowledge mode of the container. By default, the listener is transacted with automatic acknowledgment. +spring.jms.listener.auto-startup=true # Start the container automatically on startup. +spring.jms.listener.concurrency= # Minimum number of concurrent consumers. +spring.jms.listener.max-concurrency= # Maximum number of concurrent consumers. +spring.jms.pub-sub-domain=false # Specify if the default destination type is topic. + +# 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.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.host=localhost # RabbitMQ host. +spring.rabbitmq.listener.acknowledge-mode= # Acknowledge mode of container. +spring.rabbitmq.listener.auto-startup=true # Start the container automatically on startup. +spring.rabbitmq.listener.concurrency= # Minimum number of consumers. +spring.rabbitmq.listener.default-requeue-rejected= # Whether or not to requeue delivery failures; default `true`. +spring.rabbitmq.listener.max-concurrency= # Maximum number of consumers. +spring.rabbitmq.listener.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.retry.enabled=false # Whether or not publishing retries are enabled. +spring.rabbitmq.listener.retry.initial-interval=1000 # Interval between the first and second attempt to deliver a message. +spring.rabbitmq.listener.retry.max-attempts=3 # Maximum number of attempts to deliver a message. +spring.rabbitmq.listener.retry.max-interval=10000 # Maximum interval between attempts. +spring.rabbitmq.listener.retry.multiplier=1.0 # A multiplier to apply to the previous delivery retry interval. +spring.rabbitmq.listener.retry.stateless=true # Whether or not retry is stateless or stateful. +spring.rabbitmq.listener.transaction-size= # Number of messages to be processed in a transaction. For best results it should be less than or equal to the prefetch count. +spring.rabbitmq.password= # 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.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.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.virtual-host= # Virtual host to use when connecting to the broker. -# SPRING MOBILE DEVICE VIEWS (DeviceDelegatingViewResolverAutoConfiguration) -spring.mobile.devicedelegatingviewresolver.enabled=true # disabled by default -spring.mobile.devicedelegatingviewresolver.normal-prefix= -spring.mobile.devicedelegatingviewresolver.normal-suffix= -spring.mobile.devicedelegatingviewresolver.mobile-prefix=mobile/ -spring.mobile.devicedelegatingviewresolver.mobile-suffix= -spring.mobile.devicedelegatingviewresolver.tablet-prefix=tablet/ -spring.mobile.devicedelegatingviewresolver.tablet-suffix= # ---------------------------------------- # ACTUATOR PROPERTIES # ---------------------------------------- -# MANAGEMENT HTTP SERVER (ManagementServerProperties) -management.port= # defaults to 'server.port' -management.address= # bind to a specific NIC -management.context-path= # default to '/' -management.add-application-context-header= # default to true -management.security.enabled=true # enable security -management.security.role=ADMIN # role required to access the management endpoint -management.security.sessions=stateless # session creating policy to use (always, never, if_required, stateless) - -# PID FILE (ApplicationPidFileWriter) -spring.pidfile= # Location of the PID file to write - # ENDPOINTS (AbstractEndpoint subclasses) -endpoints.autoconfig.id=autoconfig -endpoints.autoconfig.sensitive=true -endpoints.autoconfig.enabled=true -endpoints.beans.id=beans -endpoints.beans.sensitive=true -endpoints.beans.enabled=true -endpoints.configprops.id=configprops -endpoints.configprops.sensitive=true -endpoints.configprops.enabled=true -endpoints.configprops.keys-to-sanitize=password,secret,key # suffix or regex -endpoints.dump.id=dump -endpoints.dump.sensitive=true -endpoints.dump.enabled=true -endpoints.env.id=env -endpoints.env.sensitive=true -endpoints.env.enabled=true -endpoints.env.keys-to-sanitize=password,secret,key # suffix or regex -endpoints.health.id=health -endpoints.health.sensitive=true -endpoints.health.enabled=true -endpoints.health.mapping.*= # mapping of health statuses to HttpStatus codes -endpoints.health.time-to-live=1000 -endpoints.info.id=info -endpoints.info.sensitive=false -endpoints.info.enabled=true -endpoints.mappings.enabled=true -endpoints.mappings.id=mappings -endpoints.mappings.sensitive=true -endpoints.metrics.id=metrics -endpoints.metrics.sensitive=true -endpoints.metrics.enabled=true -endpoints.shutdown.id=shutdown -endpoints.shutdown.sensitive=true -endpoints.shutdown.enabled=false -endpoints.trace.id=trace -endpoints.trace.sensitive=true -endpoints.trace.enabled=true - -# HEALTH INDICATORS (previously health.*) -management.health.db.enabled=true -management.health.elasticsearch.enabled=true -management.health.elasticsearch.response-timeout=100 # the time, in milliseconds, to wait for a response from the cluster -management.health.diskspace.enabled=true -management.health.diskspace.path=. -management.health.diskspace.threshold=10485760 -management.health.mongo.enabled=true -management.health.rabbit.enabled=true -management.health.redis.enabled=true -management.health.solr.enabled=true -management.health.status.order=DOWN, OUT_OF_SERVICE, UNKNOWN, UP - -# MVC ONLY ENDPOINTS -endpoints.jolokia.path=jolokia -endpoints.jolokia.sensitive=true -endpoints.jolokia.enabled=true # when using Jolokia +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.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.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.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.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.enabled=true -endpoints.jmx.domain= # the JMX domain, defaults to 'org.springboot' -endpoints.jmx.unique-names=false -endpoints.jmx.static-names= +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 -# REMOTE SHELL -shell.auth=simple # jaas, key, simple, spring -shell.command-refresh-interval=-1 -shell.command-path-patterns= # classpath*:/commands/**, classpath*:/crash/commands/** -shell.config-path-patterns= # classpath*:/crash/* -shell.disabled-commands=jpa*,jdbc*,jndi* # comma-separated list of commands to disable -shell.disabled-plugins=false # don't expose plugins -shell.ssh.enabled= # ssh settings ... -shell.ssh.key-path= -shell.ssh.port= -shell.telnet.enabled= # telnet settings ... -shell.telnet.port= -shell.auth.jaas.domain= # authentication settings ... -shell.auth.key.path= -shell.auth.simple.user.name= -shell.auth.simple.user.password= -shell.auth.spring.roles= +# MANAGEMENT HTTP SERVER (ManagementServerProperties) +management.add-application-context-header=true # 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.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=ADMIN # 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. -# SENDGRID (SendGridAutoConfiguration) -spring.sendgrid.username= # SendGrid account username -spring.sendgrid.password= # SendGrid account password -spring.sendgrid.proxy.host= # SendGrid proxy host -spring.sendgrid.proxy.port= # SendGrid proxy port +# HEALTH INDICATORS (previously health.*) +management.health.db.enabled=true # Enable database health check. +management.health.defaults.enabled=true # Enable default health indicators. +management.health.diskspace.enabled=true # 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.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.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, UNKNOWN, UP # Comma-separated list of health statuses in order of severity. + +# 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.git.mode=simple # Mode to use to expose git information. + +# REMOTE SHELL (ShellProperties) +management.shell.auth.type=simple # Authentication type. Auto-detected according to the environment. +management.shell.auth.jaas.domain=my-domain # JAAS domain. +management.shell.auth.key.path= # Path to the authentication key. This should point to a valid ".pem" file. +management.shell.auth.simple.user.name=user # Login user. +management.shell.auth.simple.user.password= # Login password. +management.shell.auth.spring.roles=ADMIN # Comma-separated list of required roles to login to the CRaSH console. +management.shell.command-path-patterns=classpath*:/commands/**,classpath*:/crash/commands/** # Patterns to use to look for commands. +management.shell.command-refresh-interval=-1 # Scan for changes and update the command if necessary (in seconds). +management.shell.config-path-patterns=classpath*:/crash/* # Patterns to use to look for configurations. +management.shell.disabled-commands=jpa*,jdbc*,jndi* # Comma-separated list of commands to disable. +management.shell.disabled-plugins= # Comma-separated list of plugins to disable. Certain plugins are disabled by default based on the environment. +management.shell.ssh.auth-timeout = # Number of milliseconds after user will be prompted to login again. +management.shell.ssh.enabled=true # Enable CRaSH SSH support. +management.shell.ssh.idle-timeout = # Number of milliseconds after which unused connections are closed. +management.shell.ssh.key-path= # Path to the SSH server key. +management.shell.ssh.port=2000 # SSH port. +management.shell.telnet.enabled=false # Enable CRaSH telnet support. Enabled by default if the TelnetPlugin is available. +management.shell.telnet.port=5000 # Telnet port. + +# 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. + + +# ---------------------------------------- +# DEVTOOLS PROPERTIES +# ---------------------------------------- -# GIT INFO -spring.git.properties= # resource ref to generated git info properties file +# DEVTOOLS (DevToolsProperties) +spring.devtools.livereload.enabled=true # 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. + +# 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.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. ``` diff --git a/X. Appendices/B. Configuration meta-data.md b/X. Appendices/B. Configuration meta-data.md index fe8990e6..a4514451 100644 --- a/X. Appendices/B. Configuration meta-data.md +++ b/X. Appendices/B. Configuration meta-data.md @@ -1,6 +1,6 @@ ### 附录B. 配置元数据 -Spring Boot jars包含元数据文件,它们提供了所有支持的配置属性详情。这些文件设计用于让IDE开发者能够为使用application.properties或application.yml文件的用户提供上下文帮助及代码完成功能。 +Spring Boot jars包含元数据文件,它们提供了所有支持的配置属性详情。这些文件设计用于让IDE开发者能够为使用`application.properties`或`application.yml`文件的用户提供上下文帮助及代码完成功能。 主要的元数据文件是在编译器通过处理所有被`@ConfigurationProperties`注解的节点来自动生成的。 diff --git a/X. Appendices/B.1. Meta-data format.md b/X. Appendices/B.1. Meta-data format.md index 8a24898e..9c057e75 100644 --- a/X. Appendices/B.1. Meta-data format.md +++ b/X. Appendices/B.1. Meta-data format.md @@ -7,6 +7,12 @@ "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": [ @@ -18,10 +24,42 @@ { "name": "server.servlet-path", "type": "java.lang.String", - "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" + "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`中如以下定义: diff --git a/all in one/I. spring_boot_documentation.md b/all in one/I. spring_boot_documentation.md deleted file mode 100644 index 767213f0..00000000 --- a/all in one/I. spring_boot_documentation.md +++ /dev/null @@ -1,65 +0,0 @@ -### Spring Boot文档 - -本节提供一个Spring Boot参考文档的简明概述。你可以把它作为文档其余部分的导航。你可以从头到尾依次阅读该参考指南,或跳过你不感兴趣的章节。 - -* 关于本文档 - -Spring Boot参考指南有[html](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/reference/html),[pdf](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/reference/pdf/spring-boot-reference.pdf)和[epub](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/reference/epub/spring-boot-reference.epub)形式的文档。在[docs.spring.io/spring-boot/docs/current/reference](http://docs.spring.io/spring-boot/docs/current/reference)可获取到最新的副本。 - -本文档的副本可自己使用,也可以分发给其他人,假如你对这些副本不收取任何费用,并且不管以打印还是电子版每个副本都包含版权声明。 - -* 获取帮助 - -使用Spring Boot遇到麻烦,我们很乐意帮忙! - -- 尝试[How-to’s](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto)-它们为多数常见问题提供解决方案。 -- 学习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)! - -* 第一步 - -如果你想从总体上对Spring Boot或Spring入门,可以从[这里开始](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started)! - -- 从零开始:[概述](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-introducing-spring-boot)|[要求](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-system-requirements)|[安装](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-spring-boot) -- 教程:[第一部分](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application)|[第二部分](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application-code) -- 运行示例:[第一部分](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application-run)|[第二部分](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application-executable-jar) - -* 使用Spring Boot - -准备开始实际使用Spring Boot?[我们已经为你做好掩护](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot). - -- 构建系统:[Maven](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-maven)|[Gradle](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-gradle)|[Ant](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-ant)|[Starter POMs](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-starter-poms) -- 最佳实践:[代码结构](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-structuring-your-code)|[@Configuration](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-configuration-classes)|[@EnableAutoConfiguration](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-auto-configuration)|[Beans和依赖注入](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-spring-beans-and-dependency-injection) -- 运行代码:[IDE](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-running-from-an-ide)|[Packaged](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-running-as-a-packaged-application)|[Maven](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-running-with-the-maven-plugin)|[Gradle](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-running-with-the-gradle-plugin) -- 应用打包:[生产jars](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-packaging-for-production) -- Spring Boot命令行:[使用CLI](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#cli) - -* 了解Spring Boot特性 - -需要更多Spring Boot核心特性?[这是为你准备的](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features)! - -- 核心特性:[SpringApplication](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-spring-application)|[外部配置](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config)|[Profiles](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-profiles)|[日志](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-logging) -- Web应用:[MVC](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-spring-mvc)|[内嵌容器](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-embedded-container) -- 使用数据:[SQL](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-sql)|[NO-SQL](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-nosql) -- 消息:[概述](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-messaging)|[JMS](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-jms) -- 测试:[概述](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing)|[Boot应用](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications)|[工具](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-test-utilities) -- 扩展:[Auto-configuration](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-developing-auto-configuration)|[@Conditions](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-condition-annotations) - -* 迁移到生存环境 - -当你准备将你的Spring Boot应用推送到生产环境时,我们为你准备了一些你[可能喜欢的技巧](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready)! - -- 管理端点:[概述](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-endpoints)|[自定义](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-customizing-endpoints) -- 连接可选项:[HTTP](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-monitoring)|[JMX](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-jmx)|[SSH](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-remote-shell) -- 监控:[指标](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-metrics)|[审计](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-auditing)|[追踪](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-tracing)|[进程](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-process-monitoring) - -* 高级主题 - -最后,我们为高级用户准备了一些主题。 - -- 云部署:[Cloud Foundry](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#cloud-deployment-cloud-foundry)|[Heroku](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#cloud-deployment-heroku)|[CloudBees](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#) -- 构建工具插件:[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/all in one/II. getting_started.md b/all in one/II. getting_started.md deleted file mode 100644 index d998eb55..00000000 --- a/all in one/II. getting_started.md +++ /dev/null @@ -1,492 +0,0 @@ -### 开始 - -如果你想从总体上对Spring Boot或Spring入门,本章节就是为你准备的!在这里,我们将回答基本的"what?","how?"和"why?"问题。你会发现一个温雅的Spring Boot介绍及安装指南。然后我们构建第一个Spring Boot应用,并讨论一些我们需要遵循的核心原则。 - -### Spring Boot介绍 - -Spring Boot使开发独立的,产品级别的基于Spring的应用变得非常简单,你只需"just run"。 -我们为Spring平台及第三方库提供开箱即用的设置,这样你就可以有条不紊地开始。多数Spring Boot应用需要很少的Spring配置。 - -你可以使用Spring Boot创建Java应用,并使用`java -jar`启动它或采用传统的war部署方式。我们也提供了一个运行"spring脚本"的命令行工具。 - -我们主要的目标是: - -- 为所有的Spring开发提供一个从根本上更快的和广泛使用的入门经验。 -- 开箱即用,但你可以通过不采用默认设置来摆脱这种方式。 -- 提供一系列大型项目常用的非功能性特征(比如,内嵌服务器,安全,指标,健康检测,外部化配置)。 -- 绝对不需要代码生成及XML配置。 - -### 系统要求 - -默认情况下,Spring Boot 1.3.0.BUILD-SNAPSHOT 需要Java7和Spring框架4.1.3或以上。你可以在Java6下使用Spring Boot,不过需要添加额外配置。具体参考[Section 73.9, “How to use Java 6” ](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-java-6)。构建环境明确支持的有Maven(3.2+)和Gradle(1.12+)。 - -**注**:尽管你可以在Java6或Java7环境下使用Spring Boot,通常我们建议你如果可能的话就使用Java8。 - -* Servlet容器 - -下列内嵌容器支持开箱即用(out of the box): - -|名称|Servlet版本|Java版本| -|--------|:-------|:-------| -|Tomcat 8|3.1|Java 7+| -|Tomcat 7|3.0|Java 6+| -|Jetty 9|3.1|Java 7+| -|Jetty 8|3.0|Java 6+| -|Undertow 1.1|3.1|Java 7+| - -你也可以将Spring Boot应用部署到任何兼容Servlet 3.0+的容器。 - -### Spring Boot安装 - -Spring Boot可以跟典型的Java开发工具一块使用或安装为一个命令行工具。不管怎样,你将需要安装[Java SDK v1.6 ](http://www.java.com/)或更高版本。在开始之前,你需要检查下当前安装的Java版本: -```shell -$ java -version -``` -如果你是一个Java新手,或你只是想体验一下Spring Boot,你可能想先尝试[Spring Boot CLI](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-the-cli),否则继续阅读经典地安装指南。 - -**注**:尽管Spring Boot兼容Java 1.6,如果可能的话,你应该考虑使用Java最新版本。 - -* 为Java开发者准备的安装指南 - -你可以以和任何标准Java库相同的方式使用Spring Boot。只需要简单地在你的classpath下包含正确的`spring-boot-*.jar`文件。Spring Boot不需要集成任何特殊的工具,所以你可以使用任何IDE或文本编辑器;Spring Boot应用也没有什么特殊之处,所以你可以像任何其他Java程序那样运行和调试。 - -尽管你可以拷贝Spring Boot jars,不过,我们通常推荐你使用一个支持依赖管理的构建工具(比如Maven或Gradle)。 - -* 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`。 - -Spring Boot依赖的`groupId`为`org.springframework.boot`。通常你的Maven POM文件需要继承`spring-boot-starter-parent`,然后声明一个或多个[“Starter POMs”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-starter-poms)依赖。Spring Boot也提供了一个用于创建可执行jars的[Maven插件](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-maven-plugin)。 - -下面是一个典型的`pom.xml`文件: -```xml - - - 4.0.0 - - com.example - myproject - 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-starter-parent - 1.3.0.BUILD-SNAPSHOT - - - - - - 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的一个不错的方式,但它不总是合适的。有时你需要继承一个不同的parent POM,或者你可能只是不喜欢我们的默认配置。查看[Section 13.1.2, “Using Spring Boot without the parent POM”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-maven-without-a-parent)获取使用`import`的替代解决方案。 - -* Gradle安装 - -Spring Boot兼容Gradle 1.12或更高版本。如果没有安装Gradle,你可以参考[www.gradle.org](http://www.gradle.org/)上的指南。 - -Spring Boot依赖可以使用`org.springframework.boot` `group`来声明。通常,你的项目将声明一个或多个[“Starter POMs”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-starter-poms)依赖。Spring Boot提供一个用于简化依赖声明和创建可执行jars的有用的[Gradle插件](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-gradle-plugin)。 - -**注**:当你需要构建一个项目时,Gradle Wrapper提供一个获取Gradle的漂亮方式。它是一个伴随你的代码一块提交的小脚本和库,用于启动构建进程。具体参考[Gradle Wrapper](www.gradle.org/docs/current/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:1.3.0.BUILD-SNAPSHOT") - } -} - -apply plugin: 'java' -apply plugin: 'spring-boot' - -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") -} - -``` -* Spring Boot CLI安装 - -Spring Boot是一个命令行工具,用于使用Spring进行快速原型搭建。它允许你运行[Groovy](http://groovy.codehaus.org/)脚本,这意味着你可以使用类Java的语法,并且没有那么多的模板代码。 - -你没有必要为了使用Spring Boot而去用CLI,但它绝对是助力Spring应用的最快方式。 - -- 手动安装 - -你可以从Spring软件仓库下载Spring CLI分发包: - -1. [spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.zip](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/1.3.0.BUILD-SNAPSHOT/spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.zip) -2. [spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin.tar.gz](http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/1.3.0.BUILD-SNAPSHOT/spring-boot-cli-1.3.0.BUILD-SNAPSHOT-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`来运行一个`.jar`文件(该脚本会帮你确定classpath被正确设置)。 - -- 使用GVM安装 - -GVM(Groovy环境管理器)可以用来管理多种不同版本的Groovy和Java二进制包,包括Groovy自身和Spring Boot CLI。可以从[gvmtool.net](http://gvmtool.net/)获取`gvm`,并使用以下命令安装Spring Boot: -```shell -$ gvm install springboot -$ spring --version -Spring Boot v1.3.0.BUILD-SNAPSHOT -``` -如果你正在为CLI开发新的特性,并想轻松获取你刚构建的版本,可以使用以下命令: -```shell -$ gvm install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-1.3.0.BUILD-SNAPSHOT-bin/spring-1.3.0.BUILD-SNAPSHOT/ -$ gvm use springboot dev -$ spring --version -Spring CLI v1.3.0.BUILD-SNAPSHOT -``` -这将会在你的gvm仓库中安装一个名叫`dev`的本地`spring`实例。它指向你的目标构建位置,所以每次你重新构建Spring Boot,`spring`将会是最新的。 - -你可以通过以下命令来验证: -```shell -$ gvm ls springboot - -================================================================================ -Available Springboot Versions -================================================================================ -> + dev -* 1.3.0.BUILD-SNAPSHOT - -================================================================================ -+ - local version -* - installed -> - currently in use -================================================================================ -``` -- 使用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`并重试即可。 - -- 使用MacPorts进行安装 - -如果你的环境是Mac,并使用[MacPorts](http://www.macports.org/),想要安装Spring Boot CLI只需如下操作: -```shell -$ sudo port install spring-boot-cli -``` -- 命令行实现 - -Spring Boot CLI启动脚本为[BASH](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29)和[zsh](http://en.wikipedia.org/wiki/Zsh) shells提供完整的命令行实现。你可以在任何shell中`source`脚本(名称也是`spring`),或将它放到你个人或系统范围的bash实现初始化中。在一个Debian系统里,系统范围的脚本位于`/shell-completion/bash`下,当一个新的shell启动时该目录下的所有脚本都被执行。想要手动运行该脚本,例如,你已经使用`GVM`进行安装了: -```shell -$ . ~/.gvm/springboot/current/shell-completion/bash/spring -$ spring - grab help jar run test version -``` - -**注**:如果你使用Homebrew或MacPorts安装Spring Boot CLI,命令行实现脚本会自动注册到你的shell。 - -- Spring CLI示例快速入门 - -下面是一个相当简单的web应用,你可以用它测试你的安装是否成功。创建一个名叫`app.groovy`的文件: -```groovy -@RestController -class ThisWillActuallyRun { - - @RequestMapping("/") - String home() { - "Hello World!" - } - -} -``` -然后简单地从一个shell中运行它: -```shell -$ spring run app.groovy -``` -**注**:当你首次运行该应用时将会花费一点时间,因为需要下载依赖。后续运行将会快很多。 - -在你最喜欢的浏览器中打开[localhost:8080](localhost:8080),然后你应该看到以下输出: -```java -Hello World! -``` -### 从Spring Boot早期版本升级 - -如果你正在升级一个Spring Boot早期版本,查看下放在[project wiki](http://github.com/spring-projects/spring-boot/wiki)上的"release notes"。你会发现每次发布的更新指南和一个"new and noteworthy"特性列表。 - -想要升级一个已安装的CLI,你需要使用合适的包管理命令(例如,`brew upgrade`),或如果你是手动安装CLI,按照[standard instructions](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation)操作并记得更新你的`PATH`环境变量以移除任何老的引用。 - -### 开发你的第一个Spring Boot应用 - -让我们使用Java开发一个简单的"Hello World!" web应用,来强调下Spring Boot的一些关键特性。我们将使用Maven构建该项目,因为大多数IDEs都支持它。 - -**注**:[spring.io](http://spring.io/)网站包含很多使用Spring Boot的"入门"指南。如果你正在找特定问题的解决方案,可以先去那瞅瞅。 - -在开始前,你需要打开一个终端,检查是否安装可用的Java版本和Maven: -```shell -$ java -version -java version "1.7.0_51" -Java(TM) SE Runtime Environment (build 1.7.0_51-b13) -Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode) -``` -```shell -$ mvn -v -Apache Maven 3.2.3 (33f8c3e1027c3ddde99d3cdebad2656a31e8fdf4; 2014-08-11T13:58:10-07:00) -Maven home: /Users/user/tools/apache-maven-3.1.1 -Java version: 1.7.0_51, vendor: Oracle Corporation -``` -**注**:该示例需要创建自己的文件夹。后续的操作假设你已创建一个合适的文件夹,并且它是你的“当前目录”。 - -* 创建POM - -我们需要以创建一个Maven `pom.xml`文件作为开始。该`pom.xml`是用来构建项目的处方。打开你最喜欢的文本编辑器,然后添加以下内容: -```xml - - - 4.0.0 - - com.example - myproject - 0.0.1-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-parent - 1.3.0.BUILD-SNAPSHOT - - - - - - - - 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的内建支持)。简单起见,我们将继续使用普通的文本编辑器完成该示例。 - -* 添加classpath依赖 - -Spring Boot提供很多"Starter POMs",这能够让你轻松的将jars添加到你的classpath下。我们的示例程序已经在POM的`partent`节点使用了`spring-boot-starter-parent`。`spring-boot-starter-parent`是一个特殊的starter,它提供了有用的Maven默认设置。同时,它也提供了一个`dependency-management`节点,这样对于”blessed“依赖你可以省略`version`标记。 - -其他的”Starter POMs“简单的提供依赖,这些依赖可能是你开发特定类型的应用时需要的。由于正在开发一个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自身。 - -* 编写代码 - -为了完成应用程序,我们需要创建一个单独的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); - } - -} -``` -尽管这里没有太多代码,但很多事情正在发生。让我们分步探讨重要的部分。 - -* @RestController和@RequestMapping注解 - -我们的`Example`类上使用的第一个注解是`@RestController`。这被称为一个构造型(stereotype)注解。它为阅读代码的人们提供建议。对于Spring,该类扮演了一个特殊角色。在本示例中,我们的类是一个web `@Controller`,所以当处理进来的web请求时,Spring会询问它。 - -`@RequestMapping`注解提供路由信息。它告诉Spring任何来自"/"路径的HTTP请求都应该被映射到`home`方法。`@RestController`注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。 - -**注**:`@RestController`和`@RequestMapping`注解是Spring MVC注解(它们不是Spring Boot的特定部分)。具体查看Spring参考文档的[MVC章节](http://docs.spring.io/spring/docs/4.1.5.RELEASE/spring-framework-reference/htmlsingle#mvc)。 - -* @EnableAutoConfiguration注解 - -第二个类级别的注解是`@EnableAutoConfiguration`。这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于`spring-boot-starter-web`添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。 - -**Starter POMs和Auto-Configuration**:设计auto-configuration的目的是更好的使用"Starter POMs",但这两个概念没有直接的联系。你可以自由地挑选starter POMs以外的jar依赖,并且Spring Boot将仍旧尽最大努力去自动配置你的应用。 - -* main方法 - -我们的应用程序最后部分是`main`方法。这只是一个标准的方法,它遵循Java对于一个应用程序入口点的约定。我们的main方法通过调用`run`,将业务委托给了Spring Boot的`SpringApplication`类。`SpringApplication`将引导我们的应用,启动Spring,相应地启动被自动配置的Tomcat web服务器。我们需要将`Example.class`作为参数传递给`run`方法来告诉`SpringApplication`谁是主要的Spring组件。为了暴露任何的命令行参数,`args`数组也会被传递过去。 - -### 运行示例 - -到此我们的应用应该可以工作了。由于使用了`spring-boot-starter-parent` POM,这样我们就有了一个非常有用的`run`目标,我们可以用它启动程序。在项目根目录下输入`mvn spring-boot:run`来启动应用: -```shell -$ mvn spring-boot:run - - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ -( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v1.3.0.BUILD-SNAPSHOT) -....... . . . -....... . . . (log output here) -....... . . . -........ Started Example in 2.222 seconds (JVM running for 6.514) -``` -如果使用一个浏览器打开[localhost:8080](http://localhost:8080),你应该可以看到以下输出: -```shell -Hello World! -``` -点击`ctrl-c`温雅地关闭应用程序。 - -### 创建一个可执行jar - -让我们通过创建一个完全自包含的可执行jar文件来结束我们的示例,该jar文件可以在生产环境运行。可执行jars(有时候被成为胖jars "fat jars")是包含你的编译后的类和你的代码运行所需的依赖jar的存档。 - -**可执行jars和Java**:Java没有提供任何标准的加载内嵌jar文件(即jar文件中还包含jar文件)的方法。如果你想发布一个自包含的应用这就是一个问题。为了解决该问题,很多开发者采用"共享的"jars。一个共享的jar简单地将来自所有jars的类打包进一个单独的“超级jar”。采用共享jar方式的问题是很难区分在你的应用程序中可以使用哪些库。在多个jars中如果存在相同的文件名(但内容不一样)也会是一个问题。Spring Boot采取一个[不同的途径](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#executable-jar),并允许你真正的内嵌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,你将需要自己声明该配置。具体参考[插件文档](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/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:1.3.0.BUILD-SNAPSHOT: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 -``` -在`target`目录下,你应该也能看到一个很小的名为`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 :: (v1.3.0.BUILD-SNAPSHOT) -....... . . . -....... . . . (log output here) -....... . . . -........ Started Example in 2.536 seconds (JVM running for 2.864) -``` -和以前一样,点击`ctrl-c`来温柔地退出程序。 diff --git a/all in one/III. using_spring_boot.md b/all in one/III. using_spring_boot.md deleted file mode 100644 index e4dd83f6..00000000 --- a/all in one/III. using_spring_boot.md +++ /dev/null @@ -1,388 +0,0 @@ -### 使用Spring Boot -本章节将会详细介绍如何使用Spring Boot。它覆盖了构建系统,自动配置和运行/部署选项等主题。我们也覆盖了一些Spring Boot最佳实践。尽管Spring Boot没有什么特别的(只是一个你能消费的库),但仍有一些建议,如果你遵循的话将会让你的开发进程更容易。 - -如果你刚接触Spring Boot,那最好先读下上一章节的[Getting Started](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started)指南。 - -### 构建系统 - -强烈建议你选择一个支持依赖管理,能消费发布到Maven中央仓库的artifacts的构建系统。我们推荐你选择Maven或Gradle。选择其他构建系统来使用Spring Boot也是可能的(比如Ant),但它们不会被很好的支持。 - -* Maven - -Maven用户可以继承`spring-boot-starter-parent`项目来获取合适的默认设置。该父项目提供以下特性: -- 默认编译级别为Java 1.6 -- 源码编码为UTF-8 -- 一个依赖管理节点,允许你省略普通依赖的``标签,继承自`spring-boot-dependencies` POM。 -- 合适的[资源过滤](https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html) -- 合适的插件配置([exec插件](http://mojo.codehaus.org/exec-maven-plugin/),[surefire](http://maven.apache.org/surefire/maven-surefire-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`的资源过滤 - -最后一点:由于默认配置文件接收Spring风格的占位符(`${...}`),Maven filtering改用`@..@`占位符(你可以使用Maven属性`resource.delimiter`来覆盖它)。 - -* 继承starter parent - -想配置你的项目继承`spring-boot-starter-parent`只需要简单地设置`parent`为: -```xml - - - org.springframework.boot - spring-boot-starter-parent - 1.3.0.BUILD-SNAPSHOT - -``` -**注**:你应该只需要在该依赖上指定Spring Boot版本。如果导入其他的starters,你可以放心的省略版本号。 - -* 使用没有父POM的Spring Boot - -不是每个人都喜欢继承`spring-boot-starter-parent` POM。你可能需要使用公司标准parent,或你可能倾向于显式声明所有Maven配置。 - -如果你不使用`spring-boot-starter-parent`,通过使用一个`scope=import`的依赖,你仍能获取到依赖管理的好处: -```xml - - - - - org.springframework.boot - spring-boot-dependencies - 1.3.0.BUILD-SNAPSHOT - pom - import - - - -``` -* 改变Java版本 - -`spring-boot-starter-parent`选择相当保守的Java兼容策略。如果你遵循我们的建议,使用最新的Java版本,你可以添加一个`java.version`属性: -```xml - - 1.8 - -``` -* 使用Spring Boot Maven插件 - -Spring Boot包含一个[Maven插件](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-maven-plugin),它可以将项目打包成一个可执行jar。如果想使用它,你可以将该插件添加到``节点处: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - - -``` -**注**:如果使用Spring Boot starter parent pom,你只需要添加该插件而无需配置它,除非你想改变定义在partent中的设置。 - -* Gradle - -Gradle用户可以直接在它们的`dependencies`节点处导入”starter POMs“。跟Maven不同的是,这里没有用于导入共享配置的"超父"(super parent)。 -```gradle -apply plugin: 'java' - -repositories { jcenter() } -dependencies { - compile("org.springframework.boot:spring-boot-starter-web:1.3.0.BUILD-SNAPSHOT") -} -``` -[spring-boot-gradle-plugin](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins-gradle-plugin)插件也是可以使用的,它提供创建可执行jar和从source运行项目的任务。它也添加了一个`ResolutionStrategy`用于让你省略常用依赖的版本号: -```gradle -buildscript { - repositories { jcenter() } - dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.BUILD-SNAPSHOT") - } -} - -apply plugin: 'java' -apply plugin: 'spring-boot' - -repositories { jcenter() } -dependencies { - compile("org.springframework.boot:spring-boot-starter-web") - testCompile("org.springframework.boot:spring-boot-starter-test") -} -``` -* Ant - -使用Apache Ant构建一个Spring Boot项目是完全可能的,然而,Spring Boot没有为它提供特殊的支持或插件。Ant脚本可以使用Ivy依赖管理系统来导入starter POMs。 - -查看[Section 73.8, “Build an executable archive with Ant”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-build-an-executable-archive-with-ant)获取更多指导。 - -* Starter POMs - -Starter POMs是可以包含到应用中的一个方便的依赖关系描述符集合。你可以获取所有Spring及相关技术的一站式服务,而不需要翻阅示例代码,拷贝粘贴大量的依赖描述符。例如,如果你想使用Spring和JPA进行数据库访问,只需要在你的项目中包含`spring-boot-starter-data-jpa`依赖,然后你就可以开始了。 - -该starters包含很多你搭建项目,快速运行所需的依赖,并提供一致的,管理的传递依赖集。 - -**名字有什么含义**:所有的starters遵循一个相似的命名模式:`spring-boot-starter-*`,在这里`*`是一种特殊类型的应用程序。该命名结构旨在帮你找到需要的starter。很多IDEs集成的Maven允许你通过名称搜索依赖。例如,使用相应的Eclipse或STS插件,你可以简单地在POM编辑器中点击`ctrl-space`,然后输入"spring-boot-starter"可以获取一个完整列表。 - -下面的应用程序starters是Spring Boot在`org.springframework.boot`组下提供的: - -**表 13.1. Spring Boot application starters** - -|名称|描述| -|------|:-----| -|spring-boot-starter|核心Spring Boot starter,包括自动配置支持,日志和YAML| -|spring-boot-starter-actuator|生产准备的特性,用于帮你监控和管理应用| -|spring-boot-starter-amqp|对"高级消息队列协议"的支持,通过`spring-rabbit`实现| -|spring-boot-starter-aop|对面向切面编程的支持,包括`spring-aop`和AspectJ| -|spring-boot-starter-batch|对Spring Batch的支持,包括HSQLDB数据库| -|spring-boot-starter-cloud-connectors|对Spring Cloud Connectors的支持,简化在云平台下(例如,Cloud Foundry 和Heroku)服务的连接| -|spring-boot-starter-data-elasticsearch|对Elasticsearch搜索和分析引擎的支持,包括`spring-data-elasticsearch`| -|spring-boot-starter-data-gemfire|对GemFire分布式数据存储的支持,包括`spring-data-gemfire`| -|spring-boot-starter-data-jpa|对"Java持久化API"的支持,包括`spring-data-jpa`,`spring-orm`和Hibernate| -|spring-boot-starter-data-mongodb|对MongoDB NOSQL数据库的支持,包括`spring-data-mongodb`| -|spring-boot-starter-data-rest|对通过REST暴露Spring Data仓库的支持,通过`spring-data-rest-webmvc`实现| -|spring-boot-starter-data-solr|对Apache Solr搜索平台的支持,包括`spring-data-solr`| -|spring-boot-starter-freemarker|对FreeMarker模板引擎的支持| -|spring-boot-starter-groovy-templates|对Groovy模板引擎的支持| -|spring-boot-starter-hateoas|对基于HATEOAS的RESTful服务的支持,通过`spring-hateoas`实现| -|spring-boot-starter-hornetq|对"Java消息服务API"的支持,通过HornetQ实现| -|spring-boot-starter-integration|对普通`spring-integration`模块的支持| -|spring-boot-starter-jdbc|对JDBC数据库的支持| -|spring-boot-starter-jersey|对Jersey RESTful Web服务框架的支持| -|spring-boot-starter-jta-atomikos|对JTA分布式事务的支持,通过Atomikos实现| -|spring-boot-starter-jta-bitronix|对JTA分布式事务的支持,通过Bitronix实现| -|spring-boot-starter-mail|对`javax.mail`的支持| -|spring-boot-starter-mobile|对`spring-mobile`的支持| -|spring-boot-starter-mustache|对Mustache模板引擎的支持| -|spring-boot-starter-redis|对REDIS键值数据存储的支持,包括`spring-redis`| -|spring-boot-starter-security|对`spring-security`的支持| -|spring-boot-starter-social-facebook|对`spring-social-facebook`的支持| -|spring-boot-starter-social-linkedin|对`spring-social-linkedin`的支持| -|spring-boot-starter-social-twitter|对`spring-social-twitter`的支持| -|spring-boot-starter-test|对常用测试依赖的支持,包括JUnit, Hamcrest和Mockito,还有`spring-test`模块| -|spring-boot-starter-thymeleaf|对Thymeleaf模板引擎的支持,包括和Spring的集成| -|spring-boot-starter-velocity|对Velocity模板引擎的支持| -|spring-boot-starter-web|对全栈web开发的支持,包括Tomcat和`spring-webmvc`| -|spring-boot-starter-websocket|对WebSocket开发的支持| -|spring-boot-starter-ws|对Spring Web服务的支持| - -除了应用程序的starters,下面的starters可以用于添加[生产准备](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready)的特性。 - -**表 13.2. Spring Boot生产准备的starters** - -|名称|描述| -|----|:----| -|spring-boot-starter-actuator|添加生产准备特性,比如指标和监控| -|spring-boot-starter-remote-shell|添加远程`ssh` shell支持| - -最后,Spring Boot包含一些可用于排除或交换具体技术方面的starters。 - -**表 13.3. Spring Boot technical starters** - -|名称|描述| -|------|:------| -|spring-boot-starter-jetty|导入Jetty HTTP引擎(作为Tomcat的替代)| -|spring-boot-starter-log4j|对Log4J日志系统的支持| -|spring-boot-starter-logging|导入Spring Boot的默认日志系统(Logback)| -|spring-boot-starter-tomcat|导入Spring Boot的默认HTTP引擎(Tomcat)| -|spring-boot-starter-undertow|导入Undertow HTTP引擎(作为Tomcat的替代)| - -**注**:查看GitHub上位于`spring-boot-starters`模块内的[README文件](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters/README.adoc),可以获取到一个社区贡献的其他starter POMs列表。 - -### 组织你的代码 - -Spring Boot不需要使用任何特殊的代码结构,然而,这里有一些有用的最佳实践。 - -* 使用"default"包 - -当类没有包含`package`声明时,它被认为处于`default package`下。通常不推荐使用`default package`,并应该避免使用它。因为对于使用`@ComponentScan`,`@EntityScan`或`@SpringBootApplication`注解的Spring Boot应用来说,来自每个jar的类都会被读取,这会造成一定的问题。 - -**注**:我们建议你遵循Java推荐的包命名规范,使用一个反转的域名(例如`com.example.project`)。 - -* 定位main应用类 - -我们通常建议你将main应用类放在位于其他类上面的根包(root package)中。通常使用`@EnableAutoConfiguration`注解你的main类,并且暗地里为某些项定义了一个基础“search package”。例如,如果你正在编写一个JPA应用,被`@EnableAutoConfiguration`注解的类所在包将被用来搜索`@Entity`项。 - -使用根包允许你使用`@ComponentScan`注解而不需要定义一个`basePackage`属性。如果main类位于根包中,你也可以使用`@SpringBootApplication`注解。 - -下面是一个典型的结构: -```shell -com - +- example - +- myproject - +- Application.java - | - +- domain - | +- Customer.java - | +- CustomerRepository.java - | - +- service - | +- CustomerService.java - | - +- web - +- CustomerController.java -``` -`Application.java`文件将声明`main`方法,还有基本的`@Configuration`。 -```java -package com.example.myproject; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableAutoConfiguration -@ComponentScan -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} -``` -### 配置类 - -Spring Boot提倡基于Java的配置。尽管你可以使用一个XML源来调用`SpringApplication.run()`,我们通常建议你使用`@Configuration`类作为主要源。一般定义`main`方法的类也是主要`@Configuration`的一个很好候选。 - -**注**:很多使用XML配置的Spring配置示例已经被发布到网络上。你应该总是尽可能的使用基于Java的配置。搜索查看`enable*`注解就是一个好的开端。 - -* 导入其他配置类 - -你不需要将所有的`@Configuration`放进一个单独的类。`@Import`注解可以用来导入其他配置类。另外,你也可以使用`@ComponentScan`注解自动收集所有的Spring组件,包括`@Configuration`类。 - -* 导入XML配置 - -如果你绝对需要使用基于XML的配置,我们建议你仍旧从一个`@Configuration`类开始。你可以使用附加的`@ImportResource`注解加载XML配置文件。 - -### 自动配置 - -Spring Boot自动配置(auto-configuration)尝试根据你添加的jar依赖自动配置你的Spring应用。例如,如果你的classpath下存在`HSQLDB`,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库。 - -你可以通过将`@EnableAutoConfiguration`或`@SpringBootApplication`注解添加到一个`@Configuration`类上来选择自动配置。 - -**注**:你只需要添加一个`@EnableAutoConfiguration`注解。我们建议你将它添加到主`@Configuration`类上。 - -* 逐步替换自动配置 - -自动配置是非侵占性的,任何时候你都可以定义自己的配置类来替换自动配置的特定部分。例如,如果你添加自己的`DataSource` bean,默认的内嵌数据库支持将不被考虑。 - -如果需要找出当前应用了哪些自动配置及应用的原因,你可以使用`--debug`开关启动应用。这将会记录一个自动配置的报告并输出到控制台。 - -* 禁用特定的自动配置 - -如果发现应用了你不想要的特定自动配置类,你可以使用`@EnableAutoConfiguration`注解的排除属性来禁用它们。 -```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 { -} -``` - -### Spring Beans和依赖注入 - -你可以自由地使用任何标准的Spring框架技术去定义beans和它们注入的依赖。简单起见,我们经常使用`@ComponentScan`注解搜索beans,并结合`@Autowired`构造器注入。 - -如果使用上面建议的结构组织代码(将应用类放到根包下),你可以添加`@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; - } - - // ... -} -``` -**注**:注意如何使用构建器注入来允许`riskAssessor`字段被标记为`final`,这意味着`riskAssessor`后续是不能改变的。 - -### 使用@SpringBootApplication注解 - -很多Spring Boot开发者总是使用`@Configuration`,`@EnableAutoConfiguration`和`@ComponentScan`注解他们的main类。由于这些注解被如此频繁地一块使用(特别是你遵循以上[最佳实践](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-structuring-your-code)时),Spring Boot提供一个方便的`@SpringBootApplication`选择。 - -该`@SpringBootApplication`注解等价于以默认属性使用`@Configuration`,`@EnableAutoConfiguration`和`@ComponentScan`。 -```java -package com.example.myproject; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} -``` -### 运行应用程序 - -将应用打包成jar并使用一个内嵌HTTP服务器的一个最大好处是,你可以像其他方式那样运行你的应用程序。调试Spring Boot应用也很简单;你不需要任何特殊IDE或扩展。 - -**注**:本章节只覆盖基于jar的打包,如果选择将应用打包成war文件,你最好参考一下服务器和IDE文档。 - -* 从IDE中运行 - -你可以从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)提供插件。 - -**注**:如果意外地运行一个web应用两次,你将看到一个"端口已在使用中"错误。为了确保任何存在的实例是关闭的,STS用户可以使用`Relaunch`按钮而不是`Run`按钮。 - -* 作为一个打包后的应用运行 - -如果使用Spring Boot Maven或Gradle插件创建一个可执行jar,你可以使用`java -jar`运行你的应用。例如: -```shell -$ java -jar target/myproject-0.0.1-SNAPSHOT.jar -``` -运行一个打包的程序并开启远程调试支持是可能的,这允许你将调试器附加到打包的应用程序上: -```shell -$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ - -jar target/myproject-0.0.1-SNAPSHOT.jar -``` -* 使用Maven插件运行 - -Spring Boot Maven插件包含一个`run`目标,它可以用来快速编译和运行应用程序。应用程序以一种暴露的方式运行,由于即时"热"加载,你可以编辑资源。 -```shell -$ mvn spring-boot:run -``` -你可能想使用有用的操作系统环境变量: -```shell -$ export MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom -``` -("egd"设置是通过为Tomcat提供一个更快的会话keys熵源来加速Tomcat的。) - -* 使用Gradle插件运行 - -Spring Boot Gradle插件也包含一个`run`目标,它可以用来以暴露的方式运行你的应用程序。不管你什么时候导入`spring-boot-plugin`,`bootRun`任务总是被添加进去。 -```shell -$ gradle bootRun -``` -你可能想使用那些有用的操作系统环境变量: -```shell -$ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom -``` -* 热交换 - -由于Spring Boot应用程序只是普通的Java应用,那JVM热交换(hot-swapping)应该能出色的工作。JVM热交换在它能替换的字节码上有些限制,更全面的解决方案可以使用[Spring Loaded](https://github.com/spring-projects/spring-loaded)项目或[JRebel](http://zeroturnaround.com/software/jrebel/)。 - -关于热交换可以参考[“How-to”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-hotswapping)章节。 - -### 打包用于生产的应用程序 - -可执行jars可用于生产部署。由于它们是自包含的,非常适合基于云的部署。关于其他“生产准备”的特性,比如健康监控,审计和指标REST,或JMX端点,可以考虑添加`spring-boot-actuator`。具体参考[Part V, “Spring Boot Actuator: Production-ready features”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready)。 - - - - - diff --git a/all in one/IV. spring_boot_features.md b/all in one/IV. spring_boot_features.md deleted file mode 100644 index 71edea80..00000000 --- a/all in one/IV. spring_boot_features.md +++ /dev/null @@ -1,1415 +0,0 @@ -Spring Boot特性 -=============== -### SpringApplication -SpringApplication类提供了一种从main()方法启动Spring应用的便捷方式。在很多情况下,你只需委托给SpringApplication.run这个静态方法: -```java -public static void main(String[] args){ - SpringApplication.run(MySpringConfiguration.class, args); -} -``` -* 自定义Banner - -通过在classpath下添加一个banner.txt或设置banner.location来指定相应的文件可以改变启动过程中打印的banner。如果这个文件有特殊的编码,你可以使用banner.encoding设置它(默认为UTF-8)。 - -在banner.txt中可以使用如下的变量: - -| 变量 | 描述 | -| ----------- | :--------| -|${application.version}|MANIFEST.MF中声明的应用版本号,例如1.0| -|${application.formatted-version}|MANIFEST.MF中声明的被格式化后的应用版本号(被括号包裹且以v作为前缀),用于显示,例如(v1.0)| -|${spring-boot.version}|正在使用的Spring Boot版本号,例如1.2.2.BUILD-SNAPSHOT| -|${spring-boot.formatted-version}|正在使用的Spring Boot被格式化后的版本号(被括号包裹且以v作为前缀), 用于显示,例如(v1.2.2.BUILD-SNAPSHOT)| - -**注**:如果想以编程的方式产生一个banner,可以使用SpringBootApplication.setBanner(…)方法。使用org.springframework.boot.Banner接口,实现你自己的printBanner()方法。 - -* 自定义SpringApplication - -如果默认的SpringApplication不符合你的口味,你可以创建一个本地的实例并自定义它。例如,关闭banner你可以这样写: -```java -public static void main(String[] args){ - SpringApplication app = new SpringApplication(MySpringConfiguration.class); - app.setShowBanner(false); - app.run(args); -} -``` -**注**:传递给SpringApplication的构造器参数是spring beans的配置源。在大多数情况下,这些将是@Configuration类的引用,但它们也可能是XML配置或要扫描包的引用。 - -你也可以使用application.properties文件来配置SpringApplication。具体参考[Externalized 配置](#Externalized 配置)。查看配置选项的完整列表,可参考[SpringApplication Javadoc](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/api/org/springframework/boot/SpringApplication.html). - -* 流畅的构建API - -如果你需要创建一个分层的ApplicationContext(多个具有父子关系的上下文),或你只是喜欢使用流畅的构建API,你可以使用SpringApplicationBuilder。SpringApplicationBuilder允许你以链式方式调用多个方法,包括可以创建层次结构的parent和child方法。 -```java -new SpringApplicationBuilder() - .showBanner(false) - .sources(Parent.class) - .child(Application.class) - .run(args); -``` -**注**:创建ApplicationContext层次时有些限制,比如,Web组件(components)必须包含在子上下文(child context)中,且相同的Environment即用于父上下文也用于子上下文中。具体参考[SpringApplicationBuilder javadoc](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/api/org/springframework/boot/builder/SpringApplicationBuilder.html) - -* Application事件和监听器 - -除了常见的Spring框架事件,比如[ContextRefreshedEvent](http://docs.spring.io/spring/docs/4.1.4.RELEASE/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html),一个SpringApplication也发送一些额外的应用事件。一些事件实际上是在ApplicationContext被创建前触发的。 - -你可以使用多种方式注册事件监听器,最普通的是使用SpringApplication.addListeners(…)方法。在你的应用运行时,应用事件会以下面的次序发送: - -1. 在运行开始,但除了监听器注册和初始化以外的任何处理之前,会发送一个ApplicationStartedEvent。 -2. 在Environment将被用于已知的上下文,但在上下文被创建前,会发送一个ApplicationEnvironmentPreparedEvent。 -3. 在refresh开始前,但在bean定义已被加载后,会发送一个ApplicationPreparedEvent。 -4. 启动过程中如果出现异常,会发送一个ApplicationFailedEvent。 - -**注**:你通常不需要使用应用程序事件,但知道它们的存在会很方便(在某些场合可能会使用到)。在Spring内部,Spring Boot使用事件处理各种各样的任务。 - -* Web环境 - -一个SpringApplication将尝试为你创建正确类型的ApplicationContext。在默认情况下,使用AnnotationConfigApplicationContext或AnnotationConfigEmbeddedWebApplicationContext取决于你正在开发的是否是web应用。 - -用于确定一个web环境的算法相当简单(基于是否存在某些类)。如果需要覆盖默认行为,你可以使用setWebEnvironment(boolean webEnvironment)。通过调用setApplicationContextClass(…),你可以完全控制ApplicationContext的类型。 - -**注**:当JUnit测试里使用SpringApplication时,调用setWebEnvironment(false)是可取的。 - -* 命令行启动器 - -如果你想获取原始的命令行参数,或一旦SpringApplication启动,你需要运行一些特定的代码,你可以实现CommandLineRunner接口。在所有实现该接口的Spring beans上将调用run(String… args)方法。 -```java -import org.springframework.boot.* -import org.springframework.stereotype.* - -@Component -public class MyBean implements CommandLineRunner { - public void run(String... args) { - // Do something... - } -} -``` -如果一些CommandLineRunner beans被定义必须以特定的次序调用,你可以额外实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解。 - -* Application退出 - -每个SpringApplication在退出时为了确保ApplicationContext被优雅的关闭,将会注册一个JVM的shutdown钩子。所有标准的Spring生命周期回调(比如,DisposableBean接口或@PreDestroy注解)都能使用。 - -此外,如果beans想在应用结束时返回一个特定的退出码(exit code),可以实现org.springframework.boot.ExitCodeGenerator接口。 - -### 外化配置 - -Spring Boot允许外化(externalize)你的配置,这样你能够在不同的环境下使用相同的代码。你可以使用properties文件,YAML文件,环境变量和命令行参数来外化配置。使用@Value注解,可以直接将属性值注入到你的beans中,并通过Spring的Environment抽象或绑定到结构化对象来访问。 - -Spring Boot使用一个非常特别的PropertySource次序来允许对值进行合理的覆盖,需要以下面的次序考虑属性: - -1. 命令行参数 -2. 来自于java:comp/env的JNDI属性 -3. Java系统属性(System.getProperties()) -4. 操作系统环境变量 -5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource -6. 在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量) -7. 在打包的jar内的应用程序配置文件(application.properties,包含YAML和profile变量) -8. 在@Configuration类上的@PropertySource注解 -9. 默认属性(使用SpringApplication.setDefaultProperties指定) - -下面是一个具体的示例(假设你开发一个使用name属性的@Component): -```java -import org.springframework.stereotype.* -import org.springframework.beans.factory.annotation.* - -@Component -public class MyBean { - @Value("${name}") - private String name; - // ... -} -``` -你可以将一个application.properties文件捆绑到jar内,用来提供一个合理的默认name属性值。当运行在生产环境时,可以在jar外提供一个application.properties文件来覆盖name属性。对于一次性的测试,你可以使用特定的命令行开关启动(比如,java -jar app.jar --name="Spring")。 - -RandomValuePropertySource在注入随机值(比如,密钥或测试用例)时很有用。它能产生整数,longs或字符串,比如: -```java -my.secret=${random.value} -my.number=${random.int} -my.bignumber=${random.long} -my.number.less.than.ten=${random.int(10)} -my.number.in.range=${random.int[1024,65536]} -``` -random.int*语法是OPEN value (,max) CLOSE,此处OPEN,CLOSE可以是任何字符,并且value,max是整数。如果提供max,那么value是最小的值,max是最大的值(不包含在内)。 - -* 访问命令行属性 - -默认情况下,SpringApplication将任何可选的命令行参数(以'--'开头,比如,--server.port=9000)转化为property,并将其添加到Spring Environment中。如上所述,命令行属性总是优先于其他属性源。 - -如果你不想将命令行属性添加到Environment里,你可以使用SpringApplication.setAddCommandLineProperties(false)来禁止它们。 - -* Application属性文件 - -SpringApplication将从以下位置加载application.properties文件,并把它们添加到Spring Environment中: - -1. 当前目录下的一个/config子目录 -2. 当前目录 -3. 一个classpath下的/config包 -4. classpath根路径(root) - -这个列表是按优先级排序的(列表中位置高的将覆盖位置低的)。 - -**注**:你可以使用YAML('.yml')文件替代'.properties'。 - -如果不喜欢将application.properties作为配置文件名,你可以通过指定spring.config.name环境属性来切换其他的名称。你也可以使用spring.config.location环境属性来引用一个明确的路径(目录位置或文件路径列表以逗号分割)。 -```shell -$ java -jar myproject.jar --spring.config.name=myproject -//or -$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties -``` -如果spring.config.location包含目录(相对于文件),那它们应该以/结尾(在加载前,spring.config.name产生的名称将被追加到后面)。不管spring.config.location是什么值,默认的搜索路径classpath:,classpath:/config,file:,file:config/总会被使用。以这种方式,你可以在application.properties中为应用设置默认值,然后在运行的时候使用不同的文件覆盖它,同时保留默认配置。 - -**注**:如果你使用环境变量而不是系统配置,大多数操作系统不允许以句号分割(period-separated)的key名称,但你可以使用下划线(underscores)代替(比如,使用SPRING_CONFIG_NAME代替spring.config.name)。如果你的应用运行在一个容器中,那么JNDI属性(java:comp/env)或servlet上下文初始化参数可以用来取代环境变量或系统属性,当然也可以使用环境变量或系统属性。 - -* 特定的Profile属性 - -除了application.properties文件,特定配置属性也能通过命令惯例application-{profile}.properties来定义。特定Profile属性从跟标准application.properties相同的路径加载,并且特定profile文件会覆盖默认的配置。 - -* 属性占位符 - -当application.properties里的值被使用时,它们会被存在的Environment过滤,所以你能够引用先前定义的值(比如,系统属性)。 -```java -app.name=MyApp -app.description=${app.name} is a Spring Boot application -``` -**注**:你也能使用相应的技巧为存在的Spring Boot属性创建'短'变量,具体参考[Section 63.3, “Use ‘short’ command line arguments”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-short-command-line-arguments)。 - -* 使用YAML代替Properties - -[YAML](http://yaml.org/)是JSON的一个超集,也是一种方便的定义层次配置数据的格式。无论你何时将[SnakeYAML ](http://code.google.com/p/snakeyaml/)库放到classpath下,SpringApplication类都会自动支持YAML作为properties的替换。 - -**注**:如果你使用'starter POMs',spring-boot-starter会自动提供SnakeYAML。 - -* 加载YAML - -Spring框架提供两个便利的类用于加载YAML文档,YamlPropertiesFactoryBean会将YAML作为Properties来加载,YamlMapFactoryBean会将YAML作为Map来加载。 - -示例: -```json -environments: - dev: - url: http://dev.bar.com - name: Developer Setup - prod: - url: http://foo.bar.com - name: My Cool App -``` -上面的YAML文档会被转化到下面的属性中: -```java -environments.dev.url=http://dev.bar.com -environments.dev.name=Developer Setup -environments.prod.url=http://foo.bar.com -environments.prod.name=My Cool App -``` -YAML列表被表示成使用[index]间接引用作为属性keys的形式,例如下面的YAML: -```json -my: - servers: - - dev.bar.com - - foo.bar.com -``` -将会转化到下面的属性中: -```java -my.servers[0]=dev.bar.com -my.servers[1]=foo.bar.com -``` -使用Spring DataBinder工具绑定那样的属性(这是@ConfigurationProperties做的事),你需要确定目标bean中有个java.util.List或Set类型的属性,并且需要提供一个setter或使用可变的值初始化它,比如,下面的代码将绑定上面的属性: -```java -@ConfigurationProperties(prefix="my") -public class Config { - private List servers = new ArrayList(); - public List getServers() { - return this.servers; - } -} -``` -* 在Spring环境中使用YAML暴露属性 - -YamlPropertySourceLoader类能够用于将YAML作为一个PropertySource导出到Sprig Environment。这允许你使用熟悉的@Value注解和占位符语法访问YAML属性。 - -* Multi-profile YAML文档 - -你可以在单个文件中定义多个特定配置(profile-specific)的YAML文档,并通过一个spring.profiles key标示应用的文档。例如: -```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配置被激活,那server.address属性将是127.0.0.1。如果development和production配置(profiles)没有启用,则该属性的值将是192.168.1.100。 - -* YAML缺点 - -YAML文件不能通过@PropertySource注解加载。所以,在这种情况下,如果需要使用@PropertySource注解的方式加载值,那就要使用properties文件。 - -* 类型安全的配置属性 - -使用@Value("${property}")注解注入配置属性有时可能比较笨重,特别是需要使用多个properties或你的数据本身有层次结构。为了控制和校验你的应用配置,Spring Boot提供一个允许强类型beans的替代方法来使用properties。 - -示例: -```java -@Component -@ConfigurationProperties(prefix="connection") -public class ConnectionSettings { - private String username; - private InetAddress remoteAddress; - // ... getters and setters -} -``` -当@EnableConfigurationProperties注解应用到你的@Configuration时,任何被@ConfigurationProperties注解的beans将自动被Environment属性配置。这种风格的配置特别适合与SpringApplication的外部YAML配置进行配合使用。 -```json -# application.yml -connection: - username: admin - remoteAddress: 192.168.1.1 -# additional configuration as required -``` -为了使用@ConfigurationProperties beans,你可以使用与其他任何bean相同的方式注入它们。 -```java -@Service -public class MyService { - @Autowired - private ConnectionSettings connection; - //... - @PostConstruct - public void openConnection() { - Server server = new Server(); - this.connection.configure(server); - } -} -``` -你可以通过在@EnableConfigurationProperties注解中直接简单的列出属性类来快捷的注册@ConfigurationProperties bean的定义。 -```java -@Configuration -@EnableConfigurationProperties(ConnectionSettings.class) -public class MyConfiguration { -} -``` -**注**:使用@ConfigurationProperties能够产生可被IDEs使用的元数据文件。具体参考[Appendix B, Configuration meta-data](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#configuration-metadata)。 - -* 第3方配置 - -正如使用@ConfigurationProperties注解一个类,你也可以在@Bean方法上使用它。当你需要绑定属性到不受你控制的第三方组件时,这种方式非常有用。 - -为了从Environment属性配置一个bean,将@ConfigurationProperties添加到它的bean注册过程: -```java -@ConfigurationProperties(prefix = "foo") -@Bean -public FooComponent fooComponent() { - ... -} -``` -和上面ConnectionSettings的示例方式相同,任何以foo为前缀的属性定义都会被映射到FooComponent上。 - -* 松散的绑定(Relaxed binding) - -Spring Boot使用一些宽松的规则用于绑定Environment属性到@ConfigurationProperties beans,所以Environment属性名和bean属性名不需要精确匹配。常见的示例中有用的包括虚线分割(比如,context--path绑定到contextPath)和将环境属性转为大写字母(比如,PORT绑定port)。 - -示例: -```java -@Component -@ConfigurationProperties(prefix="person") -public class ConnectionSettings { - private String firstName; -} -``` -下面的属性名都能用于上面的@ConfigurationProperties类: - -| 属性 | 说明 | -| -------- | :----- | -|person.firstName|标准驼峰规则| -|person.first-name|虚线表示,推荐用于.properties和.yml文件中| -|PERSON_FIRST_NAME|大写形式,使用系统环境变量时推荐| - -Spring会尝试强制外部的应用属性在绑定到@ConfigurationProperties beans时类型是正确的。如果需要自定义类型转换,你可以提供一个ConversionService bean(bean id为conversionService)或自定义属性编辑器(通过一个CustomEditorConfigurer bean)。 - -* @ConfigurationProperties校验 - -Spring Boot将尝试校验外部的配置,默认使用JSR-303(如果在classpath路径中)。你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解: -```java -@Component -@ConfigurationProperties(prefix="connection") -public class ConnectionSettings { - @NotNull - private InetAddress remoteAddress; - // ... getters and setters -} -``` -你也可以通过创建一个叫做configurationPropertiesValidator的bean来添加自定义的Spring Validator。 - -**注**:spring-boot-actuator模块包含一个暴露所有@ConfigurationProperties beans的端点。简单地将你的web浏览器指向/configprops或使用等效的JMX端点。具体参考[Production ready features](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-endpoints)。 - -### Profiles -Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。任何@Component或@Configuration都能被@Profile标记,从而限制加载它的时机。 -```java -@Configuration -@Profile("production") -public class ProductionConfiguration { - // ... -} -``` -以正常的Spring方式,你可以使用一个spring.profiles.active的Environment属性来指定哪个配置生效。你可以使用平常的任何方式来指定该属性,例如,可以将它包含到你的application.properties中: -```java -spring.profiles.active=dev,hsqldb -``` -或使用命令行开关: -```shell ---spring.profiles.active=dev,hsqldb -``` -* 添加激活的配置(profiles) - -spring.profiles.active属性和其他属性一样都遵循相同的排列规则,最高的PropertySource获胜。也就是说,你可以在application.properties中指定生效的配置,然后使用命令行开关替换它们。 - -有时,将特定的配置属性添加到生效的配置中而不是替换它们是有用的。spring.profiles.include属性可以用来无条件的添加生效的配置。SpringApplication的入口点也提供了一个用于设置额外配置的Java API(比如,在那些通过spring.profiles.active属性生效的配置之上):参考setAdditionalProfiles()方法。 - -示例:当一个应用使用下面的属性,并用`--spring.profiles.active=prod`开关运行,那proddb和prodmq配置也会生效: -```java ---- -my.property: fromyamlfile ---- -spring.profiles: prod -spring.profiles.include: proddb,prodmq -``` -**注**:spring.profiles属性可以定义到一个YAML文档中,用于决定什么时候该文档被包含进配置中。具体参考[Section 63.6, “Change configuration depending on the environment”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-change-configuration-depending-on-the-environment) - -* 以编程方式设置profiles - -在应用运行前,你可以通过调用SpringApplication.setAdditionalProfiles(…)方法,以编程的方式设置生效的配置。使用Spring的ConfigurableEnvironment接口激动配置也是可行的。 - -* Profile特定配置文件 - -application.properties(或application.yml)和通过@ConfigurationProperties引用的文件这两种配置特定变种都被当作文件来加载的,具体参考[Section 23.3, “Profile specific properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-profile-specific-properties)。 - -### 日志 -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/)提供配置。每种情况下都会预先配置使用控制台输出,也可以使用可选的文件输出。 - -默认情况下,如果你使用'Starter POMs',那么就会使用Logback记录日志。为了确保那些使用Java Util Logging, Commons Logging, Log4J或SLF4J的依赖库能够正常工作,正确的Logback路由也被包含进来。 - -**注**:如果上面的列表看起来令人困惑,不要担心,Java有很多可用的日志框架。通常,你不需要改变日志依赖,Spring Boot默认的就能很好的工作。 - -* 日志格式 - -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. 日志信息。 - -* 控制台输出 - -默认的日志配置会在写日志消息时将它们回显到控制台。默认,ERROR, WARN和INFO级别的消息会被记录。可以在启动应用时,通过`--debug`标识开启控制台的DEBUG级别日志记录。 -```shell -$ java -jar myapp.jar --debug -``` -如果你的终端支持ANSI,为了增加可读性将会使用彩色的日志输出。你可以设置`spring.output.ansi.enabled`为一个[支持的值](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/api/org/springframework/boot/ansi/AnsiOutput.Enabled.html)来覆盖自动检测。 - -* 文件输出 - -默认情况下,Spring Boot只会将日志记录到控制台而不会写进日志文件。如果除了输出到控制台你还想写入到日志文件,那你需要设置`logging.file`或`logging.path`属性(例如在你的application.properties中)。 - -下表显示如何组合使用`logging.*`: - -|logging.file|logging.path| 示例 | 描述 | -| -------- | :----- | :----- | :-----| -| (none) | (none) | | 只记录到控制台 | -|Specific file|(none)|my.log|写到特定的日志文件里,名称可以是一个精确的位置或相对于当前目录| -|(none)|Specific folder|/var/log|写到特定文件夹下的spring.log里,名称可以是一个精确的位置或相对于当前目录| - -日志文件每达到10M就会被轮换(分割),和控制台一样,默认记录ERROR, WARN和INFO级别的信息。 - -* 日志级别 - -所有支持的日志系统在Spring的Environment(例如在application.properties里)都有通过'logging.level.*=LEVEL'('LEVEL'是TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF中的一个)设置的日志级别。 - -示例:application.properties -```java -logging.level.org.springframework.web: DEBUG -logging.level.org.hibernate: ERROR -``` -* 自定义日志配置 - -通过将适当的库添加到classpath,可以激活各种日志系统。然后在classpath的根目录(root)或通过Spring Environment的`logging.config`属性指定的位置提供一个合适的配置文件来达到进一步的定制(注意由于日志是在ApplicationContext被创建之前初始化的,所以不可能在Spring的@Configuration文件中,通过@PropertySources控制日志。系统属性和平常的Spring Boot外部配置文件能正常工作)。 - -根据你的日志系统,下面的文件会被加载: - -| 日志系统 | 定制 | -| -------- | :-----: | -|Logback|logback.xml| -|Log4j|log4j.properties或log4j.xml| -|Log4j2|log4j2.xml| -|JDK (Java Util Logging)|logging.properties| - -为了帮助定制一些其他的属性,从Spring的Envrionment转换到系统属性: - -| Spring Environment| System Property| 评价 | -| -------- | :-----: | :----: | -|logging.file|LOG_FILE|如果定义,在默认的日志配置中使用| -|logging.path|LOG_PATH|如果定义,在默认的日志配置中使用| -|PID|PID|当前的处理进程(process)ID(如果能够被发现且还没有作为操作系统环境变量被定义)| - -所有支持的日志系统在解析它们的配置文件时都能查询系统属性。具体可以参考spring-boot.jar中的默认配置。 - -**注**:在运行可执行的jar时,Java Util Logging有类加载问题,我们建议你尽可能避免使用它。 - -### 开发Web应用 -Spring Boot非常适合开发web应用程序。你可以使用内嵌的Tomcat,Jetty或Undertow轻轻松松地创建一个HTTP服务器。大多数的web应用都使用spring-boot-starter-web模块进行快速搭建和运行。 - -* Spring Web MVC框架 - -Spring Web MVC框架(通常简称为"Spring MVC")是一个富"模型,视图,控制器"的web框架。 -Spring MVC允许你创建特定的@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 Boot为Spring MVC提供适用于多数应用的自动配置功能。在Spring默认基础上,自动配置添加了以下特性: - -1. 引入ContentNegotiatingViewResolver和BeanNameViewResolver beans。 -2. 对静态资源的支持,包括对WebJars的支持。 -3. 自动注册Converter,GenericConverter,Formatter beans。 -4. 对HttpMessageConverters的支持。 -5. 自动注册MessageCodeResolver。 -6. 对静态index.html的支持。 -7. 对自定义Favicon的支持。 - -如果想全面控制Spring MVC,你可以添加自己的@Configuration,并使用@EnableWebMvc对其注解。如果想保留Spring Boot MVC的特性,并只是添加其他的[MVC配置](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle#mvc)(拦截器,formatters,视图控制器等),你可以添加自己的WebMvcConfigurerAdapter类型的@Bean(不使用@EnableWebMvc注解)。 - -* HttpMessageConverters - -Spring MVC使用HttpMessageConverter接口转换HTTP请求和响应。合理的缺省值被包含的恰到好处(out of the box),例如对象可以自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用则使用它,否则使用JAXB)。字符串默认使用UTF-8编码。 - -如果需要添加或自定义转换器,你可以使用Spring Boot的HttpMessageConverters类: -```java -import org.springframework.boot.autoconfigure.web.HttpMessageConverters; -import org.springframework.context.annotation.*; -import org.springframework.http.converter.*; - -@Configuration -public class MyConfiguration { - - @Bean - public HttpMessageConverters customConverters() { - HttpMessageConverter additional = ... - HttpMessageConverter another = ... - return new HttpMessageConverters(additional, another); - } -} -``` -任何在上下文中出现的HttpMessageConverter bean将会添加到converters列表,你可以通过这种方式覆盖默认的转换器(converters)。 - -* MessageCodesResolver - -Spring MVC有一个策略,用于从绑定的errors产生用来渲染错误信息的错误码:MessageCodesResolver。如果设置`spring.mvc.message-codes-resolver.format`属性为`PREFIX_ERROR_CODE`或`POSTFIX_ERROR_CODE`(具体查看`DefaultMessageCodesResolver.Format`枚举值),Spring Boot会为你创建一个MessageCodesResolver。 - -* 静态内容 - -默认情况下,Spring Boot从classpath下一个叫/static(/public,/resources或/META-INF/resources)的文件夹或从ServletContext根目录提供静态内容。这使用了Spring MVC的ResourceHttpRequestHandler,所以你可以通过添加自己的WebMvcConfigurerAdapter并覆写addResourceHandlers方法来改变这个行为(加载静态文件)。 - -在一个单独的web应用中,容器默认的servlet是开启的,如果Spring决定不处理某些请求,默认的servlet作为一个回退(降级)将从ServletContext根目录加载内容。大多数时候,这不会发生(除非你修改默认的MVC配置),因为Spring总能够通过DispatcherServlet处理请求。 - -此外,上述标准的静态资源位置有个例外情况是[Webjars内容](http://www.webjars.org/)。任何在/webjars/**路径下的资源都将从jar文件中提供,只要它们以Webjars的格式打包。 - -**注**:如果你的应用将被打包成jar,那就不要使用src/main/webapp文件夹。尽管该文件夹是一个共同的标准,但它仅在打包成war的情况下起作用,并且如果产生一个jar,多数构建工具都会静悄悄的忽略它。 - -* 模板引擎 - -正如REST web服务,你也可以使用Spring MVC提供动态HTML内容。Spring MVC支持各种各样的模板技术,包括Velocity, FreeMarker和JSPs。很多其他的模板引擎也提供它们自己的Spring MVC集成。 - -Spring Boot为以下的模板引擎提供自动配置支持: - -1. [FreeMarker](http://freemarker.org/docs/) -2. [Groovy](http://beta.groovy-lang.org/docs/groovy-2.3.0/html/documentation/markup-template-engine.html) -3. [Thymeleaf](http://www.thymeleaf.org/) -4. [Velocity](http://velocity.apache.org/) - -**注**:如果可能的话,应该忽略JSPs,因为在内嵌的servlet容器使用它们时存在一些[已知的限制](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-jsp-limitations)。 - -当你使用这些引擎的任何一种,并采用默认的配置,你的模板将会从src/main/resources/templates目录下自动加载。 - -**注**:IntelliJ IDEA根据你运行应用的方式会对classpath进行不同的整理。在IDE里通过main方法运行你的应用跟从Maven或Gradle或打包好的jar中运行相比会导致不同的顺序。这可能导致Spring Boot不能从classpath下成功地找到模板。如果遇到这个问题,你可以在IDE里重新对classpath进行排序,将模块的类和资源放到第一位。或者,你可以配置模块的前缀为classpath*:/templates/,这样会查找classpath下的所有模板目录。 - -* 错误处理 - -Spring Boot默认提供一个/error映射用来以合适的方式处理所有的错误,并且它在servlet容器中注册了一个全局的 -错误页面。对于机器客户端(相对于浏览器而言,浏览器偏重于人的行为),它会产生一个具有详细错误,HTTP状态,异常信息的JSON响应。对于浏览器客户端,它会产生一个白色标签样式(whitelabel)的错误视图,该视图将以HTML格式显示同样的数据(可以添加一个解析为erro的View来自定义它)。为了完全替换默认的行为,你可以实现ErrorController,并注册一个该类型的bean定义,或简单地添加一个ErrorAttributes类型的bean以使用现存的机制,只是替换显示的内容。 - -如果在某些条件下需要比较多的错误页面,内嵌的servlet容器提供了一个统一的Java DSL(领域特定语言)来自定义错误处理。 -示例: -```java -@Bean -public EmbeddedServletContainerCustomizer containerCustomizer(){ - return new MyCustomizer(); -} - -// ... -private static class MyCustomizer implements EmbeddedServletContainerCustomizer { - @Override - public void customize(ConfigurableEmbeddedServletContainer container) { - container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - } -} -``` -你也可以使用常规的Spring MVC特性来处理错误,比如[@ExceptionHandler方法](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers)和[@ControllerAdvice](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-controller-advice)。ErrorController将会捡起任何没有处理的异常。 - -N.B. 如果你为一个路径注册一个ErrorPage,最终被一个过滤器(Filter)处理(对于一些非Spring web框架,像Jersey和Wicket这很常见),然后过滤器需要显式注册为一个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分发器类型。 - -* Spring HATEOAS - -如果你正在开发一个使用超媒体的RESTful API,Spring Boot将为Spring HATEOAS提供自动配置,这在多数应用中都工作良好。自动配置替换了对使用@EnableHypermediaSupport的需求,并注册一定数量的beans来简化构建基于超媒体的应用,这些beans包括一个LinkDiscoverer和配置好的用于将响应正确编排为想要的表示的ObjectMapper。ObjectMapper可以根据spring.jackson.*属性或一个存在的Jackson2ObjectMapperBuilder bean进行自定义。 - -通过使用@EnableHypermediaSupport,你可以控制Spring HATEOAS的配置。注意这会禁用上述的对ObjectMapper的自定义。 - -* JAX-RS和Jersey - -如果喜欢JAX-RS为REST端点提供的编程模型,你可以使用可用的实现替代Spring MVC。如果在你的应用上下文中将Jersey 1.x和Apache Celtix的Servlet或Filter注册为一个@Bean,那它们工作的相当好。Jersey 2.x有一些原生的Spring支持,所以我们会在Spring Boot为它提供自动配置支持,连同一个启动器(starter)。 - -想要开始使用Jersey 2.x只需要加入spring-boot-starter-jersey依赖,然后你需要一个ResourceConfig类型的@Bean,用于注册所有的端点(endpoints)。 -```java -@Component -public class JerseyConfig extends ResourceConfig { - public JerseyConfig() { - register(Endpoint.class); - } -} -``` -所有注册的端点都应该被@Components和HTTP资源annotations(比如@GET)注解。 -```java -@Component -@Path("/hello") -public class Endpoint { - @GET - public String message() { - return "Hello"; - } -} -``` -由于Endpoint是一个Spring组件(@Component),所以它的生命周期受Spring管理,并且你可以使用@Autowired添加依赖及使用@Value注入外部配置。Jersey servlet将被注册,并默认映射到/*。你可以将@ApplicationPath添加到ResourceConfig来改变该映射。 - -默认情况下,Jersey将在一个ServletRegistrationBean类型的@Bean中被设置成名称为jerseyServletRegistration的Servlet。通过创建自己的相同名称的bean,你可以禁止或覆盖这个bean。你也可以通过设置`spring.jersey.type=filter`来使用一个Filter代替Servlet(在这种情况下,被覆盖或替换的@Bean是jerseyFilterRegistration)。该servlet有@Order属性,你可以通过`spring.jersey.filter.order`进行设置。不管是Servlet还是Filter注册都可以使用spring.jersey.init.*定义一个属性集合作为初始化参数传递过去。 - -这里有一个[Jersey示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jersey),你可以查看如何设置相关事项。 - -* 内嵌servlet容器支持 - -Spring Boot支持内嵌的Tomcat, Jetty和Undertow服务器。多数开发者只需要使用合适的'Starter POM'来获取一个完全配置好的实例即可。默认情况下,内嵌的服务器会在8080端口监听HTTP请求。 - -**1.Servlets和Filters** - -当使用内嵌的servlet容器时,你可以直接将servlet和filter注册为Spring的beans。在配置期间,如果你想引用来自application.properties的值,这是非常方便的。默认情况下,如果上下文只包含单一的Servlet,那它将被映射到根路径(/)。在多Servlet beans的情况下,bean的名称将被用作路径的前缀。过滤器会被映射到/*。 - -如果基于约定(convention-based)的映射不够灵活,你可以使用ServletRegistrationBean和FilterRegistrationBean类实现完全的控制。如果你的bean实现了ServletContextInitializer接口,也可以直接注册它们。 - -**2.EmbeddedWebApplicationContext** - -Spring Boot底层使用了一个新的ApplicationContext类型,用于对内嵌servlet容器的支持。EmbeddedWebApplicationContext是一个特殊类型的WebApplicationContext,它通过搜索一个单一的EmbeddedServletContainerFactory bean来启动自己。通常,TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory将被自动配置。 - -**注**:你通常不需要知道这些实现类。大多数应用将被自动配置,并根据你的行为创建合适的ApplicationContext和EmbeddedServletContainerFactory。 - -**3.自定义内嵌servlet容器** - -常见的Servlet容器设置可以通过Spring Environment属性进行配置。通常,你会把这些属性定义到application.properties文件中。 -常见的服务器设置包括: - -1. server.port - 进来的HTTP请求的监听端口号 -2. server.address - 绑定的接口地址 -3. server.sessionTimeout - session超时时间 - -具体参考[ServerProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)。 - -**编程方式的自定义** - -如果需要以编程的方式配置内嵌的servlet容器,你可以注册一个实现EmbeddedServletContainerCustomizer接口的Spring bean。EmbeddedServletContainerCustomizer提供对ConfigurableEmbeddedServletContainer的访问,ConfigurableEmbeddedServletContainer包含很多自定义的setter方法。 -```java -import org.springframework.boot.context.embedded.*; -import org.springframework.stereotype.Component; - -@Component -public class CustomizationBean implements EmbeddedServletContainerCustomizer { - @Override - public void customize(ConfigurableEmbeddedServletContainer container) { - container.setPort(9000); - } -} -``` -**直接自定义ConfigurableEmbeddedServletContainer** - -如果上面的自定义手法过于受限,你可以自己注册TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory。 -```java -@Bean -public EmbeddedServletContainerFactory servletContainer() { - TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); - factory.setPort(9000); - factory.setSessionTimeout(10, TimeUnit.MINUTES); - factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"); - return factory; -} -``` -很多可选的配置都提供了setter方法,也提供了一些受保护的钩子方法以满足你的某些特殊需求。具体参考相关文档。 - -**4.JSP的限制** - -在内嵌的servlet容器中运行一个Spring Boot应用时(并打包成一个可执行的存档archive),容器对JSP的支持有一些限制。 - -1. tomcat只支持war的打包方式,不支持可执行的jar。 -2. 内嵌的Jetty目前不支持JSPs。 -3. Undertow不支持JSPs。 - -这里有个[JSP示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp),你可以查看如何设置相关事项。 - -### 安全 -如果Spring Security在classpath下,那么web应用默认对所有的HTTP路径(也称为终点,端点,表示API的具体网址)使用'basic'认证。为了给web应用添加方法级别的保护,你可以添加@EnableGlobalMethodSecurity并使用想要的设置。其他信息参考[Spring Security Reference](http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle#jc-method)。 - -默认的AuthenticationManager有一个单一的user('user'的用户名和随机密码会在应用启动时以INFO日志级别打印出来)。如下: -```java -Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 -``` -**注**:如果你对日志配置进行微调,确保`org.springframework.boot.autoconfigure.security`类别能记录INFO信息,否则默认的密码不会被打印。 - -你可以通过提供`security.user.password`改变默认的密码。这些和其他有用的属性通过[SecurityProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityProperties.java)(以security为前缀的属性)被外部化了。 - -默认的安全配置(security configuration)是在SecurityAutoConfiguration和导入的类中实现的(SpringBootWebSecurityConfiguration用于web安全,AuthenticationManagerConfiguration用于与非web应用也相关的认证配置)。你可以添加一个@EnableWebSecurity bean来彻底关掉Spring Boot的默认配置。为了对它进行自定义,你需要使用外部的属性配置和WebSecurityConfigurerAdapter类型的beans(比如,添加基于表单的登陆)。在[Spring Boot示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/)里有一些安全相关的应用可以带你体验常见的用例。 - -在一个web应用中你能得到的基本特性如下: - -1. 一个使用内存存储的AuthenticationManager bean和唯一的user(查看SecurityProperties.User获取user的属性)。 -2. 忽略(不保护)常见的静态资源路径(`/css/**, /js/**, /images/**`和 `**/favicon.ico`)。 -3. 对其他的路径实施HTTP Basic安全保护。 -4. 安全相关的事件会发布到Spring的ApplicationEventPublisher(成功和失败的认证,拒绝访问)。 -5. Spring Security提供的常见底层特性(HSTS, XSS, CSRF, 缓存)默认都被开启。 - -上述所有特性都能打开和关闭,或使用外部的配置进行修改(security.*)。为了覆盖访问规则(access rules)而不改变其他自动配置的特性,你可以添加一个使用@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)注解的WebSecurityConfigurerAdapter类型的@Bean。 - -如果Actuator也在使用,你会发现: - -1. 即使应用路径不受保护,被管理的路径也会受到保护。 -2. 安全相关的事件被转换为AuditEvents(审计事件),并发布给AuditService。 -3. 默认的用户有ADMIN和USER的角色。 - -使用外部属性能够修改Actuator(执行器)的安全特性(management.security.*)。为了覆盖应用程序的访问规则,你可以添加一个WebSecurityConfigurerAdapter类型的@Bean。同时,如果不想覆盖执行器的访问规则,你可以使用@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)注解该bean,否则使用@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)注解该bean。 - -### 使用SQL数据库 -Spring框架为使用SQL数据库提供了广泛的支持。从使用JdbcTemplate直接访问JDBC到完全的对象关系映射技术,比如Hibernate。Spring Data提供一个额外的功能,直接从接口创建Repository实现,并使用约定从你的方法名生成查询。 - -* 配置DataSource - -Java的javax.sql.DataSource接口提供了一个标准的使用数据库连接的方法。传统做法是,一个DataSource使用一个URL连同相应的证书去初始化一个数据库连接。 - -**1.对内嵌数据库的支持** - -开发应用时使用内存数据库是很实用的。显而易见地,内存数据库不需要提供持久化存储。你不需要在应用启动时填充数据库,也不需要在应用结束时丢弃数据。 - -Spring Boot可以自动配置的内嵌数据库包括[H2](http://www.h2database.com/), [HSQL](http://hsqldb.org/)和[Derby](http://db.apache.org/derby/)。你不需要提供任何连接URLs,只需要简单的添加你想使用的内嵌数据库依赖。 - -示例:典型的POM依赖如下: -```xml - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hsqldb - hsqldb - runtime - -``` -**注**:对于自动配置的内嵌数据库,你需要依赖spring-jdbc。在示例中,它通过`spring-boot-starter-data-jpa`被传递地拉过来了。 - -**2.连接到一个生产环境数据库** - -在生产环境中,数据库连接可以使用DataSource池进行自动配置。下面是选取一个特定实现的算法: - -- 由于Tomcat数据源连接池的性能和并发,在tomcat可用时,我们总是优先使用它。 -- 如果HikariCP可用,我们将使用它。 -- 如果Commons DBCP可用,我们将使用它,但在生产环境不推荐使用它。 -- 最后,如果Commons DBCP2可用,我们将使用它。 - -如果你使用spring-boot-starter-jdbc或spring-boot-starter-data-jpa 'starter POMs',你将会自动获取对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 -``` -其他可选的配置可以查看[DataSourceProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java)。同时注意你可以通过spring.datasource.*配置任何DataSource实现相关的特定属性:具体参考你使用的连接池实现的文档。 - -**注**:既然Spring Boot能够从大多数数据库的url上推断出driver-class-name,那么你就不需要再指定它了。对于一个将要创建的DataSource连接池,我们需要能够验证Driver是否可用,所以我们会在做任何事情之前检查它。比如,如果你设置spring.datasource.driverClassName=com.mysql.jdbc.Driver,然后这个类就会被加载。 - -**3.连接到一个JNDI数据库** - -如果正在将Spring Boot应用部署到一个应用服务器,你可能想要用应用服务器内建的特性来配置和管理你的DataSource,并使用JNDI访问它。 - -spring.datasource.jndi-name属性可以用来替代spring.datasource.url,spring.datasource.username和spring.datasource.password去从一个特定的JNDI路径访问DataSource。比如,下面application.properties中的片段展示了如何获取JBoss定义的DataSource: -```java -spring.datasource.jndi-name=java:jboss/datasources/customers -``` -* 使用JdbcTemplate - -Spring的JdbcTemplate和NamedParameterJdbcTemplate类是被自动配置的,你可以在自己的beans中通过@Autowire直接注入它们。 -```java -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Component; - -@Component -public class MyBean { - - private final JdbcTemplate jdbcTemplate; - - @Autowired - public MyBean(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - // ... -} -``` -* 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/)的参考文档。 - -**1.实体类** - -传统上,JPA实体类被定义到一个persistence.xml文件中。在Spring Boot中,这个文件不是必需的,并被'实体扫描'替代。默认情况下,在你主(main)配置类(被@EnableAutoConfiguration或@SpringBootApplication注解的类)下的所有包都将被查找。 - -任何被@Entity,@Embeddable或@MappedSuperclass注解的类都将被考虑。一个普通的实体类看起来像下面这样: -```java -package com.example.myapp.domain; - -import java.io.Serializable; -import javax.persistence.*; - -@Entity -public class City implements Serializable { - - @Id - @GeneratedValue - private Long id; - - @Column(nullable = false) - private String name; - - @Column(nullable = false) - private String state; - - // ... additional members, often include @OneToMany mappings - - protected City() { - // no-args constructor required by JPA spec - // this one is protected since it shouldn't be used directly - } - - public City(String name, String state) { - this.name = name; - this.country = country; - } - - public String getName() { - return this.name; - } - - public String getState() { - return this.state; - } - // ... etc -} -``` -**注**:你可以使用@EntityScan注解自定义实体扫描路径。具体参考[Section 67.4, “Separate @Entity definitions from Spring configuration”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-separate-entity-definitions-from-spring-configuration)。 - -**2.Spring Data JPA仓库** - -Spring Data JPA仓库(repositories)是用来定义访问数据的接口。根据你的方法名,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仓库通常继承自[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)接口。如果你使用自动配置,包括在你的主配置类(被@EnableAutoConfiguration或@SpringBootApplication注解的类)的包下的仓库将会被搜索。 - -下面是一个传统的Spring Data仓库: -```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 JPA的表面。具体查看它的[参考指南](http://projects.spring.io/spring-data-jpa/)。 - -**3.创建和删除JPA数据库** - -默认情况下,只有在你使用内嵌数据库(H2, HSQL或Derby)时,JPA数据库才会被自动创建。你可以使用spring.jpa.*属性显示的设置JPA。比如,为了创建和删除表你可以将下面的配置添加到application.properties中: -```java -spring.jpa.hibernate.ddl-auto=create-drop -``` -**注**:Hibernate自己内部对创建,删除表支持(如果你恰好记得这回事更好)的属性是hibernate.hbm2ddl.auto。使用spring.jpa.properties.*(前缀在被添加到实体管理器之前会被剥离掉),你可以设置Hibernate本身的属性,比如hibernate.hbm2ddl.auto。示例:`spring.jpa.properties.hibernate.globally_quoted_identifiers=true`将传递hibernate.globally_quoted_identifiers到Hibernate实体管理器。 - -默认情况下,DDL执行(或验证)被延迟到ApplicationContext启动。这也有一个spring.jpa.generate-ddl标识,如果Hibernate自动配置被激活,那该标识就不会被使用,因为ddl-auto设置粒度更细。 - -### 使用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/), [Couchbase](http://projects.spring.io/spring-data-couchbase/)和[Cassandra](http://projects.spring.io/spring-data-cassandra/)。Spring Boot为Redis, MongoDB, Elasticsearch, Solr和Gemfire提供自动配置。你可以充分利用其他项目,但你需要自己配置它们。具体查看[projects.spring.io/spring-data.](http://projects.spring.io/spring-data/)中合适的参考文档。 - -* Redis - -[Redis](http://redis.io/)是一个缓存,消息中间件及具有丰富特性的键值存储系统。Spring Boot为[Jedis](https://github.com/xetorthio/jedis/)客户端库和由[Spring Data Redis](https://github.com/spring-projects/spring-data-redis)提供的基于Jedis客户端的抽象提供自动配置。`spring-boot-starter-redis`'Starter POM'为收集依赖提供一种便利的方式。 - -1. 连接Redis - -你可以注入一个自动配置的RedisConnectionFactory,StringRedisTemplate或普通的跟其他Spring Bean相同的RedisTemplate实例。默认情况下,这个实例将尝试使用localhost:6379连接Redis服务器。 -```java -@Component -public class MyBean { - - private StringRedisTemplate template; - - @Autowired - public MyBean(StringRedisTemplate template) { - this.template = template; - } - // ... -} -``` -如果你添加一个你自己的任何自动配置类型的@Bean,它将替换默认的(除了RedisTemplate的情况,它是根据bean的名称'redisTemplate'而不是它的类型进行排除的)。如果在classpath路径下存在commons-pool2,默认你会获得一个连接池工厂。 - -* MongoDB - -[MongoDB](http://www.mongodb.com/)是一个开源的NoSQL文档数据库,它使用一个JSON格式的模式(schema)替换了传统的基于表的关系数据。Spring Boot为使用MongoDB提供了很多便利,包括`spring-boot-starter-data-mongodb`'Starter POM'。 - -**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,或指定一个host/port。比如,你可能会在你的application.properties中设置如下的属性: -```java -spring.data.mongodb.host=mongoserver -spring.data.mongodb.port=27017 -``` -**注**:如果没有指定`spring.data.mongodb.port`,那将使用默认的端口27017。你可以简单的从上面的示例中删除这一行。如果不使用Spring Data Mongo,你可以注入com.mongodb.Mongo beans而不是使用MongoDbFactory。 - -如果想全面控制MongoDB连接的建立,你也可以声明自己的MongoDbFactory或Mongo,@Beans。 - -**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,你只需简单的注入它即可: -```java -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.stereotype.Component; - -@Component -public class MyBean { - - private final MongoTemplate mongoTemplate; - - @Autowired - public MyBean(MongoTemplate mongoTemplate) { - this.mongoTemplate = mongoTemplate; - } - // ... -} -``` -具体参考MongoOperations Javadoc。 - -**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); - -} -``` -* 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 POM'。目前不支持Gemfire的自动配置,但你可以使用一个[单一的注解](https://github.com/spring-projects/spring-data-gemfire/blob/master/src/main/java/org/springframework/data/gemfire/repository/config/EnableGemfireRepositories.java)使Spring Data仓库支持它。 - -* Solr - -[Apache Solr](http://lucene.apache.org/solr/)是一个搜索引擎。Spring Boot为solr客户端库及[Spring Data Solr](https://github.com/spring-projects/spring-data-solr)提供的基于solr客户端库的抽象提供了基本的配置。Spring Boot提供了一个用于聚集依赖的`spring-boot-starter-data-solr`'Starter POM'。 - -**1. 连接Solr** - -你可以像其他Spring beans一样注入一个自动配置的SolrServer实例。默认情况下,该实例将尝试使用`localhost:8983/solr`连接一个服务器。 -```java -@Component -public class MyBean { - - private SolrServer solr; - - @Autowired - public MyBean(SolrServer solr) { - this.solr = solr; - } - // ... -} -``` -如果你添加一个自己的SolrServer类型的@Bean,它将会替换默认的。 - -**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/)。 - -* Elasticsearch - -[Elastic Search](http://www.elasticsearch.org/)是一个开源的,分布式,实时搜索和分析引擎。Spring Boot为Elasticsearch及[Spring Data Elasticsearch](https://github.com/spring-projects/spring-data-elasticsearch)提供的基于它的抽象提供了基本的配置。Spring Boot提供了一个用于聚集依赖的`spring-boot-starter-data-elasticsearch`'Starter POM'。 - -**1. 连接Elasticsearch** - -你可以像其他Spring beans那样注入一个自动配置的ElasticsearchTemplate或Elasticsearch客户端实例。默认情况下,该实例将尝试连接到一个本地内存服务器(在Elasticsearch项目中的一个NodeClient),但你可以通过设置`spring.data.elasticsearch.clusterNodes`为一个以逗号分割的host:port列表来将其切换到一个远程服务器(比如,TransportClient)。 -```java -@Component -public class MyBean { - - private ElasticsearchTemplate template; - - @Autowired - public MyBean(ElasticsearchTemplate template) { - this.template = template; - } - // ... -} -``` -如果你添加一个你自己的ElasticsearchTemplate类型的@Bean,它将替换默认的。 - -**2. 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/)。 - -### 消息 - -Spring Framework框架为集成消息系统提供了扩展(extensive)支持:从使用JmsTemplate简化JMS API,到实现一个完整异步消息接收的底层设施。Spring AMQP提供一个相似的用于'高级消息队列协议'的特征集,并且Spring Boot也为RabbitTemplate和RabbitMQ提供了自动配置选项。Spring Websocket提供原生的STOMP消息支持,并且Spring Boot通过starters和一些自动配置也提供了对它的支持。 - -* JMS - -javax.jms.ConnectionFactory接口提供了一个标准的用于创建一个javax.jms.Connection的方法,javax.jms.Connection用于和JMS代理(broker)交互。尽管为了使用JMS,Spring需要一个ConnectionFactory,但通常你不需要直接使用它,而是依赖于上层消息抽象(具体参考Spring框架的[相关章节](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#jms))。Spring Boot也会自动配置发送和接收消息需要的设施(infrastructure)。 - - 1. HornetQ支持 - -如果在classpath下发现HornetQ,Spring Boot会自动配置ConnectionFactory。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(除非显式设置mode属性)。支持的modes有:embedded(显式声明使用一个内嵌的代理,如果该代理在classpath下不可用将导致一个错误),native(使用netty传输协议连接代理)。当后者被配置,Spring Boot配置一个连接到一个代理的ConnectionFactory,该代理运行在使用默认配置的本地机器上。 - -**注**:如果使用spring-boot-starter-hornetq,连接到一个已存在的HornetQ实例所需的依赖都会被提供,同时还有用于集成JMS的Spring基础设施。将org.hornetq:hornetq-jms-server添加到你的应用中,你就可以使用embedded模式。 - -HornetQ配置被spring.hornetq.*中的外部配置属性所控制。例如,你可能在application.properties声明以下片段: -```java -spring.hornetq.mode=native -spring.hornetq.host=192.168.1.210 -spring.hornetq.port=9876 -``` -当内嵌代理时,你可以选择是否启用持久化,并且列表中的目标都应该是可用的。这些可以通过一个以逗号分割的列表来指定一些默认的配置项,或定义org.hornetq.jms.server.config.JMSQueueConfiguration或org.hornetq.jms.server.config.TopicConfiguration类型的bean(s)来配置更高级的队列和主题。具体参考[HornetQProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQProperties.java)。 - -没有涉及JNDI查找,目标是通过名字解析的,名字即可以使用HornetQ配置中的name属性,也可以是配置中提供的names。 - - 2. ActiveQ支持 - -如果发现ActiveMQ在classpath下可用,Spring Boot会配置一个ConnectionFactory。如果需要代理,将会开启一个内嵌的,已经自动配置好的代理(只要配置中没有指定代理URL)。 - -ActiveMQ配置是通过spring.activemq.*中的外部配置来控制的。例如,你可能在application.properties中声明下面的片段: -```java -spring.activemq.broker-url=tcp://192.168.1.210:9876 -spring.activemq.user=admin -spring.activemq.password=secret -``` -具体参考[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将创建一个,所以目标是通过它们提供的名称解析出来的。 - - 3. 使用JNDI ConnectionFactory - -如果你在一个应用服务器中运行你的应用,Spring Boot将尝试使用JNDI定位一个JMS ConnectionFactory。默认情况会检查java:/JmsXA和java:/ -XAConnectionFactory。如果需要的话,你可以使用spring.jms.jndi-name属性来指定一个替代位置。 -```java -spring.jms.jndi-name=java:/MyConnectionFactory -``` - 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](http://docs.spring.io/spring/docs/4.1.4.RELEASE/javadoc-api/org/springframework/jms/core/JmsMessagingTemplate.html)(Spring4.1新增的)也可以使用相同的方式注入。 - - 5. 接收消息 - -当JMS基础设施能够使用时,任何bean都能够被@JmsListener注解,以创建一个监听者端点。如果没有定义JmsListenerContainerFactory,一个默认的将会被自动配置。下面的组件在someQueue目标上创建一个监听者端点。 -```java -@Component -public class MyBean { -@JmsListener(destination = "someQueue") -public void processMessage(String content) { -// ... -} -} -``` -具体查看[@EnableJms javadoc](http://docs.spring.io/spring/docs/4.1.4.RELEASE/javadoc-api/org/springframework/jms/annotation/EnableJms.html)。 - -### 发送邮件 - -Spring框架使用JavaMailSender接口为发送邮件提供了一个简单的抽象,并且Spring Boot也为它提供了自动配置和一个starter模块。 -具体查看[JavaMailSender参考文档](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#mail)。 - -如果spring.mail.host和相关的库(通过spring-boot-starter-mail定义)都存在,一个默认的JavaMailSender将被创建。该sender可以通过spring.mail命名空间下的配置项进一步自定义,具体参考[MailProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mail/MailProperties.java)。 - -### 使用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自动配置功能。 - -* 使用一个Atomikos事务管理器 - -Atomikos是一个非常流行的开源事务管理器,它可以嵌入到你的Spring Boot应用中。你可以使用`spring-boot-starter-jta-atomikos`Starter POM去获取正确的Atomikos库。Spring Boot会自动配置Atomikos,并将合适的depends-on应用到你的Spring Beans上,确保它们以正确的顺序启动和关闭。 - -默认情况下,Atomikos事务日志将被记录在应用home目录(你的应用jar文件放置的目录)下的transaction-logs文件夹中。你可以在application.properties文件中通过设置spring.jta.log-dir属性来自定义该目录。以spring.jta.开头的属性能用来自定义Atomikos的UserTransactionServiceIml实现。具体参考[AtomikosProperties javadoc](http://docs.spring.io/spring-boot/docs/1.2.2.BUILD-SNAPSHOT/api/org/springframework/boot/jta/atomikos/AtomikosProperties.html)。 - -**注**:为了确保多个事务管理器能够安全地和相应的资源管理器配合,每个Atomikos实例必须设置一个唯一的ID。默认情况下,该ID是Atomikos实例运行的机器上的IP地址。为了确保生产环境中该ID的唯一性,你需要为应用的每个实例设置不同的spring.jta.transaction-manager-id属性值。 - -* 使用一个Bitronix事务管理器 - -Bitronix是另一个流行的开源JTA事务管理器实现。你可以使用`spring-boot-starter-jta-bitronix`starter POM为项目添加合适的Birtronix依赖。和Atomikos类似,Spring Boot将自动配置Bitronix,并对beans进行后处理(post-process)以确保它们以正确的顺序启动和关闭。 - -默认情况下,Bitronix事务日志将被记录到应用home目录下的transaction-logs文件夹中。通过设置spring.jta.log-dir属性,你可以自定义该目录。以spring.jta.开头的属性将被绑定到bitronix.tm.Configuration bean,你可以通过这完成进一步的自定义。具体参考[Bitronix文档](http://btm.codehaus.org/api/2.0.1/bitronix/tm/Configuration.html)。 - -**注**:为了确保多个事务管理器能够安全地和相应的资源管理器配合,每个Bitronix实例必须设置一个唯一的ID。默认情况下,该ID是Bitronix实例运行的机器上的IP地址。为了确保生产环境中该ID的唯一性,你需要为应用的每个实例设置不同的spring.jta.transaction-manager-id属性值。 - -* 使用一个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。 - -* 混合XA和non-XA的JMS连接 - -当使用JTA时,主要的JMS ConnectionFactory bean将是XA aware,并参与到分布式事务中。有些情况下,你可能需要使用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; -``` -* 支持可替代的内嵌事务管理器 - -[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集成 - -Spring集成提供基于消息和其他协议的,比如HTTP,TCP等的抽象。如果Spring集成在classpath下可用,它将会通过@EnableIntegration注解被初始化。如果classpath下'spring-integration-jmx'可用,则消息处理统计分析将被通过JMX发布出去。具体参考[IntegrationAutoConfiguration类](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java)。 - -### 基于JMX的监控和管理 - -Java管理扩展(JMX)提供了一个标准的用于监控和管理应用的机制。默认情况下,Spring Boot将创建一个id为‘mbeanServer’的MBeanServer,并导出任何被Spring JMX注解(@ManagedResource,@ManagedAttribute,@ManagedOperation)的beans。具体参考[JmxAutoConfiguration类](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.java)。 - -### 测试 - -Spring Boot提供很多有用的测试应用的工具。spring-boot-starter-test POM提供Spring Test,JUnit,Hamcrest和Mockito的依赖。在spring-boot核心模块org.springframework.boot.test包下也有很多有用的测试工具。 - -* 测试作用域依赖 - -如果使用spring-boot-starter-test ‘Starter POM’(在test作用域内),你将发现下列被提供的库: -- Spring Test - 对Spring应用的集成测试支持 -- JUnit - 事实上的(de-facto)标准,用于Java应用的单元测试。 -- Hamcrest - 一个匹配对象的库(也称为约束或前置条件),它允许assertThat等JUnit类型的断言。 -- Mockito - 一个Java模拟框架。 - -这也有一些我们写测试用例时经常用到的库。如果它们不能满足你的要求,你可以随意添加其他的测试用的依赖库。 - -* 测试Spring应用 - -依赖注入最大的优点就是它能够让你的代码更容易进行单元测试。你只需简单的通过new操作符实例化对象,而不需要涉及Spring。你也可以使用模拟对象替换真正的依赖。 - -你常常需要在进行单元测试后,开始集成测试(在这个过程中只需要涉及到Spring的ApplicationContext)。在执行集成测试时,不需要部署应用或连接到其他基础设施是非常有用的。 - -Spring框架包含一个dedicated测试模块,用于这样的集成测试。你可以直接声明对org.springframework:spring-test的依赖,或使用spring-boot-starter-test ‘Starter POM’以透明的方式拉取它。 - -如果你以前没有使用过spring-test模块,可以查看Spring框架参考文档中的[相关章节](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#testing)。 - -* 测试Spring Boot应用 - -一个Spring Boot应用只是一个Spring ApplicationContext,所以在测试它时除了正常情况下处理一个vanilla Spring context外不需要做其他特别事情。唯一需要注意的是,如果你使用SpringApplication创建上下文,外部配置,日志和Spring Boot的其他特性只会在默认的上下文中起作用。 - -Spring Boot提供一个@SpringApplicationConfiguration注解用来替换标准的spring-test @ContextConfiguration注解。如果使用@SpringApplicationConfiguration来设置你的测试中使用的ApplicationContext,它最终将通过SpringApplication创建,并且你将获取到Spring Boot的其他特性。 - -示例如下: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class) -public class CityRepositoryIntegrationTests { -@Autowired -CityRepository repository; -// ... -} -``` -**提示**:上下文加载器会通过查找@WebIntegrationTest或@WebAppConfiguration注解来猜测你想测试的是否是web应用(例如,是否使用MockMVC,MockMVC和@WebAppConfiguration是spring-test的一部分)。 - -如果想让一个web应用启动,并监听它的正常的端口,你可以使用HTTP来测试它(比如,使用RestTemplate),并使用@WebIntegrationTest注解你的测试类(或它的一个父类)。这很有用,因为它意味着你可以对你的应用进行全栈测试,但在一次HTTP交互后,你需要在你的测试类中注入相应的组件并使用它们断言应用的内部状态。 - -示例: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class) -@WebIntegrationTest -public class CityRepositoryIntegrationTests { -@Autowired -CityRepository repository; -RestTemplate restTemplate = new TestRestTemplate(); -// ... interact with the running server -} -``` -**注**:Spring测试框架在每次测试时会缓存应用上下文。因此,只要你的测试共享相同的配置,不管你实际运行多少测试,开启和停止服务器只会发生一次。 - -你可以为@WebIntegrationTest添加环境变量属性来改变应用服务器端口号,比如@WebIntegrationTest("server.port:9000")。此外,你可以将server.port和management.port属性设置为0来让你的集成测试使用随机的端口号,例如: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = MyApplication.class) -@WebIntegrationTest({"server.port=0", "management.port=0"}) -public class SomeIntegrationTests { -// ... -} -``` -可以查看[Section 64.4, “Discover the HTTP port at runtime”](),它描述了如何在测试期间发现分配的实际端口。 - -1. 使用Spock测试Spring Boot应用 - -如果期望使用Spock测试一个Spring Boot应用,你应该将Spock的spock-spring模块依赖添加到应用的构建中。spock-spring将Spring的测试框架集成到了Spock里。 - -注意你不能使用上述提到的@SpringApplicationConfiguration注解,因为[Spock找不到@ContextConfiguration元注解](https://code.google.com/p/spock/issues/detail?id=349)。为了绕过该限制,你应该直接使用@ContextConfiguration注解,并使用Spring Boot特定的上下文加载器来配置它。 -```java -@ContextConfiguration(loader = SpringApplicationContextLoader.class) -class ExampleSpec extends Specification { -// ... -} -``` -**注**:上面描述的注解在Spock中可以使用,比如,你可以使用@WebIntegrationTest注解你的Specification以满足测试需要。 - -* 测试工具 - -打包进spring-boot的一些有用的测试工具类。 - -1. ConfigFileApplicationContextInitializer - -ConfigFileApplicationContextInitializer是一个ApplicationContextInitializer,可以用来测试加载Spring Boot的application.properties文件。当不需要使用@SpringApplicationConfiguration提供的全部特性时,你可以使用它。 - -```java -@ContextConfiguration(classes = Config.class,initializers = ConfigFileApplicationContextInitializer.class) -```   -2. EnvironmentTestUtils - -EnvironmentTestUtils允许你快速添加属性到一个ConfigurableEnvironment或ConfigurableApplicationContext。只需简单的使用key=value字符串调用它: -```java -EnvironmentTestUtils.addEnvironment(env, "org=Spring", "name=Boot"); -``` -3. OutputCapture - -OutputCapture是一个JUnit Rule,用于捕获System.out和System.err输出。只需简单的将捕获声明为一个@Rule,并使用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")); -} -} -``` - -4. TestRestTemplate - -TestRestTemplate是一个方便进行集成测试的Spring RestTemplate子类。你会获取到一个普通的模板或一个发送基本HTTP认证(使用用户名和密码)的模板。在任何情况下,这些模板都表现出对测试友好:不允许重定向(这样你可以对响应地址进行断言),忽略cookies(这样模板就是无状态的),对于服务端错误不会抛出异常。推荐使用Apache HTTP Client(4.3.2或更好的版本),但不强制这样做。如果在classpath下存在Apache HTTP Client,TestRestTemplate将以正确配置的client进行响应。 -```java -public class MyTest { -RestTemplate template = new TestRestTemplate(); -@Test -public void testRequest() throws Exception { -HttpHeaders headers = template.getForEntity("http://myhost.com", String.class).getHeaders(); -assertThat(headers.getLocation().toString(), containsString("myotherhost")); -} -} -``` - -### 开发自动配置和使用条件 - -如果你在一个开发者共享库的公司工作,或你在从事一个开源或商业型的库,你可能想要开发自己的auto-configuration。Auto-configuration类能够在外部的jars中绑定,并仍能被Spring Boot发现。 - -* 理解auto-configured beans - -从底层来讲,auto-configured是使用标准的@Configuration实现的类,另外的@Conditional注解用来约束在什么情况下使用auto-configuration。通常auto-configuration类使用@ConditionalOnClass和@ConditionalOnMissingBean注解。这是为了确保只有在相关的类被发现,和你没有声明自己的@Configuration时才应用auto-configuration。 - -你可以浏览spring-boot-autoconfigure的源码,查看我们提供的@Configuration类(查看META-INF/spring.factories文件)。 - -* 定位auto-configuration候选者 - -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后面。 - -* Condition注解 - -你几乎总是需要在你的auto-configuration类里添加一个或更多的@Condition注解。@ConditionalOnMissingBean注解是一个常见的示例,它经常用于允许开发者覆盖auto-configuration,如果他们不喜欢你提供的默认行为。 - -Spring Boot包含很多@Conditional注解,你可以在自己的代码中通过注解@Configuration类或单独的@Bean方法来重用它们。 - -1. Class条件 - -@ConditionalOnClass和@ConditionalOnMissingClass注解允许根据特定类是否出现来跳过配置。由于注解元数据是使用[ASM](http://asm.ow2.org/)来解析的,你实际上可以使用value属性来引用真正的类,即使该类可能实际上并没有出现在运行应用的classpath下。如果你倾向于使用一个String值来指定类名,你也可以使用name属性。 - -2. Bean条件 - -@ConditionalOnBean和@ConditionalOnMissingBean注解允许根据特定beans是否出现来跳过配置。你可以使用value属性来指定beans(by type),也可以使用name来指定beans(by name)。search属性允许你限制搜索beans时需要考虑的ApplicationContext的层次。 - -**注**:当@Configuration类被解析时@Conditional注解会被处理。Auto-configure @Configuration总是最后被解析(在所有用户定义beans后面),然而,如果你将那些注解用到常规的@Configuration类,需要注意不能引用那些还没有创建好的bean定义。 - -3. Property条件 - -@ConditionalOnProperty注解允许根据一个Spring Environment属性来决定是否包含配置。可以使用prefix和name属性指定要检查的配置属性。默认情况下,任何存在的只要不是false的属性都会匹配。你也可以使用havingValue和matchIfMissing属性创建更高级的检测。 - -4. Resource条件 - -@ConditionalOnResource注解允许只有在特定资源出现时配置才会被包含。资源可以使用常见的Spring约定命名,例如file:/home/user/test.dat。 - -5. Web Application条件 - -@ConditionalOnWebApplication和@ConditionalOnNotWebApplication注解允许根据应用是否为一个'web应用'来决定是否包含配置。一个web应用是任何使用Spring WebApplicationContext,定义一个session作用域或有一个StandardServletEnvironment的应用。 - -6. SpEL表达式条件 - -@ConditionalOnExpression注解允许根据[SpEL表达式](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#expressions)结果来跳过配置。 - -### WebSockets - -Spring Boot为内嵌的Tomcat(8和7),Jetty 9和Undertow提供WebSockets自动配置。如果你正在将一个war包部署到一个单独的容器,Spring Boot会假设该容器会对它的WebSocket支持相关的配置负责。 - -Spring框架提供[丰富的WebSocket支持](http://docs.spring.io/spring/docs/4.1.4.RELEASE/spring-framework-reference/htmlsingle/#websocket),通过spring-boot-starter-websocket模块可以轻易获取到。 - diff --git a/all in one/IX. How-to_ guides.md b/all in one/IX. How-to_ guides.md deleted file mode 100644 index 34a39f0b..00000000 --- a/all in one/IX. How-to_ guides.md +++ /dev/null @@ -1,1426 +0,0 @@ -### How-to指南 - -本章节将回答一些常见的"我该怎么做"类型的问题,这些问题在我们使用Spring Boot时经常遇到。这绝不是一个详尽的列表,但它覆盖了很多方面。 - -如果遇到一个特殊的我们没有覆盖的问题,你可能想去查看[stackoverflow.com](http://stackoverflow.com/tags/spring-boot),看是否有人已经给出了答案;这也是一个很好的提新问题的地方(请使用`spring-boot`标签)。 - -我们也乐意扩展本章节;如果想添加一个'how-to',你可以给我们发一个[pull请求](http://github.com/spring-projects/spring-boot/tree/master)。 - -### Spring Boot应用 - -* 解决自动配置问题 - -Spring Boot自动配置总是尝试尽最大努力去做正确的事,但有时候会失败并且很难说出失败原因。 - -在每个Spring Boot `ApplicationContext`中都存在一个相当有用的`ConditionEvaluationReport`。如果开启`DEBUG`日志输出,你将会看到它。如果你使用`spring-boot-actuator`,则会有一个`autoconfig`的端点,它将以JSON形式渲染该报告。可以使用它调试应用程序,并能查看Spring Boot运行时都添加了哪些特性(及哪些没添加)。 - -通过查看源码和javadoc可以获取更多问题的答案。以下是一些经验: - -1. 查找名为`*AutoConfiguration`的类并阅读源码,特别是`@Conditional*`注解,这可以帮你找出它们启用哪些特性及何时启用。 -将`--debug`添加到命令行或添加系统属性`-Ddebug`可以在控制台查看日志,该日志会记录你的应用中所有自动配置的决策。在一个运行的Actuator app中,通过查看`autoconfig`端点(`/autoconfig`或等效的JMX)可以获取相同信息。 -2. 查找是`@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`端点。 -3. 查看使用`RelaxedEnvironment`明确地将配置从`Environment`暴露出去。它经常会使用一个前缀。 -4. 查看`@Value`注解,它直接绑定到`Environment`。相比`RelaxedEnvironment`,这种方式稍微缺乏灵活性,但它也允许松散的绑定,特别是OS环境变量(所以`CAPITALS_AND_UNDERSCORES`是`period.separated`的同义词)。 -5. 查看`@ConditionalOnExpression`注解,它根据SpEL表达式的结果来开启或关闭特性,通常使用解析自`Environment`的占位符进行计算。 - -6. 启动前自定义Environment或ApplicationContext - -每个`SpringApplication`都有`ApplicationListeners`和`ApplicationContextInitializers`,用于自定义上下文(context)或环境(environment)。Spring Boot从`META-INF/spring.factories`下加载很多这样的内部使用的自定义。有很多方法可以注册其他的自定义: - -1. 以编程方式为每个应用注册自定义,通过在SpringApplication运行前调用它的`addListeners`和`addInitializers`方法来实现。 -2. 以声明方式为每个应用注册自定义,通过设置`context.initializer.classes`或`context.listener.classes`来实现。 -3. 以声明方式为所有应用注册自定义,通过添加一个`META-INF/spring.factories`并打包成一个jar文件(该应用将它作为一个库)来实现。 - -`SpringApplication`会给监听器(即使是在上下文被创建之前就存在的)发送一些特定的`ApplicationEvents`,然后也会注册监听`ApplicationContext`发布的事件的监听器。查看Spring Boot特性章节中的[Section 22.4, “Application events and listeners” ](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-events-and-listeners)可以获取一个完整列表。 - -* 构建ApplicationContext层次结构(添加父或根上下文) - -你可以使用`ApplicationBuilder`类创建父/根`ApplicationContext`层次结构。查看'Spring Boot特性'章节的[Section 22.3, “Fluent builder API” ](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-fluent-builder-api)获取更多信息。 - -* 创建一个非web(non-web)应用 - -不是所有的Spring应用都必须是web应用(或web服务)。如果你想在main方法中执行一些代码,但需要启动一个Spring应用去设置需要的底层设施,那使用Spring Boot的`SpringApplication`特性可以很容易实现。`SpringApplication`会根据它是否需要一个web应用来改变它的`ApplicationContext`类。首先你需要做的是去掉servlet API依赖,如果不能这样做(比如,基于相同的代码运行两个应用),那你可以明确地调用`SpringApplication.setWebEnvironment(false)`或设置`applicationContextClass`属性(通过Java API或使用外部配置)。你想运行的,作为业务逻辑的应用代码可以实现为一个`CommandLineRunner`,并将上下文降级为一个`@Bean`定义。 - -### 属性&配置 - -* 外部化SpringApplication配置 - -SpringApplication已经被属性化(主要是setters),所以你可以在创建应用时使用它的Java API修改它的行为。或者你可以使用properties文件中的`spring.main.*`来外部化(在应用代码外配置)这些配置。比如,在`application.properties`中可能会有以下内容: -```java -spring.main.web_environment=false -spring.main.show_banner=false -``` -然后Spring Boot在启动时将不会显示banner,并且该应用也不是一个web应用。 - -* 改变应用程序外部配置文件的位置 - -默认情况下,来自不同源的属性以一个定义好的顺序添加到Spring的`Environment`中(查看'Sprin Boot特性'章节的[Chapter 23, Externalized Configuration](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config)获取精确的顺序)。 - -为应用程序源添加`@PropertySource`注解是一种很好的添加和修改源顺序的方法。传递给`SpringApplication`静态便利设施(convenience)方法的类和使用`setSources()`添加的类都会被检查,以查看它们是否有`@PropertySources`,如果有,这些属性会被尽可能早的添加到`Environment`里,以确保`ApplicationContext`生命周期的所有阶段都能使用。以这种方式添加的属性优先于任何使用默认位置添加的属性,但低于系统属性,环境变量或命令行参数。 - -你也可以提供系统属性(或环境变量)来改变该行为: - -1. `spring.config.name`(`SPRING_CONFIG_NAME`)是根文件名,默认为`application`。 -2. `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) - -* 使用'short'命令行参数 - -有些人喜欢使用(例如)`--port=9000`代替`--server.port=9000`来设置命令行配置属性。你可以通过在application.properties中使用占位符来启用该功能,比如: -```java -server.port=${port:8080} -``` -**注**:如果你继承自`spring-boot-starter-parent` POM,为了防止和Spring-style的占位符产生冲突,`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`属性的大写同义词。 - -* 使用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 23.6, “Using YAML instead of Properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-yaml)可以获取更多关于YAML的信息。 - -* 设置生效的Spring profiles - -Spring `Environment`有一个API可以设置生效的profiles,但通常你会设置一个系统profile(`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 24, Profiles](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-profiles)。 - -* 根据环境改变配置 - -一个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相关的值。 - -* 发现外部属性的内置选项 - -Spring Boot在运行时将来自application.properties(或.yml)的外部属性绑定进一个应用中。在一个地方不可能存在详尽的所有支持属性的列表(技术上也是不可能的),因为你的classpath下的其他jar文件也能够贡献。 - -每个运行中且有Actuator特性的应用都会有一个`configprops`端点,它能够展示所有边界和可通过`@ConfigurationProperties`绑定的属性。 - -附录中包含一个[application.properties](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties)示例,它列举了Spring Boot支持的大多数常用属性。获取权威列表可搜索`@ConfigurationProperties`和`@Value`的源码,还有不经常使用的`RelaxedEnvironment`。 - -### 内嵌的servlet容器 - -* 为应用添加Servlet,Filter或ServletContextListener - -Servlet规范支持的Servlet,Filter,ServletContextListener和其他监听器可以作为`@Bean`定义添加到你的应用中。需要格外小心的是,它们不会引起太多的其他beans的热初始化,因为在应用生命周期的早期它们已经被安装到容器里了(比如,让它们依赖你的DataSource或JPA配置就不是一个好主意)。你可以通过延迟初始化它们到第一次使用而不是初始化时来突破该限制。 - -在Filters和Servlets的情况下,你也可以通过添加一个`FilterRegistrationBean`或`ServletRegistrationBean`代替或以及底层的组件来添加映射(mappings)和初始化参数。 - -* 禁止注册Servlet或Filter - -正如[以上讨论](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-add-a-servlet-filter-or-servletcontextlistener)的任何Servlet或Filter beans将被自动注册到servlet容器中。为了禁止注册一个特殊的Filter或Servlet bean,可以为它创建一个注册bean,然后禁用该bean。例如: -```java -@Bean -public FilterRegistrationBean registration(MyFilter filter) { - FilterRegistrationBean registration = new FilterRegistrationBean(filter); - registration.setEnabled(false); - return registration; -} -``` - -* 改变HTTP端口 - -在一个单独的应用中,主HTTP端口默认为8080,但可以使用`server.port`设置(比如,在application.properties中或作为一个系统属性)。由于`Environment`值的宽松绑定,你也可以使用`SERVER_PORT`(比如,作为一个OS环境变)。 - -为了完全关闭HTTP端点,但仍创建一个WebApplicationContext,你可以设置`server.port=-1`(测试时可能有用)。 - -想获取更多详情可查看'Spring Boot特性'章节的[Section 26.3.3, “Customizing embedded servlet containers”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-customizing-embedded-containers),或[ServerProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)源码。 - -* 使用随机未分配的HTTP端口 - -想扫描一个未使用的端口(为了防止冲突使用OS本地端口)可以使用`server.port=0`。 - -* 发现运行时的HTTP端口 - -你可以通过日志输出或它的EmbeddedServletContainer的EmbeddedWebApplicationContext获取服务器正在运行的端口。获取和确认服务器已经初始化的最好方式是添加一个`ApplicationListener`类型的`@Bean`,然后当事件发布时将容器pull出来。 - -使用`@WebIntegrationTests`的一个有用实践是设置`server.port=0`,然后使用`@Value`注入实际的('local')端口。例如: -```java -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class) -@WebIntegrationTest("server.port:0") -public class CityRepositoryIntegrationTests { - - @Autowired - EmbeddedWebApplicationContext server; - - @Value("${local.server.port}") - int port; - - // ... - -} -``` -* 配置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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot/src/main/java/org/springframework/boot/context/embedded/Ssl.java)。 - -**注**:Tomcat要求key存储(如果你正在使用一个可信存储)能够直接在文件系统上访问,即它不能从一个jar文件内读取。Jetty和Undertow没有该限制。 - -使用类似于以上示例的配置意味着该应用将不在支持端口为8080的普通HTTP连接。Spring Boot不支持通过application.properties同时配置HTTP连接器和HTTPS连接器。如果你两个都想要,那就需要以编程的方式配置它们中的一个。推荐使用application.properties配置HTTPS,因为HTTP连接器是两个中最容易以编程方式进行配置的。获取示例可查看[spring-boot-sample-tomcat-multi-connectors](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors)示例项目。 - -* 配置Tomcat - -通常你可以遵循[Section 63.7, “Discover built-in options for external properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(这里主要的是`ServerProperties`)的建议,但也看下`EmbeddedServletContainerCustomizer`和各种你可以添加的Tomcat-specific的`*Customizers`。 - -Tomcat APIs相当丰富,一旦获取到`TomcatEmbeddedServletContainerFactory`,你就能够以多种方式修改它。或核心选择是添加你自己的`TomcatEmbeddedServletContainerFactory`。 - -* 启用Tomcat的多连接器(Multiple Connectors) - -你可以将一个`org.apache.catalina.connector.Connector`添加到`TomcatEmbeddedServletContainerFactory`,这就能够允许多连接器,比如HTTP和HTTPS连接器: -```java -@Bean -public EmbeddedServletContainerFactory servletContainer() { - TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); - 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); - } -} -``` -* 在前端代理服务器后使用Tomcat - -Spring Boot将自动配置Tomcat的`RemoteIpValve`,如果你启用它的话。这允许你透明地使用标准的`x-forwarded-for`和`x-forwarded-proto`头,很多前端代理服务器都会添加这些头信息(headers)。通过将这些属性中的一个或全部设置为非空的内容来开启该功能(它们是大多数代理约定的值,如果你只设置其中的一个,则另一个也会被自动设置)。 -```java -server.tomcat.remote_ip_header=x-forwarded-for -server.tomcat.protocol_header=x-forwarded-proto -``` -如果你的代理使用不同的头部(headers),你可以通过向application.properties添加一些条目来自定义该值的配置,比如: -```java -server.tomcat.remote_ip_header=x-your-remote-ip-header -server.tomcat.protocol_header=x-your-protocol-header -``` -该值也可以配置为一个默认的,能够匹配信任的内部代理的正则表达式。默认情况下,受信任的IP包括 10/8, 192.168/16, 169.254/16 和 127/8。可以通过向application.properties添加一个条目来自定义该值的配置,比如: -```java -server.tomcat.internal_proxies=192\\.168\\.\\d{1,3}\\.\\d{1,3} -``` -**注**:只有在你使用一个properties文件作为配置的时候才需要双反斜杠。如果你使用YAML,单个反斜杠就足够了,`192\.168\.\d{1,3}\.\d{1,3}`和上面的等价。 - -另外,通过在一个`TomcatEmbeddedServletContainerFactory` bean中配置和添加`RemoteIpValve`,你就可以完全控制它的设置了。 - -* 使用Jetty替代Tomcat - -Spring Boot starters(特别是spring-boot-starter-web)默认都是使用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:1.3.0.BUILD-SNAPSHOT") - compile("org.springframework.boot:spring-boot-starter-jetty:1.3.0.BUILD-SNAPSHOT") - // ... -} -``` -* 配置Jetty - -通常你可以遵循[Section 63.7, “Discover built-in options for external properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(此处主要是ServerProperties)的建议,但也要看下`EmbeddedServletContainerCustomizer`。Jetty API相当丰富,一旦获取到`JettyEmbeddedServletContainerFactory`,你就可以使用很多方式修改它。或更彻底地就是添加你自己的`JettyEmbeddedServletContainerFactory`。 - -* 使用Undertow替代Tomcat - -使用Undertow替代Tomcat和[使用Jetty替代Tomcat](https://github.com/qibaoguang/Spring-Boot-Reference-Guide/edit/master/How-to_%20guides.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:1.3.0.BUILD-SNAPSHOT") - compile 'org.springframework.boot:spring-boot-starter-undertow:1.3.0.BUILD-SNAPSHOT") - // ... -} - -``` -* 配置Undertow - -通常你可以遵循[Section 63.7, “Discover built-in options for external properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-discover-build-in-options-for-external-properties)关于`@ConfigurationProperties`(此处主要是ServerProperties和ServerProperties.Undertow),但也要看下`EmbeddedServletContainerCustomizer`。一旦获取到`UndertowEmbeddedServletContainerFactory`,你就可以使用一个`UndertowBuilderCustomizer`修改Undertow的配置以满足你的需求。或更彻底地就是添加你自己的`UndertowEmbeddedServletContainerFactory`。 - -* 启用Undertow的多监听器(Multiple Listeners) - -往`UndertowEmbeddedServletContainerFactory`添加一个`UndertowBuilderCustomizer`,然后添加一个监听者到`Builder`: -```java -@Bean -public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() { - UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory(); - factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(Builder builder) { - builder.addHttpListener(8080, "0.0.0.0"); - } - - }); - return factory; -} -``` -* 使用Tomcat7 - -Tomcat7可用于Spring Boot,但默认使用的是Tomcat8。如果不能使用Tomcat8(例如,你使用的是Java1.6),你需要改变classpath去引用Tomcat7。 - -- 通过Maven使用Tomcat7 - -如果正在使用starter pom和parent,你只需要改变Tomcat的version属性,比如,对于一个简单的webapp或service: -```xml - - 7.0.59 - - - ... - - org.springframework.boot - spring-boot-starter-web - - ... - -``` -- 通过Gradle使用Tomcat7 - -你可以通过设置`tomcat.version`属性改变Tomcat的版本: -```gradle -ext['tomcat.version'] = '7.0.59' -dependencies { - compile 'org.springframework.boot:spring-boot-starter-web' -} -``` -* 使用Jetty8 - -Jetty8可用于Spring Boot,但默认使用的是Jetty9。如果不能使用Jetty9(例如,因为你使用的是Java1.6),你只需改变classpath去引用Jetty8。你也需要排除Jetty的WebSocket相关的依赖。 - -- 通过Maven使用Jetty8 - -如果正在使用starter pom和parent,你只需添加Jetty starter,去掉WebSocket依赖,并改变version属性,比如,对于一个简单的webapp或service: -```xml - - 8.1.15.v20140411 - 2.2.0.v201112011158 - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-starter-jetty - - - org.eclipse.jetty.websocket - * - - - - -``` -- 通过Gradle使用Jetty8 - -你可以设置`jetty.version`属性并排除相关的WebSocket依赖,比如对于一个简单的webapp或service: -```gradle -ext['jetty.version'] = '8.1.15.v20140411' -dependencies { - compile ('org.springframework.boot:spring-boot-starter-web') { - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' - } - compile ('org.springframework.boot:spring-boot-starter-jetty') { - exclude group: 'org.eclipse.jetty.websocket' - } -} -``` -* 使用@ServerEndpoint创建WebSocket端点 - -如果想在一个使用内嵌容器的Spring Boot应用中使用@ServerEndpoint,你需要声明一个单独的ServerEndpointExporter @Bean: -```java -@Bean -public ServerEndpointExporter serverEndpointExporter() { - return new ServerEndpointExporter(); -} -``` -该bean将用底层的WebSocket容器注册任何的被`@ServerEndpoint`注解的beans。当部署到一个单独的servlet容器时,该角色将被一个servlet容器初始化方法履行,ServerEndpointExporter bean也就不是必需的了。 - -* 启用HTTP响应压缩 - -Spring Boot提供两种启用HTTP压缩的机制;一种是Tomcat特有的,另一种是使用一个filter,可以配合Jetty,Tomcat和Undertow。 - -- 启用Tomcat的HTTP响应压缩 - -Tomcat对HTTP响应压缩提供内建支持。默认是禁用的,但可以通过application.properties轻松的启用: -```java -server.tomcat.compression: on -``` -当设置为`on`时,Tomcat将压缩响应的长度至少为2048字节。你可以配置一个整型值来设置该限制而不只是`on`,比如: -```java -server.tomcat.compression: 4096 -``` -默认情况下,Tomcat只压缩某些MIME类型的响应(text/html,text/xml和text/plain)。你可以使用`server.tomcat.compressableMimeTypes`属性进行自定义,比如: -```java -server.tomcat.compressableMimeTypes=application/json,application/xml -``` -- 使用GzipFilter开启HTTP响应压缩 - -如果你正在使用Jetty或Undertow,或想要更精确的控制HTTP响应压缩,Spring Boot为Jetty的GzipFilter提供自动配置。虽然该过滤器是Jetty的一部分,但它也兼容Tomcat和Undertow。想要启用该过滤器,只需简单的为你的应用添加`org.eclipse.jetty:jetty-servlets`依赖。 - -GzipFilter可以使用`spring.http.gzip.*`属性进行配置。具体参考[GzipFilterProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/GzipFilterProperties.java)。 - -### Spring MVC - -* 编写一个JSON REST服务 - -在Spring Boot应用中,任何Spring `@RestController`默认应该渲染为JSON响应,只要classpath下存在Jackson2。例如: -```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 -响应头。 - -* 编写一个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`头部(或使用浏览器)。 - -* 自定义Jackson ObjectMapper - -在一个HTTP交互中,Spring MVC(客户端和服务端)使用HttpMessageConverters协商内容转换。如果classpath下存在Jackson,你就已经获取到Jackson2ObjectMapperBuilder提供的默认转换器。 - -创建的ObjectMapper(或用于Jackson XML转换的XmlMapper)实例默认有以下自定义属性: - -- `MapperFeature.DEFAULT_VIEW_INCLUSION`禁用 -- `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`禁用 - -Spring Boot也有一些简化自定义该行为的特性。 - -你可以使用当前的environment配置ObjectMapper和XmlMapper实例。Jackson提供一个扩展套件,可以用来简单的关闭或开启一些特性,你可以用它们配置Jackson处理的不同方面。这些特性在Jackson中使用5个枚举进行描述的,并被映射到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`| - -例如,设置`spring.jackson.serialization.indent_output=true`可以开启漂亮打印。注意,由于[松绑定](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-relaxed-binding)的使用,`indent_output`不必匹配对应的枚举常量`INDENT_OUTPUT`。 - -如果想彻底替换默认的ObjectMapper,你需要定义一个该类型的`@Bean`并将它标记为`@Primary`。 - -定义一个Jackson2ObjectMapperBuilder类型的`@Bean`将允许你自定义默认的ObjectMapper和XmlMapper(分别用于MappingJackson2HttpMessageConverter和MappingJackson2XmlHttpMessageConverter)。 - -另一种自定义Jackson的方法是向你的上下文添加`com.fasterxml.jackson.databind.Module`类型的beans。它们会被注册入每个ObjectMapper类型的bean,当为你的应用添加新特性时,这就提供了一种全局机制来贡献自定义模块。 - -最后,如果你提供任何MappingJackson2HttpMessageConverter类型的`@Beans`,那它们将替换MVC配置中的默认值。同时,也提供一个HttpMessageConverters类型的bean,它有一些有用的方法可以获取默认的和用户增强的message转换器。 - -想要获取更多细节可查看[Section 65.4, “Customize the @ResponseBody rendering”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-responsebody-rendering)和[WebMvcAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java)源码。 - -* 自定义@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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java)源码。 - -* 处理Multipart文件上传 - -Spring Boot采用Servlet 3 `javax.servlet.http.Part` API来支持文件上传。默认情况下,Spring Boot配置Spring MVC在单个请求中每个文件最大1Mb,最多10Mb的文件数据。你可以覆盖那些值,也可以设置临时文件存储的位置(比如,存储到`/tmp`文件夹下)及传递数据刷新到磁盘的阀值(通过使用MultipartProperties类暴露的属性)。如果你需要设置文件不受限制,例如,可以设置`multipart.maxFileSize`属性值为`-1`。 - -当你想要接收部分(multipart)编码文件数据作为Spring MVC控制器(controller)处理方法中被`@RequestParam`注解的MultipartFile类型的参数时,multipart支持就非常有用了。 - -具体参考[MultipartAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.java)源码。 - -* 关闭Spring MVC DispatcherServlet - -Spring Boot想要服务来自应用程序root `/`下的所有内容。如果你想将自己的servlet映射到该目录下也是可以的,但当然你可能失去一些Boot MVC特性。为了添加你自己的servlet,并将它映射到root资源,你只需声明一个Servlet类型的`@Bean`,并给它特定的bean名称`dispatcherServlet`(如果只想关闭但不替换它,你可以使用该名称创建不同类型的bean)。 - -* 关闭默认的MVC配置 - -完全控制MVC配置的最简单方式是提供你自己的被`@EnableWebMvc`注解的`@Configuration`。这样所有的MVC配置都逃不出你的掌心。 - -* 自定义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页面)。它在视图(view name)上应用了一个前缀和后缀(默认都为空,但你可以通过`spring.view.prefix`和`spring.view.suffix`外部配置设置),然后查找在servlet上下文中具有该路径的物理资源。可以通过提供相同类型的bean覆盖它。 -- id为`beanNameViewResolver`的BeanNameViewResolver。这是视图解析器链的一个非常有用的成员,它可以在View被解析时收集任何具有相同名称的beans。 -- id为`viewResolver`的ContentNegotiatingViewResolver只会在实际View类型的beans出现时添加。这是一个'主'解析器,它的职责会代理给其他解析器,它会尝试找到客户端发送的一个匹配'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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java),[ThymeleafAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[FreeMarkerAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[GroovyTemplateAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java),[VelocityAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java)。 - -### 日志 - -Spring Boot除了commons-logging API外没有其他强制性的日志依赖,你有很多可选的日志实现。想要使用[Logback](http://logback.qos.ch/),你需要包含它,及一些对classpath下commons-logging的绑定。最简单的方式是通过依赖`spring-boot-starter-logging`的starter pom。对于一个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`属性设置配置文件的位置。 - -* 配置Logback - -如果你将一个logback.xml放到classpath根目录下,那它将会被从这加载。Spring Boot提供一个默认的基本配置,如果你只是设置日志级别,那你可以包含它,比如: -```xml - - - - - -``` -如果查看spring-boot jar包中的默认logback.xml,你将会看到LoggingSystem为你创建的很多有用的系统属性,比如: -- ${PID},当前进程id -- ${LOG_FILE},如果在Boot外部配置中设置了`logging.file` -- ${LOG_PATH},如果设置了`logging.path`(表示日志文件产生的目录) - -Spring Boot也提供使用自定义的Logback转换器在控制台上输出一些漂亮的彩色ANSI日志信息(不是日志文件)。具体参考默认的`base.xml`配置。 - -如果Groovy在classpath下,你也可以使用logback.groovy配置Logback。 - -* 配置Log4j - -Spring Boot也支持[Log4j](http://logging.apache.org/log4j/1.2)或[Log4j 2](http://logging.apache.org/log4j/2.x)作为日志配置,但只有在它们中的某个在classpath下存在的情况。如果你正在使用starter poms进行依赖装配,这意味着你需要排除Logback,然后包含你选择的Log4j版本。如果你不使用starter poms,那除了你选择的Log4j版本外还要提供commons-logging(至少)。 - -最简单的方式可能就是通过starter poms,尽管它需要排除一些依赖,比如,在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-log4j - -``` -想要使用Log4j 2,只需要依赖`spring-boot-starter-log4j2`而不是`spring-boot-starter-log4j`。 - -**注**:使用Log4j各版本的starters都会收集好依赖以满足common logging的要求(比如,Tomcat中使用`java.util.logging`,但使用Log4j或 Log4j 2作为输出)。具体查看Actuator Log4j或Log4j 2的示例,了解如何将它用于实战。 - -* 使用YAML或JSON配置Log4j2 - -除了它的默认XML配置格式,Log4j 2也支持YAML和JSON配置文件。想要使用其他配置文件格式来配置Log4j 2,你需要添加合适的依赖到classpath。为了使用YAML,你需要添加`com.fasterxml.jackson.dataformat:jackson-dataformat-yaml`依赖,Log4j 2将查找名称为`log4j2.yaml`或`log4j2.yml`的配置文件。为了使用JSON,你需要添加`com.fasterxml.jackson.core:jackson-databind`依赖,Log4j 2将查找名称为`log4j2.json`或`log4j2.jsn`的配置文件 - -### 数据访问 - -* 配置一个数据源 - -想要覆盖默认的设置只需要定义一个你自己的DataSource类型的`@Bean`。Spring Boot提供一个工具构建类DataSourceBuilder,可用来创建一个标准的DataSource(如果它处于classpath下),或者仅创建你自己的DataSource,然后将它和在[Section 23.7.1, “Third-party configuration”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-3rd-party-configuration)解释的一系列Environment属性绑定。 - -比如: -```java -@Bean -@ConfigurationProperties(prefix="datasource.mine") -public DataSource dataSource() { - return new FancyDataSource(); -} -``` -```java -datasource.mine.jdbcUrl=jdbc:h2:mem:mydb -datasource.mine.user=sa -datasource.mine.poolSize=30 -``` -具体参考'Spring Boot特性'章节中的[Section 28.1, “Configure a DataSource”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-configure-datasource)和[DataSourceAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java)类源码。 - -* 配置两个数据源 - -创建多个数据源和创建第一个工作都是一样的。如果使用针对JDBC或JPA的默认自动配置,你可能想要将其中一个设置为`@Primary`(然后它就能被任何`@Autowired`注入获取)。 -```java -@Bean -@Primary -@ConfigurationProperties(prefix="datasource.primary") -public DataSource primaryDataSource() { - return DataSourceBuilder.create().build(); -} - -@Bean -@ConfigurationProperties(prefix="datasource.secondary") -public DataSource secondaryDataSource() { - return DataSourceBuilder.create().build(); -} -``` -* 使用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](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-jpa)或[Mongodb sample](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-mongodb)。 - -Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测你的`@Repository`定义的位置。想要获取更多控制,可以使用`@EnableJpaRepositories`注解(来自Spring Data JPA)。 - -* 从Spring配置分离`@Entity`定义 - -Spring Boot会基于它找到的`@EnableAutoConfiguration`来尝试猜测你的`@Entity`定义的位置。想要获取更多控制,你可以使用`@EntityScan`注解,比如: -```java -@Configuration -@EnableAutoConfiguration -@EntityScan(basePackageClasses=City.class) -public class Application { - - //... - -} -``` -* 配置JPA属性 - -Spring Data JPA已经提供了一些独立的配置选项(比如,针对SQL日志),并且Spring Boot会暴露它们,针对hibernate的外部配置属性也更多些。最常见的选项如下: -```java -spring.jpa.hibernate.ddl-auto: create-drop -spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.database: H2 -spring.jpa.show-sql: true -``` -(由于宽松的数据绑定策略,连字符或下划线作为属性keys作用应该是等效的)`ddl-auto`配置是个特殊情况,它有不同的默认设置,这取决于你是否使用一个内嵌数据库(create-drop)。当本地EntityManagerFactory被创建时,所有`spring.jpa.properties.*`属性都被作为正常的JPA属性(去掉前缀)传递进去了。 - -具体参考[HibernateJpaAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java)和[JpaBaseConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java)。 - -* 使用自定义的EntityManagerFactory - -为了完全控制EntityManagerFactory的配置,你需要添加一个名为`entityManagerFactory`的`@Bean`。Spring Boot自动配置会根据是否存在该类型的bean来关闭它的实体管理器(entity manager)。 - -* 使用两个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事物管理器生成它两个。 - -* 使用普通的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) - -* 使用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)。只需要改变对应注解的名称和标志。 - -* 将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)。如果需要提供其他定制,你可以创建一个继承自SpringBootRepositoryRestMvcConfiguration的`@Configuration`类。该类功能和RepositoryRestMvcConfiguration相同,但允许你继续使用`spring.data.rest.*`属性。 - -### 数据库初始化 - -一个数据库可以使用不同的方式进行初始化,这取决于你的技术栈。或者你可以手动完成该任务,只要数据库是单独的过程。 - -* 使用JPA初始化数据库 - -JPA有个生成DDL的特性,这些可以设置为在数据库启动时运行。这可以通过两个外部属性进行控制: - -- `spring.jpa.generate-ddl`(boolean)控制该特性的关闭和开启,跟实现者没关系 -- `spring.jpa.hibernate.ddl-auto`(enum)是一个Hibernate特性,用于更细力度的控制该行为。更多详情参考以下内容。 - -* 使用Hibernate初始化数据库 - -你可以显式设置`spring.jpa.hibernate.ddl-auto`,标准的Hibernate属性值有`none`,`validate`,`update`,`create`,`create-drop`。Spring Boot根据你的数据库是否为内嵌数据库来选择相应的默认值,如果是内嵌型的则默认值为`create-drop`,否则为`none`。通过查看Connection类型可以检查是否为内嵌型数据库,hsqldb,h2和derby是内嵌的,其他都不是。当从内存数据库迁移到一个真正的数据库时,你需要当心,在新的平台中不能对数据库表和数据是否存在进行臆断。你也需要显式设置`ddl-auto`,或使用其他机制初始化数据库。 - -此外,启动时处于classpath根目录下的import.sql文件会被执行。这在demos或测试时很有用,但在生产环境中你可能不期望这样。这是Hibernate的特性,和Spring没有一点关系。 - -* 使用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.continueOnError=true`禁用快速失败特性。一旦应用程序成熟并被部署了很多次,那该设置就很有用,因为脚本可以充当"可怜人的迁移"-例如,插入失败时意味着数据已经存在,也就没必要阻止应用继续运行。 - -如果你想要在一个JPA应用中使用schema.sql,那如果Hibernate试图创建相同的表,`ddl-auto=create-drop`将导致错误产生。为了避免那些错误,可以将`ddl-auto`设置为“”(推荐)或“none”。不管是否使用`ddl-auto=create-drop`,你总可以使用data.sql初始化新数据。 - -* 初始化Spring Batch数据库 - -如果你正在使用Spring Batch,那么它会为大多数的流行数据库平台预装SQL初始化脚本。Spring Boot会检测你的数据库类型,并默认执行那些脚本,在这种情况下将关闭快速失败特性(错误被记录但不会阻止应用启动)。这是因为那些脚本是可信任的,通常不会包含bugs,所以错误会被忽略掉,并且对错误的忽略可以让脚本具有幂等性。你可以使用`spring.batch.initializer.enabled=false`显式关闭初始化功能。 - -* 使用一个高级别的数据迁移工具 - -Spring Boot跟高级别的数据迁移工具[Flyway](http://flywaydb.org/)(基于SQL)和[Liquibase](http://www.liquibase.org/)(XML)工作的很好。通常我们倾向于Flyway,因为它一眼看去好像很容易,另外它通常不需要平台独立:一般一个或至多需要两个平台。 - -- 启动时执行Flyway数据库迁移 - -想要在启动时自动运行Flyway数据库迁移,需要将`org.flywaydb:flyway-core`添加到你的classpath下。 - -迁移是一些`V__.sql`格式的脚本(``是一个下划线分割的版本号,比如'1'或'2_1')。默认情况下,它们存放在一个`classpath:db/migration`的文件夹中,但你可以使用`flyway.locations`(一个列表)来改变它。详情可参考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)中提供了一个小的属性集,可用于禁止迁移,或关闭位置检测。 - -默认情况下,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),你可以作为参考。 - -- 启动时执行Liquibase数据库迁移 - -想要在启动时自动运行Liquibase数据库迁移,你需要将`org.liquibase:liquibase-core`添加到classpath下。 - -主改变日志(master change log)默认从`db/changelog/db.changelog-master.yaml`读取,但你可以使用`liquibase.change-log`进行设置。详情查看[LiquibaseProperties](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java)以获取可用设置,比如上下文,默认的schema等。 - -这里有个[Liquibase示例](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-liquibase)可作为参考。 - -### 批处理应用 - -* 在启动时执行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)。 - -### 执行器(Actuator) - -* 改变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 41.3, “Customizing the management server port”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-customizing-management-server-port)来获取更多详情。 - -* 自定义'白标'(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](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling)章节,了解下如何将处理器(handlers)注册到servlet容器中。 - -### 安全 - -* 关闭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章节)。 - -* 改变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. - } - -} -``` -* 当前端使用代理服务器时,启用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 -``` -(这些属性出现一个就会开启该功能,或者你可以通过添加一个TomcatEmbeddedServletContainerFactory bean自己添加RemoteIpValve) - -Spring Security也可以配置成针对所以或某些请求需要一个安全渠道(channel)。想要在一个Spring Boot应用中开启它,你只需将application.properties中的`security.require_ssl`设置为`true`即可。 - -### 热交换 - -* 重新加载静态内容 - -Spring Boot有很多用于热加载的选项。使用IDE开发是一个不错的方式,特别是需要调试的时候(所有的现代IDEs都允许重新加载静态资源,通常也支持对变更的Java类进行热交换)。[Maven和Gradle插件](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins)也支持命令行下的静态文件热加载。如果你使用其他高级工具编写css/js,并使用外部的css/js编译器,那你就可以充分利用该功能。 - -* 在不重启容器的情况下重新加载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自定义选项。 - -* 在不重启容器的情况下重新加载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自定义选项。 - -* 在不重启容器的情况下重新加载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自定义选项。 - -* 在不重启容器的情况下重新加载Velocity模板 - -如果你正在使用Velocity,那就将`spring.velocity.cache`设置为false。查看[VelocityAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfiguration.java)可以获取其他Velocity自定义选项。 - -* 在不重启容器的情况下重新加载Java类 - -现代IDEs(Eclipse, IDEA等)都支持字节码的热交换,所以如果你做了一个没有影响类或方法签名的改变,它会利索地重新加载并没有任何影响。 - -[Spring Loaded](https://github.com/spring-projects/spring-loaded)在这方面走的更远,它能够重新加载方法签名改变的类定义。如果对它进行一些自定义配置可以强制ApplicationContext刷新自己(但没有通用的机制来确保这对一个运行中的应用总是安全的,所以它可能只是一个开发时间的技巧)。 - -- 使用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中工作的相当漂亮,只要它们有相应的,和Maven默认一致的构建配置(Eclipse m2e对此支持的更好,开箱即用)。 - -- 使用Gradle和IntelliJ配置Spring Loaded - -如果想将Spring Loaded和Gradle,IntelliJ结合起来,那你需要付出代价。默认情况下,IntelliJ将类编译到一个跟Gradle不同的位置,这会导致Spring Loaded监控失败。 - -为了正确配置IntelliJ,你可以使用`idea` Gradle插件: -```gradle -buildscript { - repositories { jcenter() } - dependencies { - classpath "org.springframework.boot:spring-boot-gradle-plugin:1.3.0.BUILD-SNAPSHOT" - classpath 'org.springframework:springloaded:1.2.0.RELEASE' - } -} - -apply plugin: 'idea' - -idea { - module { - inheritOutputDirs = false - outputDir = file("$buildDir/classes/main/") - } -} - -// ... -``` -**注**:IntelliJ必须配置跟命令行Gradle任务相同的Java版本,并且springloaded必须作为一个buildscript依赖被包含进去。 - -此外,你也可以启用Intellij内部的`Make Project Automatically`,这样不管什么时候只要文件被保存都会自动编译你的代码。 - -### 构建 - -* 使用Maven自定义依赖版本 - -如果你使用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发布都是基于一些特定的第三方依赖集进行设计和测试的,覆盖版本可能导致兼容性问题。 - -* 使用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 - 1.3.0.BUILD-SNAPSHOT - - - - repackage - - - - - - -``` -查看[插件文档](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/usage.html)获取详细的用例。 - -* 创建其他的可执行JAR - -如果你想将自己的项目以library jar的形式被其他项目依赖,并且需要它是一个可执行版本(例如demo),你需要使用略微不同的方式来配置该构建。 - -对于Maven来说,正常的JAR插件和Spring Boot插件都有一个'classifier',你可以添加它来创建另外的JAR。示例如下(使用Spring Boot Starter Parent管理插件版本,其他配置采用默认设置): -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - -``` -上述配置会产生两个jars,默认的一个和使用带有classifier 'exec'的Boot插件构建的可执行的一个。 - -对于Gradle用户来说,步骤类似。示例如下: -```gradle -bootRepackage { - classifier = 'exec' -} -``` -* 在可执行jar运行时提取特定的版本 - -在一个可执行jar中,为了运行,多数内嵌的库不需要拆包(unpacked),然而有一些库可能会遇到问题。例如,JRuby包含它自己的内嵌jar,它假定`jruby-complete.jar`本身总是能够直接作为文件访问的。 - -为了处理任何有问题的库,你可以标记那些特定的内嵌jars,让它们在可执行jar第一次运行时自动解压到一个临时文件夹中。例如,为了将JRuby标记为使用Maven插件拆包,你需要添加如下的配置: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.jruby - jruby-complete - - - - - - -``` -使用Gradle完全上述操作: -```gradle -springBoot { - requiresUnpack = ['org.jruby:jruby-complete'] -} -``` -* 使用排除创建不可执行的JAR - -如果你构建的产物既有可执行的jar和非可执行的jar,那你常常需要为可执行的版本添加额外的配置文件,而这些文件在一个library jar中是不需要的。比如,application.yml配置文件可能需要从非可执行的JAR中排除。 - -下面是如何在Maven中实现: -```xml - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - maven-jar-plugin - - - exec - package - - jar - - - exec - - - - package - - jar - - - - true - - application.yml - - - - - - - -``` -在Gradle中,你可以使用标准任务的DSL(领域特定语言)特性创建一个新的JAR存档,然后在bootRepackage任务中使用withJarTask属性添加对它的依赖: -```gradle -jar { - baseName = 'spring-boot-sample-profile' - version = '0.0.0' - excludes = ['**/application.yml'] -} - -task('execJar', type:Jar, dependsOn: 'jar') { - baseName = 'spring-boot-sample-profile' - version = '0.0.0' - classifier = 'exec' - from sourceSets.main.output -} - -bootRepackage { - withJarTask = tasks['execJar'] -} -``` -* 远程调试一个使用Maven启动的Spring Boot项目 - -想要为使用Maven启动的Spring Boot应用添加一个远程调试器,你可以使用[mave插件](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/)的jvmArguments属性。详情参考[示例](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/examples/run-debug.html)。 - -* 远程调试一个使用Gradle启动的Spring Boot项目 - -想要为使用Gradle启动的Spring Boot应用添加一个远程调试器,你可以使用build.gradle的applicationDefaultJvmArgs属性或`--debug-jvm`命令行选项。 - -build.gradle: -```gradle -applicationDefaultJvmArgs = [ - "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005" -] -``` -命令行: -```shell -$ gradle run --debug-jvm -``` -详情查看[Gradle应用插件](http://www.gradle.org/docs/current/userguide/application_plugin.html)。 - -* 使用Ant构建可执行存档(archive) - -想要使用Ant进行构建,你需要抓取依赖,编译,然后像通常那样创建一个jar或war存档。为了让它可以执行: - -1. 使用合适的启动器配置`Main-Class`,比如对于jar文件使用JarLauncher,然后将其他需要的属性以manifest实体指定,主要是一个`Start-Class`。 -2. 将运行时依赖添加到一个内嵌的'lib'目录(对于jar),`provided`(内嵌容器)依赖添加到一个内嵌的`lib-provided`目录。记住***不要***压缩存档中的实体。 -3. 在存档的根目录添加`spring-boot-loader`类(这样`Main-Class`就可用了)。 - -示例: -```xml - - - - - - - - - - - - - - -``` -该Actuator示例中有一个build.xml文件,可以使用以下命令来运行: -```shell -$ ant -lib /ivy-2.2.jar -``` -在上述操作之后,你可以使用以下命令运行该应用: -```shell -$ java -jar target/*.jar -``` -* 如何使用Java6 - -如果想在Java6环境中使用Spring Boot,你需要改变一些配置。具体的变化取决于你应用的功能。 - -- 内嵌Servlet容器兼容性 - -如果你在使用Boot的内嵌Servlet容器,你需要使用一个兼容Java6的容器。Tomcat 7和Jetty 8都是Java 6兼容的。具体参考[Section 63.15, “Use Tomcat 7”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-tomcat-7)和[Section 63.16, “Use Jetty 8”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-use-jetty-8)。 - -- JTA API兼容性 - -Java事务API自身并不要求Java 7,而是官方的API jar包含的已构建类要求Java 7。如果你正在使用JTA,那么你需要使用能够在Java 6工作的构建版本替换官方的JTA 1.2 API jar。为了完成该操作,你需要排除任何对`javax.transaction:javax.transaction-api`的传递依赖,并使用`org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:1.0.0.Final`依赖替换它们。 - - -### 传统部署 - -* 创建一个可部署的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的packaging为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' - // … -} -``` -如果你使用[Spring Boot构建工具](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#build-tool-plugins),将内嵌容器依赖标记为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)。 - -* 为老的servlet容器创建一个可部署的war文件 - -老的Servlet容器不支持在Servlet 3.0中使用的ServletContextInitializer启动处理。你仍旧可以在这些容器使用Spring和Spring Boot,但你需要为应用添加一个web.xml,并将它配置为通过一个DispatcherServlet加载一个ApplicationContext。 - -* 将现有的应用转换为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的`@EnableAutoConfiguration`注解。示例: -```java -@Configuration -@EnableAutoConfiguration -@ComponentScan -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 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可以通过`@Import`添加到你的Application中。简单的情况下,大量使用注解配置可以在几行内定义`@Bean`定义。 - -一旦war可以使用,我们就通过添加一个main方法到Application来让它可以执行,比如: -```java -public static void main(String[] args) { - SpringApplication.run(Application.class, args); -} -``` -应用可以划分为多个类别: - -- 没有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应用,但你也可以选择其他方式。 - -* 部署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 - - - -``` -* 部署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/all in one/V. spring_boot_actuator.md b/all in one/V. spring_boot_actuator.md deleted file mode 100644 index 081d7d2c..00000000 --- a/all in one/V. spring_boot_actuator.md +++ /dev/null @@ -1,567 +0,0 @@ -###Spring Boot执行器:Production-ready特性 - -Spring Boot包含很多其他的特性,它们可以帮你监控和管理发布到生产环境的应用。你可以选择使用HTTP端点,JMX或远程shell(SSH或Telnet)来管理和监控应用。审计(Auditing),健康(health)和数据采集(metrics gathering)会自动应用到你的应用。 - -* 开启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 POM’的依赖。 - -**执行器(Actuator)的定义**:执行器是一个制造业术语,指的是用于移动或控制东西的一个机械装置。一个很小的改变就能让执行器产生大量的运动。 - -基于Maven的项目想要添加执行器只需添加下面的'starter'依赖: -```xml - - - org.springframework.boot - spring-boot-starter-actuator - - -``` -对于Gradle,使用下面的声明: -```java -dependencies { - compile("org.springframework.boot:spring-boot-starter-actuator") -} -``` -* 端点 - -执行器端点允许你监控应用及与应用进行交互。Spring Boot包含很多内置的端点,你也可以添加自己的。例如,health端点提供了应用的基本健康信息。 - -端点暴露的方式取决于你采用的技术类型。大部分应用选择HTTP监控,端点的ID映射到一个URL。例如,默认情况下,health端点将被映射到/health。 - -下面的端点都是可用的: - -| ID | 描述 |敏感(Sensitive)| -| ---- | :----- | :----- | -|autoconfig|显示一个auto-configuration的报告,该报告展示所有auto-configuration候选者及它们被应用或未被应用的原因|true| -|beans|显示一个应用中所有Spring Beans的完整列表|true| -|configprops|显示一个所有@ConfigurationProperties的整理列表|true| -|dump|执行一个线程转储|true| -|env|暴露来自Spring ConfigurableEnvironment的属性|true| -|health|展示应用的健康信息(当使用一个未认证连接访问时显示一个简单的'status',使用认证连接访问则显示全部信息详情)|false| -|info|显示任意的应用信息|false| -|metrics|展示当前应用的'指标'信息|true| -|mappings|显示一个所有@RequestMapping路径的整理列表|true| -|shutdown|允许应用以优雅的方式关闭(默认情况下不启用)|true| -|trace|显示trace信息(默认为最新的一些HTTP请求)|true| - -**注**:根据一个端点暴露的方式,sensitive参数可能会被用做一个安全提示。例如,在使用HTTP访问sensitive端点时需要提供用户名/密码(如果没有启用web安全,可能会简化为禁止访问该端点)。 - -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 -``` -2. 健康信息 - -健康信息可以用来检查应用的运行状态。它经常被监控软件用来提醒人们生产系统是否停止。health端点暴露的默认信息取决于端点是如何被访问的。对于一个非安全,未认证的连接只返回一个简单的'status'信息。对于一个安全或认证过的连接其他详细信息也会展示(具体参考[Section 41.6, “HTTP Health endpoint access restrictions” ]())。 - -健康信息是从你的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包含很多auto-configured的HealthIndicators,你也可以写自己的。 - -3. 安全与HealthIndicators - -HealthIndicators返回的信息常常性质上有点敏感。例如,你可能不想将数据库服务器的详情发布到外面。因此,在使用一个未认证的HTTP连接时,默认只会暴露健康状态(health status)。如果想将所有的健康信息暴露出去,你可以把endpoints.health.sensitive设置为false。 - -为防止'拒绝服务'攻击,Health响应会被缓存。你可以使用`endpoints.health.time-to-live`属性改变默认的缓存时间(1000毫秒)。 - -- 自动配置的HealthIndicators - -下面的HealthIndicators会被Spring Boot自动配置(在合适的时候): - -|名称|描述| -|----|:-----| -|[DiskSpaceHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicator.java)|低磁盘空间检测| -|[DataSourceHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java)|检查是否能从DataSource获取连接| -|[MongoHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/MongoHealthIndicator.java)|检查一个Mongo数据库是否可用(up)| -|[RabbitHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java)|检查一个Rabbit服务器是否可用(up)| -|[RedisHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RedisHealthIndicator.java)|检查一个Redis服务器是否可用(up)| -|[SolrHealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/SolrHealthIndicator.java)|检查一个Solr服务器是否可用(up)| - -- 编写自定义HealthIndicators - -想提供自定义健康信息,你可以注册实现了[HealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java)接口的Spring beans。你需要提供一个health()方法的实现,并返回一个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(); - } - -} -``` -除了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属性文件中: -```java -management.health.status.order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP -``` -如果使用HTTP访问health端点,你可能想要注册自定义的status,并使用HealthMvcEndpoint进行映射。例如,你可以将FATAL映射为HttpStatus.SERVICE_UNAVAILABLE。 - -4. 自定义应用info信息 - -通过设置Spring属性info.*,你可以定义info端点暴露的数据。所有在info关键字下的Environment属性都将被自动暴露。例如,你可以将下面的配置添加到application.properties: -```java -info.app.name=MyService -info.app.description=My awesome service -info.app.version=1.0.0 -``` -- 在构建时期自动扩展info属性 - -你可以使用已经存在的构建配置自动扩展info属性,而不是对在项目构建配置中存在的属性进行硬编码。这在Maven和Gradle都是可能的。 - -**使用Maven自动扩展属性** - -对于Maven项目,你可以使用资源过滤来自动扩展info属性。如果使用spring-boot-starter-parent,你可以通过`@..@`占位符引用Maven的'project properties'。 -```java -project.artifactId=myproject -project.name=Demo -project.version=X.X.X.X -project.description=Demo project for info endpoint -info.build.artifact=@project.artifactId@ -info.build.name=@project.name@ -info.build.description=@project.description@ -info.build.version=@project.version@ -``` -**注**:在上面的示例中,我们使用project.*来设置一些值以防止由于某些原因Maven的资源过滤没有开启。Maven目标`spring-boot:run`直接将`src/main/resources`添加到classpath下(出于热加载的目的)。这就绕过了资源过滤和自动扩展属性的特性。你可以使用`exec:java`替换该目标或自定义插件的配置,具体参考[plugin usage page](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/usage.html)。 - -如果你不使用starter parent,在你的pom.xml你需要添加(处于元素内): -```xml - - - src/main/resources - true - - -``` -和(处于内): -```xml - - org.apache.maven.plugins - maven-resources-plugin - 2.6 - - - @ - - - -``` -**使用Gradle自动扩展属性** - -通过配置Java插件的processResources任务,你也可以自动使用来自Gradle项目的属性扩展info属性。 -```java -processResources { - expand(project.properties) -} -``` -然后你可以通过占位符引用Gradle项目的属性: -```java -info.build.name=${name} -info.build.description=${description} -info.build.version=${version} -``` -- Git提交信息 - -info端点的另一个有用特性是,当项目构建完成后,它可以发布关于你的git源码仓库状态的信息。如果在你的jar中包含一个git.properties文件,git.branch和git.commit属性将被加载。 - -对于Maven用户,`spring-boot-starter-parent` POM包含一个能够产生git.properties文件的预配置插件。只需要简单的将下面的声明添加到你的POM中: -```xml - - - - pl.project13.maven - git-commit-id-plugin - - - -``` -对于Gradle用户可以使用一个相似的插件[gradle-git](https://github.com/ajoberstar/gradle-git),尽管为了产生属性文件可能需要稍微多点工作。 - -### 基于HTTP的监控和管理 - -如果你正在开发一个Spring MVC应用,Spring Boot执行器自动将所有启用的端点通过HTTP暴露出去。默认约定使用端点的id作为URL路径,例如,health暴露为/health。 - -* 保护敏感端点 - -如果你的项目中添加的有Spring Security,所有通过HTTP暴露的敏感端点都会受到保护。默认情况下会使用基本认证(basic authentication,用户名为user,密码为应用启动时在控制台打印的密码)。 - -你可以使用Spring属性改变用户名,密码和访问端点需要的安全角色。例如,你可能会在application.properties中添加下列配置: -```java -security.user.name=admin -security.user.password=secret -management.security.role=SUPERUSER -``` - -**注**:如果你不使用Spring Security,那你的HTTP端点就被公开暴露,你应该慎重考虑启用哪些端点。具体参考[Section 40.1, “Customizing endpoints”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-customizing-endpoints)。 - -* 自定义管理服务器的上下文路径 - -有时候将所有的管理端口划分到一个路径下是有用的。例如,你的应用可能已经将`/info`作为他用。你可以用`management.contextPath`属性为管理端口设置一个前缀: -```java -management.context-path=/manage -``` -上面的application.properties示例将把端口从`/{id}`改为`/manage/{id}`(比如,/manage/info)。 - -* 自定义管理服务器的端口 - -对于基于云的部署,使用默认的HTTP端口暴露管理端点(endpoints)是明智的选择。然而,如果你的应用是在自己的数据中心运行,那你可能倾向于使用一个不同的HTTP端口来暴露端点。 - -`management.port`属性可以用来改变HTTP端口: -```java -management.port=8081 -``` -由于你的管理端口经常被防火墙保护,不对外暴露也就不需要保护管理端点,即使你的主要应用是安全的。在这种情况下,classpath下会存在Spring Security库,你可以设置下面的属性来禁用安全管理策略(management security): -```java -management.security.enabled=false -``` -(如果classpath下不存在Spring Security,那也就不需要显示的以这种方式来禁用安全管理策略,它甚至可能会破坏应用程序。) - -* 自定义管理服务器的地址 - -你可以通过设置`management.address`属性来定义管理端点可以使用的地址。这在你只想监听内部或面向生产环境的网络,或只监听来自localhost的连接时非常有用。 - -下面的application.properties示例不允许远程管理连接: -```java -management.port=8081 -management.address=127.0.0.1 -``` - -* 禁用HTTP端点 - -如果不想使用HTTP暴露端点,你可以将管理端口设置为-1: -`management.port=-1` - -* HTTP Health端点访问限制 - -通过health端点暴露的信息根据是否为匿名访问而不同。默认情况下,当匿名访问时,任何有关服务器的健康详情都被隐藏了,该端点只简单的指示服务器是运行(up)还是停止(down)。此外,当匿名访问时,响应会被缓存一个可配置的时间段以防止端点被用于'拒绝服务'攻击。`endpoints.health.time-to-live`属性被用来配置缓存时间(单位为毫秒),默认为1000毫秒,也就是1秒。 - -上述的限制可以被禁止,从而允许匿名用户完全访问health端点。想达到这个效果,可以将`endpoints.health.sensitive`设为`false`。 - -### 基于JMX的监控和管理 - -Java管理扩展(JMX)提供了一种标准的监控和管理应用的机制。默认情况下,Spring Boot在`org.springframework.boot`域下将管理端点暴露为JMX MBeans。 - -* 自定义MBean名称 - -MBean的名称通常产生于端点的id。例如,health端点被暴露为`org.springframework.boot/Endpoint/HealthEndpoint`。 - -如果你的应用包含多个Spring ApplicationContext,你会发现存在名称冲突。为了解决这个问题,你可以将`endpoints.jmx.uniqueNames`设置为true,这样MBean的名称总是唯一的。 - -你也可以自定义JMX域,所有的端点都在该域下暴露。这里有个application.properties示例: -```java -endpoints.jmx.domain=myapp -endpoints.jmx.uniqueNames=true -``` -* 禁用JMX端点 - -如果不想通过JMX暴露端点,你可以将`spring.jmx.enabled`属性设置为false: -```java -spring.jmx.enabled=false -``` - -* 使用Jolokia通过HTTP实现JMX远程管理 - -Jolokia是一个JMX-HTTP桥,它提供了一种访问JMX beans的替代方法。想要使用Jolokia,只需添加`org.jolokia:jolokia-core`的依赖。例如,使用Maven需要添加下面的配置: -```xml - - org.jolokia - jolokia-core - -``` -在你的管理HTTP服务器上可以通过`/jolokia`访问Jolokia。 - -- 自定义Jolokia - -Jolokia有很多配置,传统上一般使用servlet参数进行设置。使用Spring Boot,你可以在application.properties中通过把参数加上`jolokia.config.`前缀来设置: -```java -jolokia.config.debug=true -``` -- 禁用Jolokia - -如果你正在使用Jolokia,但不想让Spring Boot配置它,只需要简单的将`endpoints.jolokia.enabled`属性设置为false: -```java -endpoints.jolokia.enabled=false -``` - -### 使用远程shell来进行监控和管理 - -Spring Boot支持集成一个称为'CRaSH'的Java shell。你可以在CRaSH中使用ssh或telnet命令连接到运行的应用。为了启用远程shell支持,你只需添加`spring-boot-starter-remote-shell`的依赖: -```xml - - org.springframework.boot - spring-boot-starter-remote-shell - -``` -**注**:如果想使用telnet访问,你还需添加对`org.crsh:crsh.shell.telnet`的依赖。 - -* 连接远程shell - -默认情况下,远程shell监听端口2000以等待连接。默认用户名为`user`,密码为随机生成的,并且在输出日志中会显示。如果应用使用Spring Security,该shell默认使用[相同的配置](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-security)。如果不是,将使用一个简单的认证策略,你可能会看到类似这样的信息: -```java -Using default password for shell access: ec03e16c-4cf4-49ee-b745-7c8255c1dd7e -``` -Linux和OSX用户可以使用`ssh`连接远程shell,Windows用户可以下载并安装[PuTTY](http://www.putty.org/)。 -```shell -$ ssh -p 2000 user@localhost - -user@localhost's password: - . ____ _ __ _ _ - /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ -( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ - \\/ ___)| |_)| | | | | || (_| | ) ) ) ) - ' |____| .__|_| |_|_| |_\__, | / / / / - =========|_|==============|___/=/_/_/_/ - :: Spring Boot :: (v1.3.0.BUILD-SNAPSHOT) on myhost -``` -输入help可以获取一系列命令的帮助。Spring boot提供`metrics`,`beans`,`autoconfig`和`endpoint`命令。 - -- 远程shell证书 - -你可以使用`shell.auth.simple.user.name`和`shell.auth.simple.user.password`属性配置自定义的连接证书。也可以使用Spring Security的AuthenticationManager处理登录职责。具体参考Javadoc[CrshAutoConfiguration](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/api/org/springframework/boot/actuate/autoconfigure/CrshAutoConfiguration.html)和[ShellProperties](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/api/org/springframework/boot/actuate/autoconfigure/ShellProperties.html)。 - -* 扩展远程shell - -有很多有趣的方式可以用来扩展远程shell。 - -- 远程shell命令 - -你可以使用Groovy或Java编写其他的shell命令(具体参考CRaSH文档)。默认情况下,Spring Boot会搜索以下路径的命令: -1. `classpath*:/commands/**` -2. `classpath*:/crash/commands/**` - -**注**:可以通过`shell.commandPathPatterns`属性改变搜索路径。 - -下面是一个从`src/main/resources/commands/hello.groovy`加载的'hello world'命令: -```java -package commands - -import org.crsh.cli.Usage -import org.crsh.cli.Command - -class hello { - - @Usage("Say Hello") - @Command - def main(InvocationContext context) { - return "Hello" - } - -} -``` -Spring Boot将一些额外属性添加到了InvocationContext,你可以在命令中访问它们: - -|属性名称|描述| -|------|:------| -|spring.boot.version|Spring Boot的版本| -|spring.version|Spring框架的核心版本| -|spring.beanfactory|获取Spring的BeanFactory| -|spring.environment|获取Spring的Environment| - -- 远程shell插件 - -除了创建新命令,也可以扩展CRaSH shell的其他特性。所有继承`org.crsh.plugin.CRaSHPlugin`的Spring Beans将自动注册到shell。 - -具体查看[CRaSH参考文档](http://www.crashub.org/)。 - -### 度量指标(Metrics) - -Spring Boot执行器包括一个支持'gauge'和'counter'级别的度量指标服务。'gauge'记录一个单一值;'counter'记录一个增量(增加或减少)。同时,Spring Boot提供一个[PublicMetrics](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/PublicMetrics.java)接口,你可以实现它,从而暴露以上两种机制不能记录的指标。具体参考[SystemPublicMetrics](http://github.com/spring-projects/spring-boot/tree/master/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)响应。双asterix(star-star)来自于被Spring MVC `/**`匹配到的一个请求(通常为一个静态资源)。 - -`gauge`级别展示了一个请求的最后响应时间。所以,`root`的最后请求被响应耗时2毫秒,`/metrics`耗时3毫秒。 - -* 系统指标 - -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) - -* 数据源指标 - -Spring Boot会为你应用中定义的支持的DataSource暴露以下指标: -- 最大连接数(datasource.xxx.max) -- 最小连接数(datasource.xxx.min) -- 活动连接数(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。 - -* Tomcat session指标 - -如果你使用Tomcat作为内嵌的servlet容器,session指标将被自动暴露出去。`httpsessions.active`和`httpsessions.max`提供了活动的和最大的session数量。 - -* 记录自己的指标 - -想要记录你自己的指标,只需将[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)的指南。 - -* 添加你自己的公共指标 - -想要添加额外的,每次指标端点被调用时都会重新计算的度量指标,只需简单的注册其他的PublicMetrics实现bean(s)。默认情况下,端点会聚合所有这样的beans,通过定义自己的MetricsEndpoint可以轻易改变这种情况。 - -* 指标仓库 - -通过绑定一个[MetricRepository](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/MetricRepository.java)来实现指标服务。`MetricRepository`负责存储和追溯指标信息。Spring Boot提供一个`InMemoryMetricRepository`和一个`RedisMetricRepository`(默认使用in-memory仓库),不过你可以编写自己的`MetricRepository`。`MetricRepository`接口实际是`MetricReader`接口和`MetricWriter`接口的上层组合。具体参考[Javadoc](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/api/org/springframework/boot/actuate/metrics/repository/MetricRepository.html) - -没有什么能阻止你直接将`MetricRepository`的数据导入应用中的后端存储,但我们建议你使用默认的`InMemoryMetricRepository`(如果担心堆使用情况,你可以使用自定义的Map实例),然后通过一个scheduled export job填充后端仓库(意思是先将数据保存到内存中,然后通过异步job将数据持久化到数据库,可以提高系统性能)。通过这种方式,你可以将指标数据缓存到内存中,然后通过低频率或批量导出来减少网络拥堵。Spring Boot提供一个`Exporter`接口及一些帮你开始的基本实现。 - -* Dropwizard指标 - -[Dropwizard ‘Metrics’库](https://dropwizard.github.io/metrics/)的用户会发现Spring Boot指标被发布到了`com.codahale.metrics.MetricRegistry`。当你声明对`io.dropwizard.metrics:metrics-core`库的依赖时会创建一个默认的`com.codahale.metrics.MetricRegistry` Spring bean;如果需要自定义,你可以注册自己的@Bean实例。来自于`MetricRegistry`的指标也是自动通过`/metrics`端点暴露的。 - -用户可以通过使用合适类型的指标名称作为前缀来创建Dropwizard指标(比如,`histogram.*`, `meter.*`)。 - -* 消息渠道集成 - -如果你的classpath下存在'Spring Messaging' jar,一个名为`metricsChannel`的`MessageChannel`将被自动创建(除非已经存在一个)。此外,所有的指标更新事件作为'messages'发布到该渠道上。订阅该渠道的客户端可以进行额外的分析或行动。 - -### 审计 - -Spring Boot执行器具有一个灵活的审计框架,一旦Spring Security处于活动状态(默认抛出'authentication success','failure'和'access denied'异常),它就会发布事件。这对于报告非常有用,同时可以基于认证失败实现一个锁定策略。 - -你也可以使用审计服务处理自己的业务事件。为此,你可以将存在的`AuditEventRepository`注入到自己的组件,并直接使用它,或者只是简单地通过Spring `ApplicationEventPublisher`发布`AuditApplicationEvent`(使用`ApplicationEventPublisherAware`)。 - -### 追踪(Tracing) - -对于所有的HTTP请求Spring Boot自动启用追踪。你可以查看`trace`端点,并获取最近一些请求的基本信息: -```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, - ... -}] -``` -- 自定义追踪 - -如果需要追踪其他的事件,你可以将一个[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`方法接收一个将被转化为JSON的`Map`结构,该数据将被记录下来。 - -默认情况下,使用的`InMemoryTraceRepository`将存储最新的100个事件。如果需要扩展该容量,你可以定义自己的`InMemoryTraceRepository`实例。如果需要,你可以创建自己的替代`TraceRepository`实现。 - -### 进程监控 - -在Spring Boot执行器中,你可以找到几个创建有利于进程监控的文件的类: -- `ApplicationPidFileWriter`创建一个包含应用PID的文件(默认位于应用目录,文件名为application.pid) -- `EmbeddedServerPortFileWriter`创建一个或多个包含内嵌服务器端口的文件(默认位于应用目录,文件名为application.port) - -默认情况下,这些writers没有被激活,但你可以使用下面描述的任何方式来启用它们。 - -* 扩展属性 - -你需要激活`META-INF/spring.factories`文件里的listener(s): -```java -org.springframework.context.ApplicationListener=\ -org.springframework.boot.actuate.system.ApplicationPidFileWriter, -org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter -``` - -* 以编程方式 - -你也可以通过调用`SpringApplication.addListeners(…)`方法来激活一个监听器,并传递相应的`Writer`对象。该方法允许你通过`Writer`构造器自定义文件名和路径。 diff --git a/all in one/VI. deploying_to_the_cloud.md b/all in one/VI. deploying_to_the_cloud.md deleted file mode 100644 index 3701a928..00000000 --- a/all in one/VI. deploying_to_the_cloud.md +++ /dev/null @@ -1,182 +0,0 @@ -### 部署到云端 - -对于大多数流行云PaaS(平台即服务)提供商,Spring Boot的可执行jars就是为它们准备的。这些提供商往往要求你带上自己的容器;它们管理应用的进程(不特别针对Java应用程序),所以它们需要一些中间层来将你的应用适配到云概念中的一个运行进程。 - -两个流行的云提供商,Heroku和Cloud Foundry,采取一个打包('buildpack')方法。为了启动你的应用程序,不管需要什么,buildpack都会将它们打包到你的部署代码:它可能是一个JDK和一个java调用,也可能是一个内嵌的webserver,或者是一个成熟的应用服务器。buildpack是可插拔的,但你最好尽可能少的对它进行自定义设置。这可以减少不受你控制的功能范围,最小化部署和生产环境的发散。 - -理想情况下,你的应用就像一个Spring Boot可执行jar,所有运行需要的东西都打包到它内部。 - -* Cloud Foundry - -如果不指定其他打包方式,Cloud Foundry会启用它提供的默认打包方式。Cloud Foundry的[Java buildpack](https://github.com/cloudfoundry/java-buildpack)对Spring应用有出色的支持,包括Spring Boot。你可以部署独立的可执行jar应用,也可以部署传统的.war形式的应用。 - -一旦你构建了应用(比如,使用`mvn clean package`)并[安装](http://docs.cloudfoundry.org/devguide/installcf/install-go-cli.html)了cf[命令行工具](http://docs.cloudfoundry.org/devguide/installcf/install-go-cli.html),你可以使用下面的`cf push`命令(将路径指向你编译后的.jar)来部署应用。在发布一个应用前,确保你已登陆cf命令行客户端。 -```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 -Preparing to start acloudyspringtime... OK ------> Downloaded app package (8.9M) ------> Java Buildpack source: system ------> Downloading Open JDK 1.7.0_51 from .../x86_64/openjdk-1.7.0_51.tar.gz (1.8s) - Expanding Open JDK to .java-buildpack/open_jdk (1.2s) ------> Downloading Spring Auto Reconfiguration from 0.8.7 .../auto-reconfiguration-0.8.7.jar (0.1s) ------> Uploading droplet (44M) -Checking status of app 'acloudyspringtime'... - 0 of 1 instances running (1 starting) - ... - 0 of 1 instances running (1 down) - ... - 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/)。 - -- 绑定服务 - -默认情况下,运行应用的元数据和服务连接信息被暴露为应用的环境变量(比如,$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)和服务信息(比如数据库证书)。具体参考VcapApplicationListener Javadoc。 - -**注**:[Spring Cloud Connectors](http://cloud.spring.io/spring-cloud-connectors/)项目很适合比如配置数据源的任务。Spring Boot提供自动配置支持和一个`spring-boot-starter-cloud-connectors` starter POM。 - -* Heroku - -Heroku是另外一个流行的Paas平台。想要自定义Heroku的构建过程,你可以提供一个`Procfile`,它提供部署一个应用所需的指令。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默认使用Java 1.6。只要你的Maven或Gradle构建时使用相同的版本就没问题(Maven用户可以设置`java.version`属性)。如果你想使用JDK 1.7,在你的pom.xml和Procfile临近处创建一个system.properties文件。在该文件中添加以下设置: -```java -java.runtime.version=1.7 -``` -这就是你需要做的一切。对于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.7... done ------> Installing Maven 3.2.3... 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。 - -* 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构建运行的应用可以参考它。由于一个[Gradle bug](http://issues.gradle.org/browse/GRADLE-2871),你不能使用高于1.6版本的Gradle。 - -* Google App Engine - -Google App Engine跟Servlet 2.5 API是有联系的,所以在不修改的情况系你是不能部署一个Spring应用的。具体查看本指南的[Servlet 2.5章节](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-servlet-2-5)。 diff --git a/all in one/VII. spring_boot_cli.md b/all in one/VII. spring_boot_cli.md deleted file mode 100644 index 8cca2501..00000000 --- a/all in one/VII. spring_boot_cli.md +++ /dev/null @@ -1,286 +0,0 @@ -### Spring Boot CLI - -Spring Boot CLI是一个命令行工具,如果想使用Spring进行快速开发可以使用它。它允许你运行Groovy脚本,这意味着你可以使用熟悉的类Java语法,并且没有那么多的模板代码。你也可以启动一个新的工程或为Spring Boot CLI编写自己的命令。 - -### 安装CLI - -你可以手动安装Spring Boot CLI,也可以使用GVM(Groovy环境管理工具)或Homebrew,MacPorts(如果你是一个OSX用户)。参考"Getting started"的[Section 10.2, “Installing the Spring Boot CLI” ](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-the-cli)可以看到全面的安装指令。 - -### 使用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 v1.3.0.BUILD-SNAPSHOT -``` -* 使用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 -``` -想要设置JVM命令行参数,你可以使用`JAVA_OPTS`环境变量,例如: -```shell -$ JAVA_OPTS=-Xmx1024m spring run hello.groovy -``` -- 推断"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|Caching abstraction| -|@Test|JUnit| -|@EnableRabbit|RabbitMQ| -|@EnableReactor|Project Reactor| -|继承Specification|Spock test| -|@EnableBatchProcessing|Spring Batch| -|@MessageEndpoint,@EnableIntegrationPatterns|Spring Integration| -|@EnableDeviceResolver|Spring Mobile| -|@Controller,@RestController,@EnableWebMvc|Spring MVC + Embedded 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)子类。 - -- 推断"grab"坐标 - -Spring Boot扩展Groovy标准"@Grab"注解使其能够允许你指定一个没有group或version的依赖,例如`@Grab('freemarker')`。 -artifact’s的组和版本是通过查看Spring Boot的依赖元数据推断出来的。注意默认的元数据是和你使用的CLI版本绑定的-只有在你迁移到一个CLI新版本时它才会改变,这样当你的依赖改变时你就可以控制了。在[附录](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#appendix-dependency-versions)的表格中可以查看默认元数据包含的依赖和它们的版本。 - -- 默认import语句 - -为了帮助你减少Groovy代码量,一些`import`语句被自动包含进来了。注意上面的示例中引用`@Component`,`@RestController`和`@RequestMapping`而没有使用全限定名或`import`语句。 - -**注**:很多Spring注解在不使用`import`语句的情况下可以正常工作。尝试运行你的应用,看一下在添加imports之前哪些会失败。 - -- 自动创建main方法 - -跟等效的Java应用不同,你不需要在Groovy脚本中添加一个`public static void main(String[] args)`方法。Spring Boot 会使用你编译后的代码自动创建一个SpringApplication。 - -- 自定义"grab"元数据 - -Spring Boot提供一个新的`@GrabMetadata`注解,你可以使用它提供自定义的依赖元数据,以覆盖Spring Boot的默认配置。该元数据通过使用提供一个或多个配置文件坐标的注解来指定(使用一个属性标识符"type"部署到Maven仓库).。配置文件中的每个实体必须遵循`group:module=version`的格式。 - -例如,下面的声明: -```java -`@GrabMetadata("com.example.custom-versions:1.0.0")` -``` -将会加载Maven仓库处于`com/example/custom-versions/1.0.0/`下的`custom-versions-1.0.0.properties`文件。 - -可以通过注解指定多个属性文件,它们会以声明的顺序被使用。例如: -```java -`@GrabMetadata(["com.example.custom-versions:1.0.0", - "com.example.more-versions:1.0.0"])` -``` -意味着位于`more-versions`的属性将覆盖位于`custom-versions`的属性。 - -你可以在任何能够使用`@Grab`的地方使用`@GrabMetadata`,然而,为了确保元数据的顺序一致,你在应用程序中最多只能使用一次`@GrabMetadata`。[Spring IO Platform](http://platform.spring.io/)是一个非常有用的依赖元数据源(Spring Boot的超集),例如: -```java -@GrabMetadata('io.spring.platform:platform-versions:1.0.4.RELEASE') -``` -* 测试你的代码 - -`test`命令允许你编译和运行应用程序的测试用例。常规使用方式如下: -```shell -$ spring test app.groovy tests.groovy -Total: 1, Success: 1, : Failures: 0 -Passed? true -``` -在这个示例中,`test.groovy`包含JUnit `@Test`方法或Spock `Specification`类。所有的普通框架注解和静态方法在不使用import导入的情况下,仍旧可以使用。 - -下面是我们使用的`test.groovy`文件(含有一个JUnit测试): -```java -class ApplicationTests { - - @Test - void homeSaysHello() { - assertEquals("Hello World!", new WebApplication().home()) - } - -} -``` -**注**:如果有多个测试源文件,你可以倾向于使用一个test目录来组织它们。 - -* 多源文件应用 - -你可以在所有接收文件输入的命令中使用shell通配符。这允许你轻松处理来自一个目录下的多个文件,例如: -```shell -$ spring run *.groovy -``` -如果你想将'test'或'spec'代码从主应用代码中分离,这项技术就十分有用了: -```shell -$ spring test app/*.groovy test/*.groovy -``` -* 应用打包 - -你可以使用`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`可以获得更多信息。 - -* 初始化新工程 - -`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' -``` -* 使用内嵌shell - -Spring Boot包括完整的BASH和zsh shells的命令行脚本。如果你不使用它们中的任何一个(可能你是一个Window用户),那你可以使用`shell`命令启用一个集成shell。 -```shell -$ spring shell -Spring Boot (v1.3.0.BUILD-SNAPSHOT) -Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit. -``` -从内嵌shell中可以直接运行其他命令: -```shell -$ version -Spring CLI v1.3.0.BUILD-SNAPSHOT -``` -内嵌shell支持ANSI颜色输出和tab补全。如果需要运行一个原生命令,你可以使用`$`前缀。点击ctrl-c将退出内嵌shell。 - -* 为CLI添加扩展 - -使用`install`命令可以为CLI添加扩展。该命令接收一个或多个格式为`group:artifact:version`的artifact坐标集。例如: -```shell -$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE -``` -除了安装你提供坐标的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 -``` -* 使用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/all in one/VIII. build_tool_plugins.md b/all in one/VIII. build_tool_plugins.md deleted file mode 100644 index 15137588..00000000 --- a/all in one/VIII. build_tool_plugins.md +++ /dev/null @@ -1,425 +0,0 @@ -### 构建工具插件 - -Spring Boot为Maven和Gradle提供构建工具插件。该插件提供各种各样的特性,包括打包可执行jars。本节提供关于插件的更多详情及用于扩展一个不支持的构建系统所需的帮助信息。如果你是刚刚开始,那可能需要先阅读[Part III, “Using Spring Boot”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot)章节的[“Chapter 13, Build systems”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-build-systems)。 - -### Spring Boot Maven插件 - -[Spring Boot Maven插件](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-build-systems)为Maven提供Spring Boot支持,它允许你打包可执行jar或war存档,然后就地运行应用。为了使用它,你需要使用Maven 3.2 (或更高版本)。 - -**注**:参考[Spring Boot Maven Plugin Site](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/)可以获取全部的插件文档。 - -* 包含该插件 - -想要使用Spring Boot Maven插件只需简单地在你的pom.xml的`plugins`部分包含相应的XML: -```xml - - - 4.0.0 - - - - - org.springframework.boot - spring-boot-maven-plugin - 1.3.0.BUILD-SNAPSHOT - - - - 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 - - -``` -* 打包可执行jar和war文件 - -一旦`spring-boot-maven-plugin`被包含到你的pom.xml中,它就会自动尝试使用`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 74.1, “Create a deployable war file”” ](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-create-a-deployable-war-file)章节。 - -在[插件信息页面](http://docs.spring.io/spring-boot/docs/1.3.0.BUILD-SNAPSHOT/maven-plugin/)有高级的配置选项和示例。 - -### Spring Boot Gradle插件 - -Spring Boot Gradle插件为Gradle提供Spring Boot支持,它允许你打包可执行jar或war存档,运行Spring Boot应用,对于"神圣的"依赖可以在你的build.gradle文件中省略版本信息。 - -* 包含该插件 - -想要使用Spring Boot Gradle插件,你只需简单的包含一个`buildscript`依赖,并应用`spring-boot`插件: -```gradle -buildscript { - dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.BUILD-SNAPSHOT") - } -} -apply plugin: 'spring-boot' -``` -如果想使用一个里程碑或快照版本,你可以添加相应的repositories引用: -```gradle -buildscript { - repositories { - maven.url "http://repo.spring.io/snapshot" - maven.url "http://repo.spring.io/milestone" - } - // ... -} -``` -* 声明不带版本的依赖 - -`spring-boot`插件会为你的构建注册一个自定义的Gradle `ResolutionStrategy`,它允许你在声明对"神圣"的artifacts的依赖时获取版本号。为了充分使用该功能,只需要想通常那样声明依赖,但将版本号设置为空: -```gradle -dependencies { - compile("org.springframework.boot:spring-boot-starter-web") - compile("org.thymeleaf:thymeleaf-spring4") - compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect") -} -``` -**注**:你声明的`spring-boot` Gradle插件的版本决定了"blessed"依赖的实际版本(确保可以重复构建)。你最好总是将`spring-boot` gradle插件版本设置为你想用的Spring Boot实际版本。提供的版本详细信息可以在[附录](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#appendix-dependency-versions)中找到。 - -`spring-boot`插件对于没有指定版本的依赖只会提供一个版本。如果不想使用插件提供的版本,你可以像平常那样在声明依赖的时候指定版本。例如: -```gradle -dependencies { - compile("org.thymeleaf:thymeleaf-spring4:2.1.1.RELEASE") -} -``` -* 自定义版本管理 - -如果你需要不同于Spring Boot的"blessed"依赖,有可能的话可以自定义`ResolutionStrategy`使用的版本。替代的版本元数据使用`versionManagement`配置。例如: -```gradle -dependencies { - versionManagement("com.mycorp:mycorp-versions:1.0.0.RELEASE@properties") - compile("org.springframework.data:spring-data-hadoop") -} -``` -版本信息需要作为一个`.properties`文件发布到一个仓库中。对于上面的示例,`mycorp-versions.properties`文件可能包含以下内容: -```java -org.springframework.data\:spring-data-hadoop=2.0.0.RELEASE -``` -属性文件优先于Spring Boot默认设置,如果有必要的话可以覆盖版本号。 - -* 默认排除规则 - -Gradle处理"exclude rules"的方式和Maven稍微有些不同,在使用starter POMs时这可能会引起无法预料的结果。特别地,当一个依赖可以通过不同的路径访问时,对该依赖声明的exclusions将不会生效。例如,如果一个starter POM声明以下内容: -```xml - - - org.springframework - spring-core - 4.0.5.RELEASE - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - 4.0.5.RELEASE - - -``` -`commons-logging` jar不会被Gradle排除,因为通过没有`exclusion`元素的`spring-context`可以传递性的拉取到它(spring-context → spring-core → commons-logging)。 - -为了确保正确的排除被实际应用,Spring Boot Gradle插件将自动添加排除规则。所有排除被定义在`spring-boot-dependencies` POM,并且针对"starter" POMs的隐式规则也会被添加。 - -如果不想自动应用排除规则,你可以使用以下配置: -```gradle -springBoot { - applyExcludeRules=false -} -``` -* 打包可执行jar和war文件 - -一旦`spring-boot`插件被应用到你的项目,它将使用`bootRepackage`任务自动尝试重写存档以使它们能够执行。为了构建一个jar或war,你需要按通常的方式配置项目。 - -你想启动的main类既可以通过一个配置选项指定,也可以通过向manifest添加一个`Main-Class`属性。如果你没有指定main类,该插件会搜索带有`public static void main(String[] args)`方法的类。 - -为了构建和运行一个项目artifact,你可以输入以下内容: -```shell -$ gradle build -$ java -jar build/libs/mymodule-0.0.1-SNAPSHOT.jar -``` -为了构建一个即能执行也可以部署到外部容器的war包,你需要将内嵌容器依赖标记为"providedRuntime",比如: -```gradle -... -apply plugin: 'war' - -war { - baseName = 'myapp' - version = '0.5.0' -} - -repositories { - jcenter() - maven { url "http://repo.spring.io/libs-snapshot" } -} - -configurations { - providedRuntime -} - -dependencies { - compile("org.springframework.boot:spring-boot-starter-web") - providedRuntime("org.springframework.boot:spring-boot-starter-tomcat") - ... -} -``` -**注**:具体参考[“Section 74.1, “Create a deployable war file””](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-create-a-deployable-war-file)。 - -* 就地(in-place)运行项目 - -为了在不先构建jar的情况下运行项目,你可以使用"bootRun"任务: -```shell -$ gradle bootRun -``` -默认情况下,以这种方式运行项目可以让你的静态classpath资源(比如,默认位于`src/main/resources`下)在应用运行期间被重新加载。使静态资源可以重新加载意味着`bootRun`任务不会使用`processResources`任务的输出,比如,当调用`bootRun`时,你的应用将以资源未处理的形式来使用它们。 - -你可以禁止直接使用静态classpath资源。这意味着资源不再是可重新加载的,但`processResources`任务的输出将会被使用。想要这样做,只需将`bootRun`任务的`addResources`设为false: -```gradle -bootRun { - addResources = false -} -``` -* Spring Boot插件配置 - -Gradle插件自动扩展你的构建脚本DSL,它为脚本添加一个`springBoot`元素以此作为Boot插件的全局配置。你可以像配置其他Gradle扩展那样为`springBoot`设置相应的属性(下面有配置选项列表)。 -```gradle -springBoot { - backupSource = false -} -``` -* Repackage配置 - -该插件添加了一个`bootRepackage`任务,你可以直接配置它,比如: -```gradle -bootRepackage { - mainClass = 'demo.Application' -} -``` -下面是可用的配置选项: - -|名称|描述| -|-------|:------| -|enabled|布尔值,用于控制repackager的开关(如果你只想要Boot的其他特性而不是这个,那它就派上用场了)| -|mainClass|要运行的main类。如果没有指定,则使用project属性`mainClassName`。如果没有定义`mainClassName` id,则搜索存档以寻找一个合适的类。"合适"意味着一个唯一的,具有良好格式的`main()`方法的类(如果找到多个则构建会失败)。你也可以通过"run"任务(`main`属性)指定main类的名称,和/或将"startScripts"(`mainClassName`属性)作为"springBoot"配置的替代。| -|classifier|添加到存档的一个文件名字段(在扩展之前),这样最初保存的存档仍旧存放在最初的位置。在存档被重新打包(repackage)的情况下,该属性默认为null。默认值适用于多数情况,但如果你想在另一个项目中使用原jar作为依赖,最好使用一个扩展来定义该可执行jar| -|withJarTask|`Jar`任务的名称或值,用于定位要被repackage的存档| -|customConfiguration|自定义配置的名称,用于填充内嵌的lib目录(不指定该属性,你将获取所有编译和运行时依赖)| - -* 使用Gradle自定义配置进行Repackage - -有时候不打包解析自`compile`,`runtime`和`provided`作用域的默认依赖可能更合适些。如果创建的可执行jar被原样运行,你需要将所有的依赖内嵌进该jar中;然而,如果目的是explode一个jar文件,并手动运行main类,你可能在`CLASSPATH`下已经有一些可用的库了。在这种情况下,你可以使用不同的依赖集重新打包(repackage)你的jar。 - -使用自定义的配置将自动禁用来自`compile`,`runtime`和`provided`作用域的依赖解析。自定义配置即可以定义为全局的(处于`springBoot`部分内),也可以定义为任务级的。 -```gradle -task clientJar(type: Jar) { - appendix = 'client' - from sourceSets.main.output - exclude('**/*Something*') -} - -task clientBoot(type: BootRepackage, dependsOn: clientJar) { - withJarTask = clientJar - customConfiguration = "mycustomconfiguration" -} -``` -在以上示例中,我们创建了一个新的`clientJar` Jar任务从你编译后的源中打包一个自定义文件集。然后我们创建一个新的`clientBoot` BootRepackage任务,并让它使用`clientJar`任务和`mycustomconfiguration`。 -```gradle -configurations { - mycustomconfiguration.exclude group: 'log4j' -} - -dependencies { - mycustomconfiguration configurations.runtime -} -``` -在`BootRepackage`中引用的配置是一个正常的[Gradle配置](http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.Configuration.html)。在上面的示例中,我们创建了一个新的名叫`mycustomconfiguration`的配置,指示它来自一个`runtime`,并排除对`log4j`的依赖。如果`clientBoot`任务被执行,重新打包的jar将含有所有来自`runtime`作用域的依赖,除了`log4j` jars。 - -* 配置选项 - -可用的配置选项如下: - -|名称|描述| -|-------|:--------| -|mainClass|可执行jar运行的main类| -|providedConfiguration|provided配置的名称(默认为providedRuntime)| -|backupSource|在重新打包之前,原先的存档是否备份(默认为true)| -|customConfiguration|自定义配置的名称| -|layout|存档类型,对应于内部依赖是如何制定的(默认基于存档类型进行推测)| -|requiresUnpack|一个依赖列表(格式为"groupId:artifactId",为了运行,它们需要从fat jars中解压出来。)所有节点被打包进胖jar,但运行的时候它们将被自动解压| - -* 理解Gradle插件是如何工作的 - -当`spring-boot`被应用到你的Gradle项目,一个默认的名叫`bootRepackage`的任务被自动创建。`bootRepackage`任务依赖于Gradle `assemble`任务,当执行时,它会尝试找到所有限定符为空的jar artifacts(也就是说,tests和sources jars被自动跳过)。 - -由于`bootRepackage`查找'所有'创建jar artifacts的事实,Gradle任务执行的顺序就非常重要了。多数项目只创建一个单一的jar文件,所以通常这不是一个问题。然而,如果你正打算创建一个更复杂的,使用自定义`jar`和`BootRepackage`任务的项目setup,有几个方面需要考虑。 - -如果'仅仅'从项目创建自定义jar文件,你可以简单地禁用默认的`jar`和`bootRepackage`任务: -```gradle -jar.enabled = false -bootRepackage.enabled = false -``` -另一个选项是指示默认的`bootRepackage`任务只能使用一个默认的`jar`任务: -```gradle -bootRepackage.withJarTask = jar -``` -如果你有一个默认的项目setup,在该项目中,主(main)jar文件被创建和重新打包。并且,你仍旧想创建额外的自定义jars,你可以将自定义的repackage任务结合起来,然后使用`dependsOn`,这样`bootJars`任务就会在默认的`bootRepackage`任务执行以后运行: -```gradle -task bootJars -bootJars.dependsOn = [clientBoot1,clientBoot2,clientBoot3] -build.dependsOn(bootJars) -``` -上面所有方面经常用于避免一个已经创建的boot jar又被重新打包的情况。重新打包一个存在的boot jar不是什么大问题,但你可能会发现它包含不必要的依赖。 - -* 使用Gradle将artifacts发布到一个Maven仓库 - -如果你声明依赖但没有指定版本,且你想要将artifacts发布到一个Maven仓库,那你需要使用详细的Spring Boot依赖管理来配置Maven发布。通过配置它发布继承自`spring-boot-starter-parent`的poms或引入来自`spring-boot-dependencies`的依赖管理可以实现该需求。这种配置的具体细节取决于你如何使用Gradle及如何发布该artifacts的。 - -- 自定义Gradle,用于产生一个继承依赖管理的pom - -下面示例展示了如何配置Gradle去产生一个继承自`spring-boot-starter-parent`的pom。请参考[Gradle用户指南](http://gradle.org/docs/current/userguide/userguide.html)获取更多信息。 -```gradle -uploadArchives { - repositories { - mavenDeployer { - pom { - project { - parent { - groupId "org.springframework.boot" - artifactId "spring-boot-starter-parent" - version "1.3.0.BUILD-SNAPSHOT" - } - } - } - } - } -} -``` -- 自定义Gradle,用于产生一个导入依赖管理的pom - -以下示例展示了如何配置Gradle去产生一个导入`spring-boot-dependencies`提供的依赖管理的pom。请参考[Gradle用户指南](http://gradle.org/docs/current/userguide/userguide.html)获取更多信息。 -```gradle -uploadArchives { - repositories { - mavenDeployer { - pom { - project { - dependencyManagement { - dependencies { - dependency { - groupId "org.springframework.boot" - artifactId "spring-boot-dependencies" - version "1.3.0.BUILD-SNAPSHOT" - type "pom" - scope "import" - } - } - } - } - } - } - } -} -``` -### 对其他构建系统的支持 - -如果想使用除了Maven和Gradle之外的构建工具,你可能需要开发自己的插件。可执行jars需要遵循一个特定格式,并且一些实体需要以不压缩的方式写入(详情查看附录中的[可执行jar格式](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#executable-jar)章节)。 - -Spring Boot Maven和Gradle插件都利用`spring-boot-loader-tools`来实际地产生jars。如果需要,你也可以自由地直接使用该库。 - -* 重新打包存档 - -使用`org.springframework.boot.loader.tools.Repackager`可以将一个存在的存档重新打包,这样它就变成一个自包含的可执行存档。`Repackager`类需要提供单一的构造器参数,它引用一个存在的jar或war包。使用两个可用的`repackage()`方法中的一个来替换原始的文件或写入一个新的目标。在repackager运行前还可以设置各种配置。 - -* 内嵌的库 - -当重新打包一个存档时,你可以使用`org.springframework.boot.loader.tools.Libraries`接口来包含对依赖文件的引用。在这里我们不提供任何该Libraries接口的具体实现,因为它们通常跟具体的构建系统相关。 - -如果你的存档已经包含libraries,你可以使用`Libraries.NONE`。 - -* 查找main类 - -如果你没有使用`Repackager.setMainClass()`指定一个main类,该repackager将使用[ASM](http://asm.ow2.org/)去读取class文件,然后尝试查找一个合适的,具有`public static void main(String[] args)`方法的类。如果发现多个候选者,将会抛出异常。 - -* 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/all in one/spring_boot_start.md b/all in one/spring_boot_start.md deleted file mode 100644 index 88276420..00000000 --- a/all in one/spring_boot_start.md +++ /dev/null @@ -1,113 +0,0 @@ -Spring Boot初级教程 -======================= - -### 一. Spring Boot安装 -环境要求:Java 8,Maven 3.2或Gradle 1.12 - -#### 1.Maven方式 -
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
-    http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>com.example</groupId>
-    <artifactId>myproject</artifactId>
-    <version>0.0.1-SNAPSHOT</version>
-
-    <!-- Inherit defaults from Spring Boot -->
-    <parent>
-        <groupId>org.springframework.boot</groupId>
-        <artifactId>spring-boot-starter-parent</artifactId>
-        <version>1.2.1.RELEASE</version>
-    </parent>
-
-    <!-- Add typical dependencies for a web application -->
-    <dependencies>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-web</artifactId>
-        </dependency>
-    </dependencies>
-
-    <!-- Package as an executable jar -->
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.springframework.boot</groupId>
-                <artifactId>spring-boot-maven-plugin</artifactId>
-            </plugin>
-        </plugins>
-    </build>
-</project>
-
-注:Spring Boot依赖的groupId是org.springframework.boot,一般Maven pom需要继承spring-boot-starter-parent,然后声明相应[Starter POMs](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter-poms).如果不想继承spring-boot-starter-parent,可以使用import作用域。 - -#### 2.Gradle方式 - -build.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:1.2.2.BUILD-SNAPSHOT")
-    }
-}
-
-apply plugin: 'java'
-apply plugin: 'spring-boot'
-
-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")
-}
-
- -#### 3.安装Spring Boot命令行工具 - -
-$ gvm install springboot
-$ spring --version
-$ gvm ls springboot
-$ . ~/.gvm/springboot/current/shell-completion/bash/spring
-$ spring 
-  grab  help  jar  run  test  version
-
- -#### 4.Quick Start - -创建app.groovy,代码如下: -
-@RestController
-class ThisWillActuallyRun {
-    @RequestMapping("/")
-    String home() {
-        "Hello World!"
-    }
-}
-
-运行: -
-$ spring run app.groovy
-
- - - -