13. 构建系统

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

13.1 Dependency Management

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

You can still specify a version and override Spring Boot’s recommendations if you need to do so.

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

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

13.2 Maven

Maven用户可以继承spring-boot-starter-parent项目以获得合理的默认值。父项目提供以下功能:

  • Java 1.8作为默认编译器级别。
  • UTF-8 source encoding
  • 继承自spring-boot-dependencies ``pom的依赖关系管理部分,用于管理公共依赖关系的版本。 此依赖关系管理允许您在自己的pom中使用时省略这些依赖项的<version>标记
  • 使用重新打包执行ID执行重新打包目标。
  • 明智的资源过滤。
  • 明智的插件配置(exec plugin, Git commit ID, and shade)。
  • application.propertiesapplication.yml的合理资源过滤,包括特定于配置文件的文件(例如,application-dev.propertiesapplication-dev.yml

Note that, since the application.properties and application.yml files accept Spring style placeholders (${…}), the Maven filtering is changed to use @..@ placeholders. (You can override that by setting a Maven property called resource.delimiter.)

13.2.1 Inheriting the Starter Parent

<!-- Inherit defaults from Spring Boot -->
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.7.RELEASE</version>
</parent>

You should need to specify only the Spring Boot version number on this dependency.如果导入其他启动器,则可以安全地省略版本号。

通过该设置,您还可以通过覆盖自己项目中的属性来覆盖单个依赖项。例如,要升级到另一个Spring Data版本系列,您需要将以下内容添加到pom.xml

<properties>
	<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>

检查spring-boot-dependencies`` pom以获取支持的属性列表。

下面依赖的作用:确保Spring Data模块使用一致版本集的材料清单

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-releasetrain -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-releasetrain</artifactId>
    <version>Fowler-SR2</version>
    <type>pom</type>
</dependency>

13.2.2 Using Spring Boot without the Parent POM

您可能拥有自己需要使用的公司标准父级,或者您可能更愿意明确声明所有Maven配置。

如果您不想使用spring-boot-starter-parent,您仍然可以通过使用scope = import依赖项来保持依赖项管理(but not the plugin management)的好处,如下所示:

<dependencyManagement>
	<dependencies>
		<dependency>
			<!-- 从Spring Boot导入依赖关系管理 -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-dependencies</artifactId>
			<version>2.1.7.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

如上所述,前面的示例设置不允许您使用属性覆盖单个依赖项。 要获得相同的结果,您需要在spring-boot-dependencies条目之前在项目的dependencyManagement中添加一个条目。 例如,要升级到另一个Spring Data版本系列,可以将以下元素添加到pom.xml

<dependencyManagement>
	<dependencies>
		<!-- Override Spring Data release train provided by Spring Boot -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-releasetrain</artifactId>
			<version>Fowler-SR2</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-dependencies</artifactId>
			<version>2.1.7.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

在前面的示例中,我们指定了BOM,但是可以以相同的方式覆盖任何依赖关系类型。

什么是pom?

Maven POM是一个XML文件,其中包含Maven用于导入依赖项和构建项目的信息和配置(关于项目)。

什么是bom?

BOM代表物料清单。 BOM是一种特殊的POM,用于控制项目依赖项的版本,并提供定义和更新这些版本的中心位置。 BOM提供了向模块添加依赖项的灵活性,而无需担心我们应该依赖的版本。

13.2.3 Using the Spring Boot Maven Plugin

Spring Boot包含一个Maven插件,可以将项目打包为可执行jar。如果要使用插件,请将插件添加到部分,如以下示例所示:

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

13.3 Starters 启动器

启动器是一组方便的依赖关系描述符,您可以在应用程序中包含这些描述符。您可以获得所需的所有Spring和相关技术的一站式服务,而无需查看示例代码和复制粘贴依赖描述符的负载。 例如,如果要开始使用Spring和JPA进行数据库访问,请在项目中包含spring-boot-starter-data-jpa依赖项。 启动器包含许多依赖项,这些依赖项是使项目快速启动和运行所需的依赖项,以及一组受支持的托管传递依赖项。

所有官方首发都遵循类似的命名模式; spring-boot-starter- ,其中是特定类型的应用程序。 此命名结构旨在帮助您找到启动器。 许多IDE中的Maven集成允许您按名称搜索依赖项。 例如,安装了适当的Eclipse或STS插件后,您可以在POM编辑器中按ctrl-space并输入“spring-boot-starter”以获取完整列表。 正如“创建自己的初学者”部分所述,第三方启动器不应该以spring-boot启动,因为它是为官方Spring Boot工件保留的。 相反,第三方启动器通常以项目名称开头。 例如,名为thirdpartyproject的第三方启动项目通常被命名为thirdpartyproject-spring-boot-starter。

以下应用程序启动程序由org.springframework.boot组下的Spring Boot提供:

表13.1 Spring Boot应用程序启动器

Name

Description

Pom

spring-boot-starter

核心启动器,包括自动配置支持,日志记录和YAML

Pom

spring-boot-starter-activemq

Starter for JMS messaging using Apache ActiveMQ

Pom

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ

Pom

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ

Pom

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

Pom

spring-boot-starter-batch

Starter for using Spring Batch

Pom

spring-boot-starter-cache

Starter for using Spring Framework’s caching support

Pom

spring-boot-starter-cloud-connectors

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

Pom

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

Pom

spring-boot-starter-data-cassandra-reactive

Starter for using Cassandra distributed database and Spring Data Cassandra Reactive

Pom

spring-boot-starter-data-couchbase

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

Pom

spring-boot-starter-data-couchbase-reactive

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

Pom

spring-boot-starter-data-elasticsearch

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

Pom

spring-boot-starter-data-jdbc

Starter for using Spring Data JDBC

Pom

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

Pom

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

Pom

spring-boot-starter-data-mongodb

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

Pom

spring-boot-starter-data-mongodb-reactive

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

Pom

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

Pom

spring-boot-starter-data-redis

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

Pom

spring-boot-starter-data-redis-reactive

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

Pom

spring-boot-starter-data-rest

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

Pom

spring-boot-starter-data-solr

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

Pom

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views

Pom

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

Pom

spring-boot-starter-hateoas

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

Pom

spring-boot-starter-integration

Starter for using Spring Integration

Pom

spring-boot-starter-jdbc

Starter for using JDBC with the HikariCP connection pool

Pom

spring-boot-starter-jersey

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

Pom

spring-boot-starter-jooq

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

Pom

spring-boot-starter-json

Starter for reading and writing json

Pom

spring-boot-starter-jta-atomikos

Starter for JTA transactions using Atomikos

Pom

spring-boot-starter-jta-bitronix

Starter for JTA transactions using Bitronix

Pom

spring-boot-starter-mail

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

Pom

spring-boot-starter-mustache

Starter for building web applications using Mustache views

Pom

spring-boot-starter-oauth2-client

Starter for using Spring Security’s OAuth2/OpenID Connect client features

Pom

spring-boot-starter-oauth2-resource-server

Starter for using Spring Security’s OAuth2 resource server features

Pom

spring-boot-starter-quartz

Starter for using the Quartz scheduler

Pom

spring-boot-starter-security

Starter for using Spring Security

Pom

spring-boot-starter-test

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

Pom

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views

Pom

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator

Pom

spring-boot-starter-web

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

Pom

spring-boot-starter-web-services

Starter for using Spring Web Services

Pom

spring-boot-starter-webflux

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

Pom

spring-boot-starter-websocket

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

Pom

除应用程序启动器外,还可以使用以下启动器添加生产就绪功能:

Table 13.2. Spring Boot production starters

Name

Description

Pom

spring-boot-starter-actuator

使用Spring Boot的Actuator的初学者,它提供生产就绪功能,帮助您监控和管理您的应用程序

Pom

Spring Boot还包括以下启动器,如果要排除或交换特定的技术方面,可以使用它们:

Table 13.3. Spring Boot technical starters

Name

Description

Pom

spring-boot-starter-jetty

Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat使用Jetty作为嵌入式servlet容器的入门。替代

Pom

spring-boot-starter-log4j2

Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging开始使用Log4j2进行日志记录。 spring-boot-starter日志记录的替代方案

Pom

spring-boot-starter-logging

开始使用Logback进行日志记录。默认日志记录开始

Pom

spring-boot-starter-reactor-netty

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

Pom

spring-boot-starter-tomcat

Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web使用Tomcat作为嵌入式servlet容器的入门者。 spring-boot-starter-web使用的默认servlet容器启动器

Pom

spring-boot-starter-undertow

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

Pom

14. Structuring Your Code

14.1 Using the “default” Package

当类不包含包声明时,它被认为是在“默认包”中。 通常不鼓励使用“默认包”,应该避免使用。 对于使用@ComponentScan@ EntityScan@SpringBootApplication注释的Spring Boot应用程序,它可能会导致特定问题,因为每个jar中的每个类都被读取。推荐使用例如,com.example.project

14.2 Locating the Main Application Class

We generally recommend that you locate your main application class in a root package above other classes. The @SpringBootApplication is often placed on your main class, 它隐含地为某些项目定义了一个基础“搜索包(search package)”。例如,如果您正在编写 JPA 应用程序,则使用@SpringBootApplication带注释类的包来搜索@Entity项。使用根包还允许组件扫描仅应用于您的项目。

如果您不想使用@SpringBootApplication,导入的@EnableAutoConfiguration·@ComponentScan注解也会定义该行为,因此可以用@EnableAutoConfiguration·@ComponentScan代替@SpringBootApplication

以下清单显示了典型的布局:

com
 +- example
     +- myapplication
         +- Application.java
         |
         +- customer
         |   +- Customer.java
         |   +- CustomerController.java
         |   +- CustomerService.java
         |   +- CustomerRepository.java
         |
         +- order
             +- Order.java
             +- OrderController.java
             +- OrderService.java
             +- OrderRepository.java

Application.java文件将声明main方法以及基本的@SpringBootApplication如下:

package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

}

