springboot 2.1.8官方文档翻译--2.Part III使用Spring Boot

Table of Contents

Part III. 使用Spring Boot

13. Build Systems

13.1 Dependency Management

13.2 Maven

13.2.1 继承the Starter Parent

13.2.2 Using Spring Boot without the Parent POM

13.2.3 Using the Spring Boot Maven Plugin

13.3 Gradle

13.4 Ant

13.5 Starters

14. Structuring Your Code

14.1 Using the “default” Package

14.2 Locating the Main Application Class

15. Configuration Classes

15.1 Importing Additional Configuration Classes

15.2 Importing XML Configuration

16. Auto-configuration

16.1 Gradually Replacing Auto-configuration

16.2 Disabling Specific Auto-configuration Classes

17. Spring Beans and Dependency Injection(依赖注入)

18. Using the @SpringBootApplication Annotation

19. Running Your Application

19.2 Running as a Packaged Application

19.3 Using the Maven Plugin

19.4 Using the Gradle Plugin

19.5 Hot Swapping

20. Developer Tools

20.1 Property Defaults

20.2 Automatic Restart

20.2.1 Logging changes in condition evaluation

20.2.2 Excluding Resources

20.2.3 Watching Additional Paths

20.2.4 Disabling Restart

20.2.5 Using a Trigger File

20.2.6 Customizing the Restart Classloader

20.2.7 Known Limitations

20.3 LiveReload

20.4 Global Settings

20.5 Remote Applications

20.5.1 Running the Remote Client Application

20.5.2 Remote Update

20.5.3 Configuring File System Watcher

20.5.4 Security Configuration for Devtools Remote


Part III. 使用Spring Boot

本节将更详细地介绍如何使用Spring Boot。包含的话题有build systems, auto-configuration和怎样去运行你的application(应用程序)。我们也会包含一些Spring Boot最好的测试例子。对于Spring Boot虽然没有什么特别的(也就是使用一些其他的library )

如果你开始就使用Spring Boot,建议阅读前面一篇Getting Started 。

13. Build Systems

强烈建议您选择支持依赖项管理的构建系统。我们建议您选择Maven或Gradle。Spring Boot与其他构建系统(例如Ant)一起工作也是可能的,但是它们并没有得到特别好的支持。

13.1 Dependency Management

Spring Boot的每个版本都提供了一个它所支持的依赖项列表。实际上,您不需要在构建配置的时候添加每一个依赖项版本,因为Spring Boot已经帮我们提供了。当更新Spring Boot的时候,它里面包含的版本也会随之更新。

Spring Boot管理列表包含所有spring启动时可能使用到的spring模块,以及第三方库的细化列表。那个列表可以作为一个标准的Bills of Materials (spring-boot-dependencies) ,该列表能够被Maven和Gradle使用。

13.2 Maven

Maven可以从spring-boot-starter-parent中继承一些合理的默认值。parent项目提供以下功能:

  • Java 1.8作为默认编译器级别。

  • utf - 8编码。

  •  Dependency Management section 继承自spring-boot-dependencies的pom文件,管理着常用的版本。这种依赖关系管理方便你在自己的pom中使用这些依赖关系时可以省略<version>标记。

  • 合理的资源过滤。

  • 合理的插件配置(exec pluginGit commit ID, and shade)。

  • 在 application.properties 和 application.yml 配置一些自定义的属性(例如 application-dev.properties and application-dev.yml)

需要注意的是,application.properties 和application.yml 继承了spring的占位风格(${…​}),Maven过滤被更改为使用@..@占位符。

13.2.1 继承the Starter Parent

项目配置继承spring-boot-starter-parent,设置Parent如下:

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

使用下面设置,您还可以通过覆盖自己项目中的属性来覆盖各个依赖项。例如,你要更新一个新的spring data的发布版本,你可以增加如下配置:

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

13.2.2 Using Spring Boot without the Parent POM

并不是每一个都能够继承spring-boot-starter-parent 的pom文件。你可能有自己公司的标准Parent,这样的话您需要使用或更明显地声明对应的依赖的所有Maven配置。如果你不想用spring-boot-starter-parent,您可以通过使用scope=import仍然可以保留依赖项管理的好处(并不是插件管理)

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

