本节将详细介绍如何使用Spring Boot。它涵盖了诸如构建系统,自动配置以及如何运行应用程序之类的主题。我们还将介绍一些Spring Boot最佳实践。尽管关于Spring Boot并没有什么特别的(它只是另一个可以使用的库),但是有一些建议可以使您的开发过程更轻松一些。
如果您是从Spring Boot开始的,那么在进入本节之前,您可能应该阅读《入门指南》

1.构建系统

强烈建议您选择一个支持依赖关系管理并且可以使用发布到“ Maven Central”存储库的工件的构建系统。我们建议您选择Maven或Gradle。可以使Spring Boot与其他构建系统(例如,Ant)一起使用,但是它们并没有得到很好的支持。

1.1 依赖管理

每个Spring Boot版本都提供了它所支持的依赖关系的精选列表。实际上,您不需要为构建配置中的所有这些依赖项提供版本,因为Spring Boot会为您管理版本。当您升级Spring Boot本身时,这些依赖项也会以一致的方式升级。

您仍然可以指定版本,并在需要时覆盖Spring Boot的建议。

精选列表包含可与Spring Boot一起使用的所有Spring模块以及精炼的第三方库列表。该列表作为spring-boot-dependencies可与MavenGradle一起使用的标准材料清单()提供。

每个Spring Boot版本都与Spring Framework的基本版本相关联。我们强烈建议您不要指定其版本。

1.2 马文