15. 配置类

Spring Boot支持基于Java的配置。虽然可以将SpringApplication与XML源一起使用,但我们通常建议您的主要源是单个@Configuration类。 Usually the class that defines the main method is a good candidate as the primary @Configuration.

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

15.1 Importing Additional Configuration Classes

您无需将所有@Configuration放入单个类中。@Import注释可用于导入其他配置类。或者,您可以使用@ComponentScan自动获取所有Spring components组件,包括@Configuration类。

15.2 Importing XML Configuration

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

16. 自动配置

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

您应该只添加一个one @SpringBootApplication or @EnableAutoConfiguration annotation. We generally recommend that you add one or the other to your primary @Configuration class only.

16.1 逐步更换自动配置

自动配置是非侵入性的。在任何时候,您都可以开始定义自己的配置以替换自动配置的特定部分。例如,如果添加自己的DataSource bean,则默认的嵌入式数据库支持会退回。

如果您需要了解当前正在应用的自动配置以及原因,请使用--debug开关启动您的应用程序。这样做可以为选择的核心记录器启用调试日志,并将条件报告记录到控制台。

16.2 Disabling Specific Auto-configuration Classes

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

import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

如果类不在类路径上,则可以使用批注的excludeName属性并指定完全限定名称。 最后,您还可以使用spring.autoconfigure.exclude属性控制要排除的自动配置类列表。