如上所述,前面的示例设置并不能实现使用我们自定义的依赖性去覆盖之前已有的依赖项。所以我们为了达到相同的项目,在dependencyManagement 里面,spring-boot-dependencies之前添加。例如,你要更新一个新的spring data的发布版本,你可以增加如下配置:

<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.8.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

13.2.3 Using the Spring Boot Maven Plugin

Spring Boot里面包含一个maven插件,用来将项目打包成可执行的jar包。如果你要去使用它的话,添加插件到你的<plugins>标签中:

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

13.3 Gradle

如果要详细的去了解和使用Gradle,你可以看如下的相关文档:

13.4 Ant

通过 Apache Ant+Ivy来构建一个spring boot项目是完全没有问题的。ivy.xml配置文件:

<ivy-module version="2.0">
	<info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
	<configurations>
		<conf name="compile" description="everything needed to compile this module" />
		<conf name="runtime" extends="compile" description="everything needed to run this module" />
	</configurations>
	<dependencies>
		<dependency org="org.springframework.boot" name="spring-boot-starter"
			rev="${spring-boot.version}" conf="compile" />
	</dependencies>
</ivy-module>

build.xml配置

<project
	xmlns:ivy="antlib:org.apache.ivy.ant"
	xmlns:spring-boot="antlib:org.springframework.boot.ant"
	name="myapp" default="build">

	<property name="spring-boot.version" value="2.1.8.RELEASE" />

	<target name="resolve" description="--> retrieve dependencies with ivy">
		<ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
	</target>

	<target name="classpaths" depends="resolve">
		<path id="compile.classpath">
			<fileset dir="lib/compile" includes="*.jar" />
		</path>
	</target>

	<target name="init" depends="classpaths">
		<mkdir dir="build/classes" />
	</target>

	<target name="compile" depends="init" description="compile">
		<javac srcdir="src/main/java" destdir="build/classes" classpathref="compile.classpath" />
	</target>

	<target name="build" depends="compile">
		<spring-boot:exejar destfile="build/myapp.jar" classes="build/classes">
			<spring-boot:lib>
				<fileset dir="lib/runtime" />
			</spring-boot:lib>
		</spring-boot:exejar>
	</target>
</project>

13.5 Starters

Starters是一组方便的依赖关系描述符,您可以将其包含在应用程序中。您可以获得所需的所有Spring和相关技术的一站式服务,而不必遍历样例代码和进行依赖描述符的复制-粘贴负载。例如,如果您想开始使用Spring和JPA进行数据库访问,只需要把spring-boot-starter-data-jpa依赖进来即可。

Starters包含许多依赖项,这些依赖项的目的就是快速启动和运行项目,并使之保持一致。提供一系列可管理可传递的依赖。

** What’s in a name

所有的官方starters都有规范的命名方式。spring-boot-starter-* ,*号代表特定类型的应用。这种命名方式目的是方便你能够更好的找到你需要的starter。许多ide中的Maven集成允许您根据名称搜索依赖项。例如,安装了Eclipse或STS插件后,您可以在POM编辑器中按下ctrl-space并输入“spring-boot-starter”以获得完整的列表。

解释一下 “Creating Your Own Starter” 部分,第三方Starters不应该用spring-boot启动,它是为官方的Spring boot artifacts保留的。第三方Starters通常以项目的名称开始。例如,名为thirdpartyproject的第三方Starters通常被命名为thirdpartyproject-spring-boot-starter。**

以下应用程序Starters是由org.springframework下的Spring Boot提供的

Table 13.1. Spring Boot application starters

Name Description Pom

spring-boot-starter

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter/pom.xml[Pom]

spring-boot-starter-activemq

Starter for JMS messaging using Apache ActiveMQ

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-activemq/pom.xml[Pom]

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-amqp/pom.xml[Pom]

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-aop/pom.xml[Pom]

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-artemis/pom.xml[Pom]

spring-boot-starter-batch