要了解有关将Spring Boot与Maven结合使用的信息,请参阅Spring Boot的Maven插件的文档:

  • 参考(HTMLPDF
  • API

    1.3 摇篮

    要了解有关将Spring Boot与Gradle结合使用的信息,请参阅Spring Boot的Gradle插件的文档:

  • 参考(HTMLPDF

  • API

    1.4 蚂蚁

    可以使用Apache Ant + Ivy构建Spring Boot项目。该spring-boot-antlib“的antlib”模块还可以帮助蚂蚁创建可执行的JAR文件。
    要声明依赖关系,典型ivy.xml文件看起来类似于以下示例:
    1. <ivy-module version="2.0">
    2. <info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
    3. <configurations>
    4. <conf name="compile" description="everything needed to compile this module" />
    5. <conf name="runtime" extends="compile" description="everything needed to run this module" />
    6. </configurations>
    7. <dependencies>
    8. <dependency org="org.springframework.boot" name="spring-boot-starter"
    9. rev="${spring-boot.version}" conf="compile" />
    10. </dependencies>
    11. </ivy-module>
    典型build.xml的示例如下所示:
    1. <project
    2. xmlns:ivy="antlib:org.apache.ivy.ant"
    3. xmlns:spring-boot="antlib:org.springframework.boot.ant"
    4. name="myapp" default="build">
    5. <property name="spring-boot.version" value="2.4.3" />
    6. <target name="resolve" description="--> retrieve dependencies with ivy">
    7. <ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
    8. </target>
    9. <target name="classpaths" depends="resolve">
    10. <path id="compile.classpath">
    11. <fileset dir="lib/compile" includes="*.jar" />
    12. </path>
    13. </target>
    14. <target name="init" depends="classpaths">
    15. <mkdir dir="build/classes" />
    16. </target>
    17. <target name="compile" depends="init" description="compile">
    18. <javac srcdir="src/main/java" destdir="build/classes" classpathref="compile.classpath" />
    19. </target>
    20. <target name="build" depends="compile">
    21. <spring-boot:exejar destfile="build/myapp.jar" classes="build/classes">
    22. <spring-boot:lib>
    23. <fileset dir="lib/runtime" />
    24. </spring-boot:lib>
    25. </spring-boot:exejar>
    26. </target>
    27. </project>
    | | 如果您不想使用该spring-boot-antlib模块,请参见howto.html “操作方法”。 | | :—-: | —- |

1.5 初学者

入门程序是一组便捷的依赖项描述符,您可以在应用程序中包括它们。您可以一站式购买所需的所有Spring和相关技术,而不必遍历示例代码和依赖描述符的复制粘贴负载。例如,如果要开始使用Spring和JPA进行数据库访问,请spring-boot-starter-data-jpa在项目中包括依赖项。
入门程序包含许多启动项目并快速运行所需的依赖项,并且具有一组受支持的受管传递性依赖项。
名字叫什么
所有官方入门者都遵循类似的命名方式。spring-boot-starter-*,其中*是特定类型的应用程序。这种命名结构旨在在您需要寻找入门者时提供帮助。许多IDE中的Maven集成使您可以按名称搜索依赖项。例如,在安装了适当的Eclipse或STS插件的情况下,您可以按ctrl-spacePOM编辑器,然后键入“ spring-boot-starter”以获取完整列表。
如“创建您自己的启动程序”部分中所述,第三方启动程序不应以开头spring-boot,因为它是为官方Spring Boot工件保留的。而是,第三方启动程序通常以项目名称开头。例如,thirdpartyproject通常将名为的第三方启动程序项目命名为thirdpartyproject-spring-boot-starter
Spring Boot在该org.springframework.boot组下提供了以下应用程序启动器:
表1. Spring Boot应用程序启动器

姓名 描述
spring-boot-starter 核心入门工具,包括自动配置支持,日志记录和YAML
spring-boot-starter-activemq 使用Apache ActiveMQ的JMS消息传递入门
spring-boot-starter-amqp 使用Spring AMQP和Rabbit MQ的入门
spring-boot-starter-aop 使用Spring AOP和AspectJ进行面向方面编程的入门
spring-boot-starter-artemis 使用Apache Artemis的JMS消息传递入门
spring-boot-starter-batch 使用Spring Batch的入门
spring-boot-starter-cache 开始使用Spring Framework的缓存支持
spring-boot-starter-data-cassandra 使用Cassandra分布式数据库和Spring Data Cassandra的入门
spring-boot-starter-data-cassandra-reactive 使用Cassandra分布式数据库和Spring Data Cassandra Reactive的入门
spring-boot-starter-data-couchbase 使用Couchbase面向文档的数据库和Spring Data Couchbase的入门
spring-boot-starter-data-couchbase-reactive 使用Couchbase面向文档的数据库和Spring Data Couchbase Reactive的入门
spring-boot-starter-data-elasticsearch 使用Elasticsearch搜索和分析引擎以及Spring Data Elasticsearch的入门者
spring-boot-starter-data-jdbc 使用Spring Data JDBC的入门
spring-boot-starter-data-jpa 将Spring Data JPA与Hibernate结合使用的入门
spring-boot-starter-data-ldap 使用Spring Data LDAP的入门
spring-boot-starter-data-mongodb 使用MongoDB面向文档的数据库和Spring Data MongoDB的入门
spring-boot-starter-data-mongodb-reactive 使用MongoDB面向文档的数据库和Spring Data MongoDB Reactive的入门
spring-boot-starter-data-neo4j 使用Neo4j图形数据库和Spring Data Neo4j的入门
spring-boot-starter-data-r2dbc 使用Spring Data R2DBC的入门
spring-boot-starter-data-redis 使用Redis键值数据存储与Spring Data Redis和Lettuce客户端的入门
spring-boot-starter-data-redis-reactive 将Redis键值数据存储与Spring Data Redis Reacting和Lettuce客户端一起使用的入门
spring-boot-starter-data-rest 使用Spring Data REST在REST上公开Spring Data存储库的入门
spring-boot-starter-data-solr 结合使用Apache Solr搜索平台和Spring Data Solr的入门者。自2.3.9起不推荐使用
spring-boot-starter-freemarker 使用FreeMarker视图构建MVC Web应用程序的入门
spring-boot-starter-groovy-templates 使用Groovy模板视图构建MVC Web应用程序的入门
spring-boot-starter-hateoas 使用Spring MVC和Spring HATEOAS构建基于超媒体的RESTful Web应用程序的入门者
spring-boot-starter-integration 使用Spring Integration的入门
spring-boot-starter-jdbc 结合使用JDBC和HikariCP连接池的入门
spring-boot-starter-jersey 使用JAX-RS和Jersey构建RESTful Web应用程序的入门。的替代品spring-boot-starter-web
spring-boot-starter-jooq 使用jOOQ访问SQL数据库的入门。替代spring-boot-starter-data-jpaspring-boot-starter-jdbc
spring-boot-starter-json 读写JSON入门
spring-boot-starter-jta-atomikos 使用Atomikos的JTA交易入门
spring-boot-starter-jta-bitronix 使用Bitronix的JTA交易入门。自2.3.0起不推荐使用
spring-boot-starter-mail 开始使用Java Mail和Spring Framework的电子邮件发送支持
spring-boot-starter-mustache 使用Mustache视图构建Web应用程序的入门
spring-boot-starter-oauth2-client 使用Spring Security的OAuth2 / OpenID Connect客户端功能的入门
spring-boot-starter-oauth2-resource-server 使用Spring Security的OAuth2资源服务器功能的入门
spring-boot-starter-quartz 入门使用Quartz Scheduler
spring-boot-starter-rsocket 用于构建RSocket客户端和服务器的入门
spring-boot-starter-security 使用Spring Security的入门
spring-boot-starter-test 用于使用包括JUnit Jupiter,Hamcrest和Mockito在内的库测试Spring Boot应用程序的入门程序
spring-boot-starter-thymeleaf 使用Thymeleaf视图构建MVC Web应用程序的入门
spring-boot-starter-validation 通过Hibernate Validator使用Java Bean验证的入门
spring-boot-starter-web 使用Spring MVC构建Web(包括RESTful)应用程序的入门者。使用Tomcat作为默认的嵌入式容器
spring-boot-starter-web-services 使用Spring Web Services的入门
spring-boot-starter-webflux 使用Spring Framework的Reactive Web支持构建WebFlux应用程序的入门者
spring-boot-starter-websocket 使用Spring Framework的WebSocket支持构建WebSocket应用程序的入门

除了应用程序启动程序,以下启动程序可用于添加生产就绪功能:
表2. Spring Boot生产入门

姓名 描述
spring-boot-starter-actuator 使用Spring Boot的Actuator的入门程序,它提供了生产就绪功能,可帮助您监视和管理应用程序

最后,Spring Boot还包括以下启动程序,如果您要排除或交换特定的技术方面,可以使用这些启动程序:
表3. Spring Boot技术入门

姓名 描述
spring-boot-starter-jetty 使用Jetty作为嵌入式servlet容器的入门者。的替代品spring-boot-starter-tomcat
spring-boot-starter-log4j2 使用Log4j2进行日志记录的启动程序。的替代品spring-boot-starter-logging
spring-boot-starter-logging 使用Logback进行日志记录的启动器。默认记录启动器
spring-boot-starter-reactor-netty 使用Reactor Netty作为嵌入式反应式HTTP服务器的入门者。
spring-boot-starter-tomcat 入门,用于将Tomcat用作嵌入式servlet容器。默认使用的servlet容器启动器spring-boot-starter-web
spring-boot-starter-undertow 使用Undertow作为嵌入式servlet容器的入门。的替代品spring-boot-starter-tomcat

要了解如何交换技术方面的信息,请参阅有关交换Web服务器日志记录系统的方法文档。

有关社区贡献的其他入门者的列表,请参阅GitHub中模块中的README文件spring-boot-starters

2.构建代码

Spring Boot不需要任何特定的代码布局即可工作。但是,有一些最佳实践可以帮助您。

2.1 使用“默认”包

当一个类不包含package声明时,它被认为是在“默认包”中。通常不建议使用“默认程序包”,应避免使用。这可能会导致使用了Spring启动应用程序的特殊问题@ComponentScan@ConfigurationPropertiesScan@EntityScan,或@SpringBootApplication注解,因为从每一个罐子每一个类被读取。

我们建议您遵循Java建议的程序包命名约定,并使用反向域名(例如com.example.project)。

2.2 找到主要的应用程序类别

我们通常建议您将主应用程序类放在其他类之上的根包中。该@SpringBootApplication注解往往放在你的主类,它隐含地定义为某些项目一基地“搜索包”。例如,如果您正在编写JPA应用程序,@SpringBootApplication则使用带注释的类的包搜索@Entity项目。使用根软件包还允许组件扫描仅应用于您的项目。

如果您不想使用@SpringBootApplication,它导入的@EnableAutoConfiguration@ComponentScan批注将定义该行为,因此您也可以使用它们。

以下清单显示了典型的布局:
com
+-例子
+-我的应用
+-Application.java
|
+-客户
| +-客户.java
| +-CustomerController.java
| +-CustomerService.java
| +-CustomerRepository.java
|
+-订单
+-Order.java
+-OrderController.java
+-OrderService.java
+-OrderRepository.java
Application.java文件将声明main方法以及basic方法,@SpringBootApplication如下所示:

  1. package com.example.myapplication;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

3.配置类

Spring Boot支持基于Java的配置。尽管可以SpringApplication与XML源一起使用,但是我们通常建议您的主要源为单个@Configuration类。通常,定义main方法的类是主要的候选者@Configuration

Internet上已经发布了许多使用XML配置的Spring配置示例。如果可能,请始终尝试使用等效的基于Java的配置。搜索Enable*注释可以是一个很好的起点。

3.1 导入其他配置类

您无需将所有内容都@Configuration放在一个类中。所述@Import注释可以用于导入额外的配置类。另外,您可以@ComponentScan用来自动拾取所有Spring组件,包括@Configuration类。

3.2 导入XML配置

如果绝对必须使用基于XML的配置,我们建议您仍然从一个@Configuration类开始。然后,您可以使用@ImportResource批注来加载XML配置文件。

4.自动配置

Spring Boot自动配置会尝试根据添加的jar依赖项自动配置Spring应用程序。例如,如果HSQLDB在类路径上,并且您尚未手动配置任何数据库连接bean,那么Spring Boot会自动配置内存数据库。
您需要通过将@EnableAutoConfiguration@SpringBootApplication注释添加到一个@Configuration类中来选择自动配置。

您只能添加一个@SpringBootApplication@EnableAutoConfiguration注释。我们通常建议您仅将一个或另一个添加到您的主要@Configuration班级。

4.1 逐渐取代自动配置

自动配置是非侵入性的。在任何时候,您都可以开始定义自己的配置,以替换自动配置的特定部分。例如,如果您添加自己的DataSourcebean,则默认的嵌入式数据库支持将退出。
如果您需要找出当前正在应用的自动配置以及原因,请使用--debug开关启动应用程序。这样做可以启用调试日志以供选择核心记录器,并将条件报告记录到控制台。

4.2 禁用特定的自动配置类

如果发现正在应用不需要的特定自动配置类,则可以使用exclude属性@SpringBootApplication来禁用它们,如以下示例所示:

  1. import org.springframework.boot.autoconfigure.*;
  2. import org.springframework.boot.autoconfigure.jdbc.*;
  3. @SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
  4. public class MyApplication {
  5. }

如果该类不在类路径中,则可以使用excludeName注释的属性,并指定完全限定的名称。如果您喜欢使用@EnableAutoConfiguration而不是@SpringBootApplicationexclude并且excludeName也可以使用。最后,您还可以使用spring.autoconfigure.exclude属性来控制要排除的自动配置类的列表。

您可以在注释级别和使用属性来定义排除项。
即使是自动配置类public,该类的唯一方面也被视为公共API,该类的名称是可用于禁用自动配置的类的名称。这些类的实际内容(例如嵌套配置类或Bean方法)仅供内部使用,我们不建议直接使用它们。

5.春豆和依赖注入

您可以自由使用任何标准的Spring Framework技术来定义bean及其注入的依赖项。我们经常发现使用@ComponentScan(查找您的bean)和使用@Autowired(进行构造函数注入)效果很好。
如果按照上面的建议构造代码(将应用程序类放在根包中),则可以添加@ComponentScan任何参数。您的所有应用程序组件(的@Component@Service@Repository@Controller等)自动注册为春豆。
以下示例显示了一个@Service使用构造函数注入来获取所需RiskAssessorBean的Bean:

  1. package com.example.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class DatabaseAccountService implements AccountService {
  6. private final RiskAssessor riskAssessor;
  7. @Autowired
  8. public DatabaseAccountService(RiskAssessor riskAssessor) {
  9. this.riskAssessor = riskAssessor;
  10. }
  11. // ...
  12. }

如果bean具有一个构造函数,则可以省略@Autowired,如以下示例所示:

  1. @Service
  2. public class DatabaseAccountService implements AccountService {
  3. private final RiskAssessor riskAssessor;
  4. public DatabaseAccountService(RiskAssessor riskAssessor) {
  5. this.riskAssessor = riskAssessor;
  6. }
  7. // ...
  8. }
请注意,使用构造函数注入如何将riskAssessor字段标记为final,指示该字段随后不能更改。

6.使用@SpringBootApplication注释

许多Spring Boot开发人员喜欢他们的应用程序使用自动配置,组件扫描,并能够在其“应用程序类”上定义额外的配置。单个@SpringBootApplication注释可用于启用这三个功能,即:

  • @EnableAutoConfiguration:启用Spring Boot的自动配置机制
  • @ComponentScan:启用@Component对应用程序所在的软件包的扫描(请参阅最佳实践
  • @Configuration:允许在上下文中注册额外的bean或导入其他配置类
    1. package com.example.myapplication;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
    5. public class Application {
    6. public static void main(String[] args) {
    7. SpringApplication.run(Application.class, args);
    8. }
    9. }
    | | @SpringBootApplication还提供了别名定制的属性@EnableAutoConfiguration@ComponentScan。 | | :—-: | —- |

| | 这些功能都不是强制性的,您可以选择用它启用的任何功能替换此单个注释。例如,您可能不想在应用程序中使用组件扫描或配置属性扫描:``` package com.example.myapplication;

import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import;

@Configuration(proxyBeanMethods = false) @EnableAutoConfiguration @Import({ MyConfig.class, MyAnotherConfig.class }) public class Application {

  1. **public** **static** **void** **main**(String[] args) {
  2. SpringApplication.run(Application.class, args);
  3. }

}

  1. 在此示例中,`Application`与其他任何Spring Boot应用程序一样,除了不会自动检测`@Component`-annotated类和`@ConfigurationProperties`-annotated类,并且显式导入用户定义的Bean(请参阅参考资料`@Import`)。 |
  2. | :---: | --- |
  3. <a name="using-boot-running-your-application"></a>
  4. ## 7.运行您的应用程序
  5. 将应用程序打包为jar并使用嵌入式HTTP服务器的最大优势之一是,您可以像运行其他应用程序一样运行应用程序。该示例适用于调试Spring Boot应用程序。您不需要任何特殊的IDE插件或扩展。
  6. | | 本节仅介绍基于罐子的包装。如果选择将应用程序打包为war文件,则应参考服务器和IDE文档。 |
  7. | :---: | --- |
  8. <a name="using-boot-running-from-an-ide"></a>
  9. ### 7.1 从IDE运行
  10. 您可以从IDE作为Java应用程序运行Spring Boot应用程序。但是,您首先需要导入您的项目。导入步骤因您的IDE和构建系统而异。大多数IDE可以直接导入Maven项目。例如,Eclipse用户可以从菜单中选择`Import…` `Existing Maven Projects``File`<br />如果您不能直接将项目导入到IDE中,则可以使用构建插件来生成IDE元数据。Maven包括[Eclipse](https://maven.apache.org/plugins/maven-eclipse-plugin/)和[IDEA的](https://maven.apache.org/plugins/maven-idea-plugin/)插件。Gradle提供了用于[各种IDE的](https://docs.gradle.org/current/userguide/userguide.html)插件。
  11. | | 如果不小心两次运行Web应用程序,则会看到“端口已在使用中”错误。STS用户可以使用`Relaunch`按钮而不是`Run`按钮来确保关闭任何现有实例。 |
  12. | :---: | --- |
  13. <a name="using-boot-running-as-a-packaged-application"></a>
  14. ### 7.2 作为打包的应用程序运行
  15. 如果您使用Spring Boot MavenGradle插件创建可执行jar,则可以使用来运行您的应用程序`java -jar`,如以下示例所示:<br />$ java -jar target / myapplication-0.0.1-SNAPSHOT.jar<br />也可以在启用了远程调试支持的情况下运行打包的应用程序。这样做使您可以将调试器附加到打包的应用程序,如以下示例所示:<br />$ java -Xdebug -Xrunjdwpserver = ytransport = dt_socketaddress = 8000suspend = n \<br /> -jar目标/myapplication-0.0.1-SNAPSHOT.jar
  16. <a name="using-boot-running-with-the-maven-plugin"></a>
  17. ### 7.3 使用Maven插件
  18. Spring Boot Maven插件包含一个`run`目标,可用于快速编译和运行您的应用程序。应用程序以爆炸形式运行,就像在IDE中一样。以下示例显示了运行Spring Boot应用程序的典型Maven命令:<br />$ mvn spring-boot:运行<br />您可能还想使用`MAVEN_OPTS`操作系统环境变量,如以下示例所示:<br />$ export MAVEN_OPTS = -Xmx1024m
  19. <a name="using-boot-running-with-the-gradle-plugin"></a>
  20. ### 7.4 使用Gradle插件
  21. Spring Boot Gradle插件还包含一个`bootRun`任务,可用于以爆炸形式运行您的应用程序。`bootRun`每当您应用`org.springframework.boot``java`插件时,都会添加该任务,并在以下示例中显示:<br />$ gradle bootRun<br />您可能还想使用`JAVA_OPTS`操作系统环境变量,如以下示例所示:<br />$ export JAVA_OPTS = -Xmx1024m
  22. <a name="using-boot-hot-swapping"></a>
  23. ### 7.5 热交换
  24. 由于Spring Boot应用程序是普通的Java应用程序,因此JVM热交换应该可以立即使用。JVM热插拔在一定程度上受到它可以替换的字节码的限制。对于更完整的解决方案,可以使用[JRebel](https://www.jrebel.com/products/jrebel)。<br />该`spring-boot-devtools`模块还包括对应用程序快速重启的支持。有关详细信息,请参见本章后面的“[开发人员工具”](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools)部分和[热插拔“操作方法”](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/howto.html#howto-hotswapping)。
  25. <a name="using-boot-devtools"></a>
  26. ## 8.开发人员工具
  27. Spring Boot包含一组额外的工具,这些工具可以使应用程序开发体验更加愉快。该`spring-boot-devtools`模块可以包含在任何项目中,以提供其他开发时功能。要包括devtools支持,请将模块依赖项添加到您的构建中,如以下MavenGradle清单所示:<br />马文

org.springframework.boot spring-boot-devtools true

  1. 摇篮

dependencies { developmentOnly(“org.springframework.boot:spring-boot-devtools”) }

  1. | | 运行完全打包的应用程序时,将自动禁用开发人员工具。如果您的应用程序是`java -jar`从某个特殊的类加载器启动的,或者从特殊的类加载器启动的,则将其视为“生产应用程序”。您可以通过使用`spring.devtools.restart.enabled`system属性来控制此行为。要启用devtools,无论用于启动应用程序的类加载器如何,都要设置`-Dspring.devtools.restart.enabled=true`系统属性。在运行devtools有安全风险的生产环境中,绝对不能这样做。要禁用devtools,请排除依赖项或设置`-Dspring.devtools.restart.enabled=false`系统属性。 |
  2. | :---: | --- |
  3. | | Maven中将依赖项标记为可选,或`developmentOnly`Gradle中使用配置(如上所示)可以防止将devtools过渡地应用到使用项目的其他模块。 |
  4. | :---: | --- |
  5. | | 重新打包的存档默认情况下不包含devtools。如果要使用[某个远程devtools功能](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-remote),则需要包括它。使用Maven插件时,请将`excludeDevtools`属性设置为`false`。使用Gradle插件时,请[配置任务的类路径以包括`developmentOnly`configuration](https://docs.spring.io/spring-boot/docs/2.4.3/gradle-plugin/reference/htmlsingle/#packaging-executable-configuring-including-development-only-dependencies)。 |
  6. | :---: | --- |
  7. <a name="using-boot-devtools-property-defaults"></a>
  8. ### 8.1 属性默认值
  9. Spring Boot支持的一些库使用缓存来提高性能。例如,[模板引擎](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/spring-boot-features.html#boot-features-spring-mvc-template-engines)缓存已编译的模板,以避免重复解析模板文件。同样,Spring MVC可以在提供静态资源时向响应添加HTTP缓存头。<br />尽管缓存在生产中非常有益,但在开发过程中可能适得其反,从而使您无法看到刚刚在应用程序中所做的更改。因此,默认情况下,spring-boot-devtools禁用缓存选项。<br />缓存选项通常由`application.properties`文件中的设置配置。例如,Thymeleaf提供了该`spring.thymeleaf.cache`属性。该`spring-boot-devtools`模块无需手动设置这些属性,而是自动应用合理的开发时配置。<br />由于在开发Spring MVC和Spring WebFlux应用程序时需要有关Web请求的更多信息,因此开发人员工具将启用`DEBUG`日志`web`记录组的日志记录。这将为您提供有关传入请求,正在处理该请求的处理程序,响应结果等的信息。如果您希望记录所有请求的详细信息(包括潜在的敏感信息),则可以打开`spring.mvc.log-request-details`或`spring.codec.log-request-details`配置属性。
  10. | | 如果你不想被应用属性默认可以设置`spring.devtools.add-properties``false``application.properties` |
  11. | :---: | --- |
  12. | | 有关devtools应用的属性的完整列表,请参见[DevToolsPropertyDefaultsPostProcessor](https://github.com/spring-projects/spring-boot/tree/v2.4.3/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java)。 |
  13. | :---: | --- |
  14. <a name="using-boot-devtools-restart"></a>
  15. ### 8.2 自动重启
  16. `spring-boot-devtools`只要类路径上的文件发生更改,使用的应用程序就会自动重新启动。当在IDE中工作时,这可能是一个有用的功能,因为它为代码更改提供了非常快速的反馈循环。默认情况下,将监视类路径上指向目录的任何条目的更改。请注意,某些资源(例如静态资产和视图模板)[不需要重新启动应用程序](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-restart-exclude)。<br />触发重启<br />当DevTools监视类路径资源时,触发重启的唯一方法是更新类路径。导致类路径更新的方式取决于您使用的IDE:
  17. - Eclipse中,保存修改后的文件将导致类路径被更新并触发重新启动。<br />
  18. - IntelliJ IDEA中,构建项目(`Build +→+ Build Project`)具有相同的效果。<br />
  19. - 如果使用构建插件,`mvn compile`则为Maven`gradle build`Gradle运行将触发重新启动。<br />
  20. | | 如果要使用构建插件从MavenGradle重新启动,则必须将`forking`设置保留为`enabled`。如果禁用分叉,则不会创建devtools使用的隔离的应用程序类加载器,并且重新启动将无法正常运行。 |
  21. | :---: | --- |
  22. | | LiveReload一起使用时,自动重新启动效果很好。 [有关](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-livereload)详细信息,[请参见LiveReload部分](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-livereload)。如果使用JRebel,则禁用自动重新启动,而支持动态类重新加载。其他devtools功能(例如LiveReload和属性替代)仍可以使用。 |
  23. | :---: | --- |
  24. | | DevTools依靠应用程序上下文的关闭挂钩在重新启动期间将其关闭。如果您禁用了关机挂钩(`SpringApplication.setRegisterShutdownHook(false)`),它将无法正常工作。 |
  25. | :---: | --- |
  26. | | DevTools需求来定制`ResourceLoader`使用的`ApplicationContext`。如果您的应用程序已经提供了,它将被包装。不支持直接覆盖`getResource`方法`ApplicationContext` |
  27. | :---: | --- |
  28. 重新启动与重新加载<br />Spring Boot提供的重启技术通过使用两个类加载器来工作。不变的类(例如,来自第三方jar的类)将被加载到_基本_类加载器中。您正在积极开发的类将加载到_重新启动_类加载器中。重新启动应用程序后,将丢弃_重新启动_类加载器,并创建一个新的类加载器。这种方法意味着应用程序的重启通常比“冷启动”要快得多,因为_基本_类加载器已经可用并已填充。<br />如果发现重新启动对于您的应用程序而言不够快,或者遇到类加载问题,则可以考虑从ZeroTurnaround重新加载技术,例如[JRebel](https://jrebel.com/software/jrebel/)。这些方法通过在加载类时重写类来使其更易于重新加载。
  29. <a name="using-boot-devtools-restart-logging-condition-delta"></a>
  30. #### 8.2.1 记录条件评估中的更改
  31. 默认情况下,每次应用程序重新启动时,都会记录一个报告,其中显示了条件评估增量。该报告显示了在进行更改(例如添加或删除Bean以及设置配置属性)时对应用程序自动配置的更改。<br />要禁用报告的日志记录,请设置以下属性:<br />特性<br />Yaml

spring: devtools: restart: log-condition-evaluation-delta: false

  1. <a name="using-boot-devtools-restart-exclude"></a>
  2. #### 8.2.2 排除资源
  3. 某些资源在更改后不一定需要触发重新启动。例如,Thymeleaf模板可以就地编辑。默认情况下,改变资源`/META-INF/maven`,`/META-INF/resources`,`/resources`,`/static`,`/public`,或`/templates`不触发重新启动,但确会触发[现场重装](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-livereload)。如果要自定义这些排除项,则可以使用该`spring.devtools.restart.exclude`属性。例如,仅排除`/static`,`/public`您将设置以下属性:<br />特性<br />Yaml

spring: devtools: restart: exclude: “static/,public/

  1. | | 如果要保留这些默认值并_添加_其他排除项,请改用该`spring.devtools.restart.additional-exclude`属性。 |
  2. | :---: | --- |
  3. <a name="using-boot-devtools-restart-additional-paths"></a>
  4. #### 8.2.3 观看其他路径
  5. 当您对不在类路径上的文件进行更改时,您可能希望重新启动或重新加载应用程序。为此,请使用该`spring.devtools.restart.additional-paths`属性来配置其他路径以监视更改。您可以使用[前面描述](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-restart-exclude)的`spring.devtools.restart.exclude`属性来控制其他路径下的更改是触发完全重新启动还是[实时重新加载](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-livereload)。
  6. <a name="using-boot-devtools-restart-disable"></a>
  7. #### 8.2.4 禁用重启
  8. 如果您不想使用重新启动功能,则可以使用该`spring.devtools.restart.enabled`属性将其禁用。在大多数情况下,您可以在自己的设备中设置此属性`application.properties`(这样做仍会初始化重新启动类加载器,但它不会监视文件更改)。<br />如果您需要_完全_禁用重启支持(例如,因为它不适用于特定的库),则需要在调用之前将`spring.devtools.restart.enabled` `System`属性设置为,如以下示例所示:`false``SpringApplication.run(…)`

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

  1. <a name="using-boot-devtools-restart-triggerfile"></a>
  2. #### 8.2.5 使用触发文件
  3. 如果使用持续编译更改文件的IDE,则可能更喜欢仅在特定时间触发重新启动。为此,您可以使用“触发文件”,这是一个特殊文件,当您要实际触发重新启动检查时必须对其进行修改。
  4. | | 对文件的任何更新都会触发检查,但是只有在Devtools检测到有事情要做的情况下,重启才会真正发生。 |
  5. | :---: | --- |
  6. 要使用触发文件,请将`spring.devtools.restart.trigger-file`属性设置为触发文件的名称(不包括任何路径)。触发文件必须出现在类路径上的某个位置。<br />例如,如果您的项目具有以下结构:<br />src<br />+-主要<br /> +-资源<br /> +-.reloadtrigger<br />那么您的`trigger-file`财产将是:<br />特性<br />Yaml

spring: devtools: restart: trigger-file: “.reloadtrigger”

  1. 现在,仅在`src/main/resources/.reloadtrigger`更新时才会重新启动。
  2. | | 您可能希望将其设置`spring.devtools.restart.trigger-file`为[全局设置](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-globalsettings),以便所有项目以相同的方式运行。 |
  3. | :---: | --- |
  4. 某些IDE具有使您不必手动更新触发器文件的功能。 [EclipseSpring工具](https://spring.io/tools)和[IntelliJ IDEA(最终版)](https://www.jetbrains.com/idea/)都具有这种支持。使用Spring Tools,您可以从控制台视图中使用“重新加载”按钮(只要您`trigger-file`名为`.reloadtrigger`)。对于IntelliJ IDEA,您可以按照[其文档中](https://www.jetbrains.com/help/idea/spring-boot.html#application-update-policies)的[说明进行操作](https://www.jetbrains.com/help/idea/spring-boot.html#application-update-policies)。
  5. <a name="using-boot-devtools-customizing-classload"></a>
  6. #### 8.2.6 自定义重启类加载器
  7. 如前面的“[重新启动与重新加载”](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-spring-boot-restart-vs-reload)部分所述,重新启动功能是通过使用两个类加载器实现的。对于大多数应用程序,此方法效果很好。但是,有时可能会导致类加载问题。<br />默认情况下,IDE中的任何打开的项目均使用“重新启动”类加载器加载,而任何常规`.jar`文件均使用“基本”类加载器加载。如果您在多模块项目上工作,并且并非每个模块都导入到IDE中,则可能需要自定义内容。为此,您可以创建一个`META-INF/spring-devtools.properties`文件。<br />该`spring-devtools.properties`文件可以包含以`restart.exclude`和开头的属性`restart.include`。该`include`元素是应该被拉高到“重启”的类加载器的项目,以及`exclude`要素是应该向下推入“基地”类加载器的项目。该属性的值是应用于类路径的正则表达式模式,如以下示例所示:<br />特性<br />Yaml

restart: exclude: companycommonlibs: “/mycorp-common-[\w\d-\.]+\.jar” include: projectcommon: “/mycorp-myproj-[\w\d-\.]+\.jar”

  1. | | 所有属性键都必须是唯一的。只要属性以`restart.include.`或开头,`restart.exclude.`就可以考虑。 |
  2. | :---: | --- |
  3. | | 所有`META-INF/spring-devtools.properties`从类路径加载。您可以将文件打包在项目内部或项目使用的库中。 |
  4. | :---: | --- |
  5. <a name="using-boot-devtools-known-restart-limitations"></a>
  6. #### 8.2.7 已知局限性
  7. 重新启动功能不适用于通过使用标准反序列化的对象`ObjectInputStream`。如果你需要反序列化的数据,你可能需要使用Spring`ConfigurableObjectInputStream`结合`Thread.currentThread().getContextClassLoader()`。<br />不幸的是,一些第三方库在不考虑上下文类加载器的情况下反序列化。如果发现这样的问题,则需要向原始作者请求修复。
  8. <a name="using-boot-devtools-livereload"></a>
  9. ### 8.3 LiveReload
  10. `spring-boot-devtools`模块包括一个嵌入式LiveReload服务器,该服务器可用于在更改资源时触发浏览器刷新。可从[livereload.com](http://livereload.com/extensions/)免费获得适用于Chrome,Firefox和Safari的LiveReload浏览器扩展。<br />如果您不想在应用程序运行时启动LiveReload服务器,则可以将`spring.devtools.livereload.enabled`属性设置为`false`。
  11. | | 一次只能运行一台LiveReload服务器。在启动应用程序之前,请确保没有其他LiveReload服务器正在运行。如果从IDE启动多个应用程序,则只有第一个具有LiveReload支持。 |
  12. | :---: | --- |
  13. | | 要在文件更改时触发LiveReload,必须启用[自动重启](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-restart)。 |
  14. | :---: | --- |
  15. <a name="using-boot-devtools-globalsettings"></a>
  16. ### 8.4 全局设置
  17. 您可以通过将以下任何文件添加到`$HOME/.config/spring-boot`目录来配置全局devtools设置:
  18. 1. `spring-boot-devtools.properties`<br />
  19. 1. `spring-boot-devtools.yaml`<br />
  20. 1. `spring-boot-devtools.yml`<br />
  21. 添加到这些文件的任何属性都将应用于使用devtools的计算机上的_所有_Spring Boot应用程序。例如,要将重新启动配置为始终使用[触发文件](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-restart-triggerfile),您可以在[文件中](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools-restart-triggerfile)添加以下属性`spring-boot-devtools`:<br />特性<br />Yaml

spring: devtools: restart: trigger-file: “.reloadtrigger”

  1. | | 如果在中找不到devtools配置文件`$HOME/.config/spring-boot`,则在`$HOME`目录的根目录中搜索是否存在`.spring-boot-devtools.properties`文件。这使您可以与不支持该`$HOME/.config/spring-boot`位置的旧版Spring Boot上的应用程序共享devtools全局配置。 |
  2. | :---: | --- |
  3. | | devtools属性/ yaml文件中不支持配置文件。<br />激活的任何配置文件`.spring-boot-devtools.properties`都不会影响[特定于配置文件的配置文件](https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/spring-boot-features.html#boot-features-external-config-files-profile-specific)的加载。不支持配置文件特定的文件名(格式为`spring-boot-devtools-<profile>.properties`)以及`spring.config.activate.on-profile`YAML和属性文件中的文档。 |
  4. | :---: | --- |
  5. <a name="configuring-file-system-watcher"></a>
  6. #### 8.4.1 配置文件系统观察器
  7. [FileSystemWatcher的](https://github.com/spring-projects/spring-boot/tree/v2.4.3/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSystemWatcher.java)工作方式是按一定时间间隔轮询类更改,然后等待预定义的静默期以确保没有更多更改。由于Spring Boot完全依赖IDE来编译文件并将其复制到Spring Boot可以读取文件的位置,因此您可能会发现,有时候devtools重新启动应用程序时某些更改未反映出来。如果您经常观察到此类问题,请尝试将`spring.devtools.restart.poll-interval`和`spring.devtools.restart.quiet-period`参数增加到适合您的开发环境的值:<br />特性<br />Yaml

spring: devtools: restart: poll-interval: “2s” quiet-period: “1s”

  1. 现在每2秒轮询一次受监视的类路径目录以查找更改,并保持1秒钟的静默时间以确保没有其他类更改。
  2. <a name="using-boot-devtools-remote"></a>
  3. ### 8.5 远程应用
  4. Spring Boot开发人员工具不仅限于本地开发。远程运行应用程序时,您还可以使用多种功能。选择启用远程支持是因为启用它可能会带来安全风险。仅当在受信任的网络上运行或使用SSL保护时,才应启用它。如果这两个选项都不可用,则不应使用DevTools的远程支持。您永远不应在生产部署上启用支持。<br />要启用它,您需要确保已将`devtools`其包含在重新打包的存档中,如以下清单所示:

org.springframework.boot spring-boot-maven-plugin false `` 然后,您需要设置spring.devtools.remote.secret属性。像任何重要的密码或机密一样,该值应唯一且强壮,以免被猜测或强行使用。<br />远程devtools支持分为两个部分:接受连接的服务器端终结点和在IDE中运行的客户端应用程序。spring.devtools.remote.secret`设置属性后,将自动启用服务器组件。客户端组件必须手动启动。

8.5.1 运行远程客户端应用程序

远程客户端应用程序旨在在您的IDE中运行。您需要org.springframework.boot.devtools.RemoteSpringApplication使用与所连接的远程项目相同的类路径运行。应用程序的唯一必需参数是它连接到的远程URL。
例如,如果您正在使用Eclipse或STS,并且有一个my-app已部署到Cloud Foundry的项目,则应执行以下操作:

  • 选择Run Configurations…Run菜单。
  • 创建一个新的Java Application“启动配置”。
  • 浏览该my-app项目。
  • 使用org.springframework.boot.devtools.RemoteSpringApplication作为主类。
  • 添加[https://myapp.cfapps.io](https://myapp.cfapps.io)Program arguments(或任何您的远程URL)。

正在运行的远程客户端可能类似于以下清单:
_
/ \ / __
__ \ \ \ \
(()\
|’ |’ | |’ \ / ` | | \ __ || | __ \ \ \ \
\ / )| | )| | | | | || ( | [] :::::: [] / -)’\ / \ / -)))))
‘| _
| . | | | | | | \ ,| | | \ | | | \ _ / \ \ _ | / / / /
======== | | ============== | __ / ====================== ============= / / / _ /
:: Spring Boot Remote :: 2.4.3

2015-06-10 18:25:06.632信息14938—[main] osbdevtools.RemoteSpringApplication:使用PID 14938在pwmbp上启动RemoteSpringApplication(/ Users / pwebb / projects / spring-boot / code / spring-boot-project / spring -boot-devtools / target / classes由pwebb在/ Users / pwebb / projects / spring-boot / code中启动)
2015-06-10 18:25:06.671信息14938—[main] scaAnnotationConfigApplicationContext:刷新org.spring framework.context.annotation.AnnotationConfigApplicationContext @ 2a17b7b6:启动日期[WDT Jun 10 18:25:06 PDT 2015];上下文层次结构的根
2015-06-10 18:25:07.043 WARN 14938 —- [main] osbdrcRemoteClientConfiguration:与http:// localhost:8080的连接不安全。您应使用以“ https://”开头的URL。
2015-06-10 18:25:07.074信息14938 —- [main] osbdaOptionalLiveReloadServer:LiveReload服务器在端口35729上运行
2015-06-10 18:25:07.130信息14938 —- [main] osbdevtools.RemoteSpringApplication:在0.74秒内启动RemoteSpringApplication(JVM运行1.105)

因为远程客户端使用与真实应用程序相同的类路径,所以它可以直接读取应用程序属性。这就是spring.devtools.remote.secret读取属性并将其传递给服务器进行身份验证的方式。
始终建议将其https://用作连接协议,以便对通信进行加密并且不能截获密码。
如果您需要使用代理来访问远程应用程序,请配置spring.devtools.remote.proxy.hostspring.devtools.remote.proxy.port属性。

8.5.2 远程更新

远程客户端以与本地重新启动相同的方式监视应用程序类路径中的更改。任何更新的资源都会推送到远程应用程序,并且(如果需要)会触发重新启动。如果您迭代使用本地没有的云服务的功能,这将很有帮助。通常,远程更新和重新启动比完整的重建和部署周期要快得多。
在较慢的开发环境中,可能会发生静默期不够的情况,并且类中的更改可能会分为批次。第一批类更改上传后,服务器将重新启动。由于服务器正在重新启动,因此下一批不能发送到应用程序。
这通常通过RemoteSpringApplication日志中关于无法上载某些类的警告以及随后的重试来表明。但是,这也可能导致应用程序代码不一致,并且在上传第一批更改后无法重新启动。如果您经常观察到此类问题,请尝试将spring.devtools.restart.poll-intervalspring.devtools.restart.quiet-period参数增加到适合您的开发环境的值。请参阅“配置文件系统监视程序”部分以配置这些属性。

仅在远程客户端运行时监视文件。如果在启动远程客户端之前更改文件,则不会将其推送到远程服务器。

9.打包您的生产申请

可执行jar可以用于生产部署。由于它们是独立的,因此它们也非常适合基于云的部署。
对于其他“生产准备就绪”功能,例如运行状况,审核和度量REST或JMX端点,请考虑添加spring-boot-actuator。有关详细信息,请参见production-ready-features.html

10.下一步阅读

现在,您应该了解如何使用Spring Boot以及应遵循的一些最佳实践。现在,您可以继续深入了解特定的Spring Boot功能,或者可以跳过并阅读有关Spring Boot的“生产就绪”方面的信息。