您可以在注释级别和使用属性定义排除项。

17. Spring Beans和依赖注入

You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. 为简单起见,我们经常发现使用@ComponentScan(找到你的bean)并使用@Autowired(做构造函数注入)效果很好。

If you structure your code as suggested above (locating your application class in a root package), you can add @ComponentScan without any arguments. All of your application components (@Component, @Service, @Repository, @Controller etc.) are automatically registered as Spring Beans.

以下示例显示了一个@Service Bean,它使用构造函数注入来获取所需的RiskAssessor bean:

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

	private final RiskAssessor riskAssessor;

	@Autowired
	public DatabaseAccountService(RiskAssessor riskAssessor) {
		this.riskAssessor = riskAssessor;
	}

	// ...

}

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

@Service
public class DatabaseAccountService implements AccountService {

	private final RiskAssessor riskAssessor;

	public DatabaseAccountService(RiskAssessor riskAssessor) {
		this.riskAssessor = riskAssessor;
	}

	// ...

}

请注意使用构造函数注入如何将riskAssessor字段标记为final,表示无法随后更改它。

18. Using the @SpringBootApplication Annotation

Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their “application class”. A single @SpringBootApplication annotation can be used to enable those three features, that is:

  • @EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism自动配置机制
  • @ComponentScan: enable @Component scan on the package where the application is located (see the best practices)在应用程序所在的包上启用@Component扫描
  • @Configuration: allow to register extra beans in the context or import additional configuration classes

允许在上下文中注册额外的bean或导入其他配置类

@SpringBootApplication注释等同于使用@ Configuration@ EnableAutoConfiguration@ComponentScan及其默认属性,如以下示例所示:

package com.example.myapplication;

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);
	}

}

@SpringBootApplication also provides aliases to customize the attributes of @EnableAutoConfiguration and @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 @EnableAutoConfiguration @Import({ MyConfig.class, MyAnotherConfig.class }) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

In this example, Application is just like any other Spring Boot application except that 未自动检测@Component-annotated类,并显式导入用户定义的bean(see @Import).

19. 运行程序

将应用程序打包为jar并使用嵌入式HTTP服务器的最大优势之一,您可以像运行任何其他应用程序一样运行应用程序。 调试Spring Boot应用程序也很容易。 您不需要任何特殊的IDE插件或扩展(IDE plugins or extensions)

本节仅介绍基于jar的包装。 如果您选择将应用程序打包为war文件,则应参阅服务器和IDE文档。

https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-running-your-application.html

20. 开发者工具

Spring Boot包含一组额外的工具,可以使应用程序开发体验更加愉快。 spring-boot-devtools模块可以包含在任何项目中,以提供额外的开发时间功能。 要包含devtools支持,请将模块依赖项添加到您的构建中,如以下Maven和Gradle列表中所示:

Maven.

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

Gradle.

configurations {
	developmentOnly
	runtimeClasspath {
		extendsFrom developmentOnly
	}
}
dependencies {
	developmentOnly("org.springframework.boot:spring-boot-devtools")
}

运行完全打包的应用程序时会自动禁用开发人员工具。 如果您的应用程序是从java -jar启动的,或者它是从特殊的类加载器启动的,那么它将被视为“生产应用程序”。 如果这不适用于您(即,如果您从容器运行应用程序),请考虑排除devtools或设置-Dspring.devtools.restart.enabled = false系统属性。

将依赖项标记为Maven中的可选项或在Gradle中使用自定义“开发”配置(如上所示)是防止devtools传递应用于使用项目的其他模块的最佳实践。

重新打包的归档默认情况下不包含devtools。如果要使用某个远程devtools功能,则需要禁用excludeDevtools构建属性以包含它。该属性由Maven和Gradle插件支持。

20.1 默认属性

Spring Boot支持的几个库使用缓存来提高性能。例如, template engines 模板引擎缓存已编译的模板以避免重复解析模板文件。此外,Spring MVC可以在提供静态资源时为响应添加HTTP缓存标头。虽然缓存在生产中非常有用,但在开发过程中可能会适得其反,使您无法看到刚刚在应用程序中进行的更改。因此,spring-boot-devtools默认禁用缓存选项。缓存选项通常由application.properties文件中的设置配置。例如,Thymeleaf提供了spring.thymeleaf.cache属性。 spring-boot-devtools模块不需要手动设置这些属性,而是自动应用合理的开发时间配置。因为在开发Spring MVC和Spring WebFlux应用程序时需要有关Web请求的更多信息,所以开发人员工具将为Web日志记录组启用DEBUG日志记录。这将为您提供有关传入请求,处理程序正在处理它,响应结果等的信息。如果您希望记录所有请求详细信息(包括可能的敏感信息),您可以打开spring.http.log-request-详细配置属性。

如果您不希望应用属性默认值,则可以在application.properties中将spring.devtools.add-properties设置为false。

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

20.2 自动重启 Automatic Restart

使用spring-boot-devtools的应用程序会在类路径上的文件发生更改时自动重新启动。 在IDE中工作时,这可能是一个有用的功能,因为它为代码更改提供了非常快速的反馈循环。 默认情况下,将监视类路径上指向文件夹的任何条目的更改。 请注意,某些资源(如静态资源和视图模板)无需重新启动应用程序。

**Triggering a restart **触发重启

As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath. The way in which you cause the classpath to be updated depends on the IDE that you are using. In Eclipse, saving a modified file causes the classpath to be updated and triggers a restart. In IntelliJ IDEA, building the project (Build -> Build Project) has the same effect.

后续:

https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-livereload

21. Packaging Your Application for Production

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

可执行jar可用于生产部署。由于它们是独立的,因此它们也非常适合基于云的部署。

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

22. 接下来的内容

您现在应该了解如何使用Spring Boot以及您应该遵循的一些最佳实践。 您现在可以继续深入了解特定的Spring Boot功能,or you could skip ahead and read about the “production ready” aspects of Spring Boot