Starter for using Spring Batch

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-batch/pom.xml[Pom]

spring-boot-starter-cache

Starter for using Spring Framework’s caching support

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-cache/pom.xml[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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-cloud-connectors/pom.xml[Pom]

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-cassandra/pom.xml[Pom]

spring-boot-starter-data-cassandra-reactive

Starter for using Cassandra distributed database and Spring Data Cassandra Reactive

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-cassandra-reactive/pom.xml[Pom]

spring-boot-starter-data-couchbase

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-couchbase/pom.xml[Pom]

spring-boot-starter-data-couchbase-reactive

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-couchbase-reactive/pom.xml[Pom]

spring-boot-starter-data-elasticsearch

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-elasticsearch/pom.xml[Pom]

spring-boot-starter-data-jdbc

Starter for using Spring Data JDBC

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-jdbc/pom.xml[Pom]

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-jpa/pom.xml[Pom]

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-ldap/pom.xml[Pom]

spring-boot-starter-data-mongodb

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-mongodb/pom.xml[Pom]

spring-boot-starter-data-mongodb-reactive

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-mongodb-reactive/pom.xml[Pom]

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-neo4j/pom.xml[Pom]

spring-boot-starter-data-redis

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-redis/pom.xml[Pom]

spring-boot-starter-data-redis-reactive

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-redis-reactive/pom.xml[Pom]

spring-boot-starter-data-rest

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-rest/pom.xml[Pom]

spring-boot-starter-data-solr

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-data-solr/pom.xml[Pom]

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-freemarker/pom.xml[Pom]

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-groovy-templates/pom.xml[Pom]

spring-boot-starter-hateoas

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-hateoas/pom.xml[Pom]

spring-boot-starter-integration

Starter for using Spring Integration

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-integration/pom.xml[Pom]

spring-boot-starter-jdbc

Starter for using JDBC with the HikariCP connection pool

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-jdbc/pom.xml[Pom]

spring-boot-starter-jersey

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-jersey/pom.xml[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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-jooq/pom.xml[Pom]

spring-boot-starter-json

Starter for reading and writing json

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-json/pom.xml[Pom]

spring-boot-starter-jta-atomikos

Starter for JTA transactions using Atomikos

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-atomikos/pom.xml[Pom]

spring-boot-starter-jta-bitronix

Starter for JTA transactions using Bitronix

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-jta-bitronix/pom.xml[Pom]

spring-boot-starter-mail

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-mail/pom.xml[Pom]

spring-boot-starter-mustache

Starter for building web applications using Mustache views

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-mustache/pom.xml[Pom]

spring-boot-starter-oauth2-client

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-oauth2-client/pom.xml[Pom]

spring-boot-starter-oauth2-resource-server

Starter for using Spring Security’s OAuth2 resource server features

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-oauth2-resource-server/pom.xml[Pom]

spring-boot-starter-quartz

Starter for using the Quartz scheduler

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-quartz/pom.xml[Pom]

spring-boot-starter-security

Starter for using Spring Security

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-security/pom.xml[Pom]

spring-boot-starter-test

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-test/pom.xml[Pom]

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-thymeleaf/pom.xml[Pom]

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-validation/pom.xml[Pom]

spring-boot-starter-web

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-web/pom.xml[Pom]

spring-boot-starter-web-services

Starter for using Spring Web Services

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-web-services/pom.xml[Pom]

spring-boot-starter-webflux

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-webflux/pom.xml[Pom]

spring-boot-starter-websocket

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-websocket/pom.xml[Pom]

除了应用程序starter之外,还可以使用以下starter添加产品准备特性:

Table 13.2. Spring Boot production starters

Name Description Pom

spring-boot-starter-actuator

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-actuator/pom.xml[Pom]

最后,Spring Boot还包括以下starter,如果您想排除或交换特定的技术方面,可以使用这些starter:

Table 13.3. Spring Boot technical starters

spring-boot-starter-jetty

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-jetty/pom.xml[Pom]

spring-boot-starter-log4j2

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-log4j2/pom.xml[Pom]

spring-boot-starter-logging

Starter for logging using Logback. Default logging starter

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-logging/pom.xml[Pom]

spring-boot-starter-reactor-netty

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-reactor-netty/pom.xml[Pom]

spring-boot-starter-tomcat

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-tomcat/pom.xml[Pom]

spring-boot-starter-undertow

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

{github-code}/spring-boot-project/spring-boot-starters/spring-boot-starter-undertow/pom.xml[Pom]

14. Structuring Your Code

Spring Boot并不要求使用特定的代码布局。下面将会有一些最佳实践可以提供帮助。

14.1 Using the “default” Package

当类不包含Package声明时,它使用的就是“default” Package。使用“default package”是不推荐使用的和尽量避免使用。在spring boot总它会引起特殊的问题,特别是在使用@ComponentScan@EntityScan, or @SpringBootApplication注解的时候,因为来自于jar中的类都会被读取。

**我们建议你使用java的Package命名方式,也就是使用颠倒命名法(例如, com.example.project). **

14.2 Locating the Main Application Class

我们通常建议将主应用程序类(main)定位在根包中,在其他类之上。@SpringBootApplication注解一般放在main类上,它隐式地为某些项目定义了一个基本的“搜索包”。例如,你写一个JPA应用,@SpringBootApplication注解就会被用来搜索@Entity。

**如果您不想使用@SpringBootApplication,那么它导入的@EnableAutoConfiguration和@ComponentScan注释定义了该行为,因此您也可以使用它。**

下面的清单显示了一个典型的布局:

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

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. Configuration Classes

Spring Boot支持Java-based(java基础)配置。尽管可以将SpringApplication与XML source一起使用,我们通常建议您的主source是单个@Configuration类。通常,定义main方法的类可以作为主@Configuration。

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

15.1 Importing Additional Configuration Classes

您不需要将所有@Configuration放到单个类中。@Import注释可用于导入其他配置类。如果不使用前面的方法或者可以使用@ComponentScan自动获取所有Spring组件,包括@Configuration类。

15.2 Importing XML Configuration

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

16. Auto-configuration

Spring Boot自动配置尝试根据添加的jar依赖项自动配置Spring应用程序。例如,如果HSQLDB在您的类路径中,并且您没有手动配置任何数据库连接bean,那么Spring Boot将自动配置它内存中的数据库。

您需要通过将@EnableAutoConfiguration或@SpringBootApplication注释添加到您的@Configuration类来选择自动配置。

**您之前只添加了一个@SpringBootApplication或@EnableAutoConfiguration注释。我们通常建议只向主@Configuration类添加其中一个即可。**

16.1 Gradually Replacing Auto-configuration

自动配置是非侵入性的。在任何时候,您都可以开始定义自己的配置来替换自动配置的特定部分。例如,如果您添加自己的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 {
}

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

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

即使自动配置类是公共的,类中唯一被认为是公共API的方面是类的名称,它可以用来禁用自动配置。这些类的实际内容,例如嵌套配置类或bean方法,仅供内部使用,我们不建议直接使用它们。**

17. Spring Beans and Dependency Injection(依赖注入)

您可以自由地使用任何标准的Spring框架技术来定义bean及其注入的依赖项。为了方便,我们经常发现使用@ComponentScan(查找和加载bean)和@Autowired(构造函数注入)一起工作非常方便。

如果按照前面的建议构造代码(将应用程序类(main)定位在根包中),则添加@ComponentScan时候不需要任何参数,自动去加载对应的bean。

所有应用程序组件(@Component、@Service、@Repository、@Controller等)都会自动注册为Spring bean。

下面的例子展示了一个@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

许多spring boot开发者喜欢使用自动装配、组件扫描、定义额外的配置在他们的"application class"。@SpringBootApplication的三个特征:

  • @EnableAutoConfiguration:启用Spring Boot的自动配置机制
  • @ComponentScan :在应用程序所在的包上启用@Component扫描(具体请看the best practices)
  • @Configuration:允许在上下文中注册额外的bean或导入额外的配置类

@SpringBootApplication注解等同于使用他们三个注解。

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还提供了别名来定制@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
@EnableAutoConfiguration
@Import({ MyConfig.class, MyAnotherConfig.class })
public class Application {

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

}

19. Running Your Application

最大优点之一是可以像运行其他应用程序一样运行应用程序通过将应用程序打包为jar并使用嵌入式HTTP服务器。但是,首先需要导入项目,导入的方式取决于你的IDE 和build system。大多数ide可以直接导入Maven项目。例如,Eclipse 使用者通过menu菜单Import…​ → Existing Maven Projects

如果您不能直接将项目导入IDE,则可以使用构建插件生成IDE元数据。Maven包括Eclipse和IDEA的插件。Gradle也为各种ide提供插件。

**如果您不小心运行了一个web应用程序两次,您会看到一个“Port already in use”错误。STS用户可以使用重新启动按钮而不是运行按钮来确保关闭任何现有实例。**

19.2 Running as a Packaged Application

如果您使用Spring Boot Maven或Gradle插件来创建一个可执行jar,您可以使用以下命令java -jar运行应用程序,如下例所示:

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

还可以在启用远程调试支持的情况下运行打包的应用程序。这样做可以将调试器附加到打包的应用程序中,如下面的示例所示:

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

19.3 Using the Maven Plugin

Spring Boot Maven插件包含一个运行目标,可用于快速编译和运行应用程序。应用程序以分解形式运行,就像在IDE中一样。下面的示例显示了运行Spring启动应用程序的典型Maven命令:

$ mvn spring-boot:run

你可能想要通过maven调整操作系统变量,如下面的例子所示:

$ export MAVEN_OPTS=-Xmx1024m

19.4 Using the Gradle Plugin

Spring Boot Gradle插件还包含一个bootRun任务,可以用它来运行你的应用程序。无论什么时候运行org.springframework.boot 和 java插件 bootRun任务都会被添加进来:

$ gradle bootRun

您可能还想使用JAVA_OPTS操作系统环境变量,如下面的示例所示:

$ export JAVA_OPTS=-Xmx1024m

19.5 Hot Swapping

因为Spring  boot应用程序只是普通的Java应用程序,JVM热交换应该开箱即用(out of the box)。JVM热交换在一定程度上受到它可以替换的字节码的限制。对于更完整的解决方案,可以使用JRebel。

spring-boot-devtools模块还支持快速重启应用程序。有关详细信息,请参阅本章后面的第20章,Developer Tools 部分Hot swapping “How-to” 。

20. Developer Tools

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 system属性。**

**在Maven中将依赖项标记为可选的,或者在Gradle中使用定制的“仅开发”配置(如上所示),这是一种最佳实践,可以防止devtools过渡地应用于使用您的项目的其他模块。**

默认情况下,重新打包的归档文件不包含devtools。如果你想使用某个远程devtools特性,您需要禁用excludeDevtools构建属性来包含它。该属性同时受到Maven和Gradle插件的支持。

20.1 Property Defaults

Spring Boot支持的几个库使用缓存来提高性能。例如,模板引擎缓存已编译的模板,以避免重复解析模板文件。此外,在提供静态资源时,Spring MVC会将HTTP缓存头添加到响应中。虽然缓存在生产中非常有用,但在开发过程中可能会适得其反,阻止您查看刚刚在应用程序中进行的更改。出于这个原因,spring-boot-devtools默认禁用缓存选项。缓存选项通常由应用程序中的application.properties的文件设置。例如,Thymeleaf提供spring.thymeleaf缓存属性。spring-boot-devtools模块不需要手动设置这些属性,而是自动应用合理的development-time配置。

因为在开发Spring MVC和Spring WebFlux时需要更多关于web请求的信息。开发人员工具将为web日志组启用DEBUG日志。这将为您提供有关传入请求、正在处理它的处理程序、响应结果等信息。如果你想要日志记录下所有的细节,你可以打开spring.http.log-request-details配置属性。

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

获取devtools应用的属性的完整列表,请参考DevToolsPropertyDefaultsPostProcessor.

20.2 Automatic Restart

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

20.2.1 Logging changes in condition evaluation

默认情况下,每次应用程序重新启动时,都会记录一个显示条件评估增量的报告。该报告显示了在进行更改(如添加或删除bean和设置配置属性)时对应用程序自动配置的更改。若要禁用报告的日志记录,请设置以下属性:

spring.devtools.restart.log-condition-evaluation-delta=false

20.2.2 Excluding Resources

某些资源在更改时不一定需要重新启动。例如,Thymeleaf模板可以就地(in-place)编辑。默认情况下,更改/META-INF/maven、/META-INF/resources、/resources、/static、/public或/templates中的资源不会触发重启,但会触发动态重新加载( live reload)。

如果您想要自定义这些排除,您可以使用spring.devtools.restart.exclude属性。例如,要仅排除/static和/public,您需要设置以下属性:

spring.devtools.restart.exclude=static/**,public/**

**如果你想要保持默认值的情况下增加排除的地址,那么可以使用spring.devtools.restart. additionation -exclude属性。**

20.2.3 Watching Additional Paths

你可能希望应用程序重新启动或重新加载那些你所更改的但不在类路径上的文件。 你可以使用spring.devtools.restart.additional-paths属性去配置。可以使用前面描述的spring.devtools.restart.exclude属性来控制附加路径下的更改是触发完全重新启动还是实时重新加载。

20.2.4 Disabling Restart

在大多数情况下,可以在应用程序中设置此属性。属性(这样做仍然会初始化restart classloader,但它不会监视文件更改)。

如果您需要完全禁用重新启动支持(例如,因为它不能与特定的库一起工作),您需要在调用SpringApplication.run(…)之前将spring.devtools.restart.enabled系统属性设置为false,如下面的示例所示:

20.2.5 Using a Trigger File

如果您使用的IDE不断地编译更改后的文件,那么您可能更希望只在特定的时间触发重新启动。为此,您可以使用一个“触发器文件”(trigger file),它是一个特殊的文件,当您想要实际触发重启检查时,必须对其进行修改。

要使用触发器文件,将spring.devtools.restart.trigger-file属性设置为您的触发器文件的名称(不包括任何路径)。触发器文件必须出现在类路径中的某个位置。例如:

src
+- main
   +- resources
      +- .reloadtrigger

触发文件属性:

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

现在只会在src/main/resources/.reloadtrigger 更新时重启。

20.2.6 Customizing the Restart Classloader

正如前面在Restart vs Reload一节中所描述的,重新启动功能是通过使用两个类加载器实现的。对于大多数应用程序,这种方法工作得更好。然而,它有时也会出现类加载问题。

默认情况下,IDE中任何打开的项目都是用“restart”类加载器加载的,而任何常规的.jar文件都是用“base”类加载器加载的。

如果您处理的是一个多模块项目,而不是每个模块都导入到IDE中,那么您可能需要自定义一些东西。为此,您可以创建一个META-INF/spring-devtools.properties文件。

spring-devtools.properties文件包含的属性前缀restart.exclude 和restart.include。include里面的元素都被放入到“restart”启动器中。exclude里面的元素放入到 “base” 启动器中。属性的值是一个应用到类路径的regex模式,如下面的例子所示:

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

20.2.7 Known Limitations

对于使用标准ObjectInputStream反序列化的对象,重新启动功能不能很好地工作。如果你不需要去反序列化数据的话,你可以使用ConfigurableObjectInputStream再结合Thread.currentThread().getContextClassLoader()

不幸的是,一些第三方库在反序列化时没有考虑上下文类加载器。如果您发现这样的问题,您需要向原始作者请求修复。

20.3 LiveReload

spring-boot-devtools模块包含一个内嵌的LiveReload服务器,可以用来在资源更改时触发浏览器刷新。从livereload.com可以免费获得Chrome、Firefox和Safari的LiveReload浏览器扩展。

如果您不想在应用程序运行时启动LiveReload服务器,您可以将spring.devtools.livereload.enabled属性设置为false。

20.4 Global Settings

你可以配置一个全局的devtools 设置通过增加一个文件名为.spring-boot-devtools.properties的文件放到你的$HOME目录下(注意,文件名以“.”开头)

添加到此文件的任何属性都适用于您机器上使用devtools的所有Spring启动应用程序。例如,要将restart配置为始终使用触发器文件,您需要添加以下属性:

~/.spring-boot-devtools.properties. 

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

20.5 Remote Applications

Spring Boot开发人员工具并不局限于本地开发。在远程运行应用程序时,还可以使用几个特性。远程支持是可选的,启用它,您需要确保重新打包的存档文件中包含devtools,如下面的清单所示:

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

你需要设置spring.devtools.remote.secret属性,如下

spring.devtools.remote.secret=mysecret

远程devtools支持分为两部分:接受连接的服务器端端点和在IDE中运行的客户机应用程序。当设置了spring.devtools.remote.secret,服务器组件是自动启用的。客户端组件必须手动启动。

20.5.1 Running the Remote Client Application

远程客户端应用程序设计为在IDE中运行。您需要使用与您连接的远程项目相同的类路径来运行org.springframework.boot.devtools.RemoteSpringApplication。应用程序唯一需要的参数是它所连接的远程URL。

例如,如果你正在使用Eclipse或STS,你有一个名为my-app的项目,你已经部署到Cloud Foundry,你需要做如下的操作:

  1. Select Run Configurations…​ from the Run menu.
  2. Create a new Java Application “launch configuration”.
  3. Browse for the my-app project.
  4. Use org.springframework.boot.devtools.RemoteSpringApplication as the main class.
  5. Add https://myapp.cfapps.io to the Program arguments (or whatever your remote URL is).

正在运行的远程客户端可能类似于以下清单:

 .   ____          _                                              __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _          ___               _      \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` |        | _ \___ _ __  ___| |_ ___ \ \ \ \
 \\/  ___)| |_)| | | | | || (_| []::::::[]   / -_) '  \/ _ \  _/ -_) ) ) ) )
  '  |____| .__|_| |_|_| |_\__, |        |_|_\___|_|_|_\___/\__\___|/ / / /
 =========|_|==============|___/===================================/_/_/_/
 :: Spring Boot Remote :: 2.1.8.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   : Start

20.5.2 Remote Update

远程客户端以与本地重启相同的方式监视应用程序类路径的更改。任何更新的资源都会被推送到远程应用程序并(在需要的时候)触发重启。如果您在一个使用本地没有的云服务的特性上进行迭代,这可能会很有帮助。通常,远程更新和重新启动比完整的重新构建和部署周期要快得多。

20.5.3 Configuring File System Watcher

FileSystemWatcher的工作方式是,在一定的时间间隔内轮询类更改,然后等待一段预定义的静默期时间,以确保在这个时期内不再发生更改。然后将更改上传到远程应用程序。类中的更改可以被切分诚批。第一批更改的类上传之后,服务器将重新启动。下一批数据不能发送到应用程序,因为服务器正在重新启动。

这通常通过RemoteSpringApplication日志中关于未能上载某些类的警告表现出来,然后重试。但它也可能导致应用程序代码不一致,并且在上传第一批更改后无法重新启动。

如果您经常观察到这类问题,请尝试将spring.devtools.restart.poll-interval和spring.devtools.restart.quiet-period参数增加到适合您的开发环境的值:

spring.devtools.restart.poll-interval=2s
spring.devtools.restart.quiet-period=1s

被监视的classpath文件夹现在每2秒轮询一次,以查找更改,并保持1秒的静默期,以确保没有其他类更改。

20.5.4 Security Configuration for Devtools Remote

如果您在类路径上有Spring Security,您可能会在RemoteSpringApplication的日志中观察到HTTP错误401或403:

Exception in thread "File Watcher" java.lang.IllegalStateException: Unexpected 401 UNAUTHORIZED response uploading class files

类上传的URL应该不受web安全性和csrf过滤器的限制。下面的示例展示了如何配置对远程devtools端点的匿名访问:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.requestMatchers("/.~~spring-boot!~/restart").anyRequest().anonymous()
			.and().csrf().disable();
	}

}
发布了469 篇原创文章 · 获赞 94 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_37909508/article/details/101866557