Spring Boot官方文档学习——使用Spring Boot

1. 简述

    本文将详细介绍如何使用Spring Boot。本文将覆盖系统构建、自动配置、如何运行应用。还会包含一些Spring Boot最佳实践。尽管Spring Boot没有什么特殊的地方(它仅仅是你可以使用的一个类库而已)但是仍然有一些意见你可以采纳。这些意见将会使得你的开发更加容易一些。

2. 构建系统

    强烈建议您选择支持依赖管理的构建系统,并且可以使用发布到“Maven Central”存储库的工件。 官方建议您选择MavenGradle虽然 Spring Boot可以与其他构建系统(例如Ant)一起工作,但是它们不会得到特别好的支持。

2.1 依赖管理    

Spring Boot的每个发行版都提供了一个支持的依赖列表。 在实践中,您不需要为构建配置中的任何这些依赖项提供一个版本,因为Spring Boot正在为您进行管理。 当您升级Spring Boot本身时,这些依赖关系也将以一致的方式升级。

    如果您觉得有必要,您仍然可以指定一个版本并覆盖Spring Boot的建议版本

    支持的依赖列表包含您可以使用Spring Boot的所有模块以及第三方库的精炼列表。 该列表可作为标准的spring-boot-dependencies清单提供,并且还提供MavenGradle的其他专用支持。

    Spring Boot的每个版本都与Spring Framework的基础版本相关联,因此官方强烈建议您不要自行指定其版本。

2.2 Maven    

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

  • Java 1.6作为默认的编译器级别。
  • UTF-8源码编码。
  • 依赖管理部分,继承自Spring-Boot-dependencies POM的通用依赖项允许您省略的<version>标记。
  • 合理的的资源过滤。
  • 合理的插件配置(exec plugin, surefire, Git commit ID, shad)。
  • application.propertiesapplication.yml进行合理的资源过滤,包括特定于配置文件的文件(例如application-foo.propertiesapplication-foo.yml  

2.2.1 继承父Starter

要将项目配置为从spring-boot-starter-parent继承,只需设置父项:

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

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

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

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

https://github.com/spring-projects/spring-boot/blob/v1.5.10.RELEASE/spring-boot-dependencies/pom.xml

2.2.2 不使用父Starter来创建Spring Boot应用

        不是每个人都喜欢从spring-boot-starter-parent POM继承。 你可能有你自己的企业标准的parent可以使用,或者你可能只是喜欢显式声明所有的Maven配置。

        如果你不想使用spring-boot-starter-parent,你仍然可以通过使用scope = import dependency来保持依赖管理的好处(但不是插件管理):

<dependencyManagement>
     <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.10.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>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.10.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2.2.3 修改Java版本

        spring-boot-starter-parent选择相当保守的Java兼容性。 如果您想遵循官方的建议并使用较新的Java版本,则可以添加一个java.version属性:

<properties>
    <java.version>1.8</java.version>
</properties>

2.2.4 使用Spring Boot Maven插件

        Spring Boot包含一个Maven插件,可以将项目打包为可执行的jar文件。 如果你想使用它,请将插件添加到<plugins>部分:

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

        如果你使用Spring Boot starter parent pom,你只需要添加插件,除非你想改变在父代中定义的设置,否则不需要进行配置。

2.3 Gradle

        Gradle用户可以直接在他们的依赖部分导入'starters'。 与Maven不同的是,没有“super parent”可以导入来共享某些配置。

repositories {
    jcenter()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.5.10.RELEASE")
}

        spring-boot-gradle-plugin也是提供了创建可执行的jar和从源代码运行项目的任务的功能 它还提供依赖性管理,还允许您省略由Spring Boot管理的任何依赖项的版本号:

plugins {
    id 'org.springframework.boot' version '1.5.10.RELEASE'
    id 'java'
}


repositories {
    jcenter()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

3 Starters

        Starters是一套方便的依赖描述符,可以包含在应用程序中。 您可以获得所需的所有Spring及相关技术的一站式服务,无需搜索示例代码,也不需要复制粘贴大量的依赖关系描述符。 例如,如果你想开始使用SpringJPA进行数据库访问,只需在你的项目中加入spring-boot-starter-data-jpa依赖项,你就可以开始了。

       Starters包含很多您需要快速启动并运行一个项目依赖项,并使用一组支持的传递依赖项。

        所有官方starters都遵循类似的命名模式; spring-boot-starter- *,其中*是特定类型的应用程序。 这种命名结构旨在帮助您找到启动器。 许多IDE中的Maven集成允许您按名称搜索依赖项。 例如,安装适当的EclipseSTS插件后,只需在POM编辑器中点击ctrl-space并键入“spring-boot-starter”即可获得完整列表。

        第三方starters不应该以spring-boot命名作为开始,因为它是为官方的Spring Boot预留的。 acme的第三方starter通常被命名为acme-spring-boot-starter

Name

Description

spring-boot-starter

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

spring-boot-starter-activemq

Starter for JMS messaging using Apache ActiveMQ

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

spring-boot-starter-batch

Starter for using Spring Batch

spring-boot-starter-cache

Starter for using Spring Framework’s caching support

spring-boot-starter-cloud-connectors

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

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

spring-boot-starter-data-couchbase

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

spring-boot-starter-data-elasticsearch

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

spring-boot-starter-data-gemfire

Starter for using GemFire distributed data store and Spring Data GemFire

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

spring-boot-starter-data-mongodb

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

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

spring-boot-starter-data-redis

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

spring-boot-starter-data-rest

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

spring-boot-starter-data-solr

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

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

spring-boot-starter-hateoas

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

spring-boot-starter-integration

Starter for using Spring Integration

spring-boot-starter-jdbc

Starter for using JDBC with the Tomcat JDBC connection pool

spring-boot-starter-jersey

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

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

spring-boot-starter-jta-atomikos

Starter for JTA transactions using Atomikos

spring-boot-starter-jta-bitronix

Starter for JTA transactions using Bitronix

spring-boot-starter-jta-narayana

Spring Boot Narayana JTA Starter

spring-boot-starter-mail

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

spring-boot-starter-mobile

Starter for building web applications using Spring Mobile

spring-boot-starter-mustache

Starter for building MVC web applications using Mustache views

spring-boot-starter-security

Starter for using Spring Security

spring-boot-starter-social-facebook

Starter for using Spring Social Facebook

spring-boot-starter-social-linkedin

Stater for using Spring Social LinkedIn

spring-boot-starter-social-twitter

Starter for using Spring Social Twitter

spring-boot-starter-test

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

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator

spring-boot-starter-web

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

spring-boot-starter-web-services

Starter for using Spring Web Services

spring-boot-starter-websocket

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

        

    除了应用程序starter之外,还可以将以下starter添加到准生产功能:

Name

Description

spring-boot-starter-actuator

Spring Boot的 Actuator Starter帮助您监控和管理您的应用程序

spring-boot-starter-remote-shell

使用CRaSH Starter远程shell通过SSH监视和管理您的应用程序。 自1.5以来已弃用

    

    最后,Spring Boot还包括一些可以用来排除或交换特定技术方面的starter:

Name

Description

spring-boot-starter-jetty

Jetty作为内嵌的servlet容器的starterspring-boot-starter-tomcat的替代方案

spring-boot-starter-log4j2

用Log4j2记录日志的Starter。spring-boot-starter-logging的替代方案。

spring-boot-starter-logging

使用Logback进行日志记录的Starter。 默认日志启动器

spring-boot-starter-tomcat

使用Tomcat作为嵌入式servlet容器的starter。 spring-boot-starter-web使用的默认servlet容器启动器

spring-boot-starter-undertow

使用Undertow作为内嵌的servlet容器。spring-boot-starter-tomcat的替代方案

4 代码布局

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

4.1 默认包

    当一个类不包含包声明时,它被认为是在“默认包”中。 通常不鼓励使用“默认软件”,应该避免使用“默认软件”。 对于使用@ComponentScan,@EntityScan或@SpringBootApplication注释的Spring Boot应用程序来说,这可能会导致问题,因为每个jar的每个类都将被读取。官方建议您遵循Java推荐的软件包命名约定,并使用反向域名(例如,com.example.project)。

4.2 主类的位置

        官方通常建议您将主应用程序类放在其他类的根包中。 @EnableAutoConfiguration注解通常放在主类上,它隐式地为某些项目定义了一个基本的“搜索包”。 例如,如果您正在编写JPA应用程序,则被@EnableAutoConfiguration注解的类的所在的包将用于搜索@Entity。使用根包也使得@ComponentScan注释不需要指定basePackage属性。 如果您的主类位于根包中,也可以使用@SpringBootApplication注释。这是一个典型的布局:

com

 +- example

     +- myproject

         +- Application.java

         |

         +- domain

         |   +- Customer.java

         |   +- CustomerRepository.java

         |

         +- service

         |   +- CustomerService.java

         |

         +- web

             +- CustomerController.java

5 配置类

Application.java文件声明main方法以及基本的@Configuration

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注解。

5.1 添加额外的配置

    你不需要把所有的@Configuration放到一个类中。 @Import注释可用于导入其他配置类。 或者,您可以使用@ComponentScan自动获取所有Spring组件,包括@Configuration类。

5.2 引入XML配置 

        如果您必须要使用基于XML的配置,建议您仍以@Configuration类开头。 然后您可以使用额外的@ImportResource注解来加载XML配置文件。

6 自动配置

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

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

        您可以只添加一个@EnableAutoConfiguration注释。 我们通常建议您将其添加到您的被@Configuration注解的主类上。

6.1 关闭指定项的自动配置

    如果您发现正在应用您不需要的特定自动配置类,则可以使用@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属性来控制自动配置类的列表。您可以在注释级别和使用属性中定义排除。

7 使用@SpringBootApplication注解

    许多Spring Boot开发人员总是使用@Configuration,@EnableAutoConfiguration和@ComponentScan注解其主类。 由于这些注释经常一起使用(特别是如果您遵循以上最佳实践),Spring Boot提供了一种方便的@SpringBootApplication替代方法。@SpringBootApplication注释等价于使用@Configuration,@EnableAutoConfiguration和@ComponentScan三个注解的默认属性:

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

    @SpringBootApplication还提供别名来自定义@EnableAutoConfiguration和@ComponentScan的属性。

/*
 * Copyright 2012-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AliasFor;

/**
 * Indicates a {@link Configuration configuration} class that declares one or more
 * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
 * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience
 * annotation that is equivalent to declaring {@code @Configuration},
 * {@code @EnableAutoConfiguration} and {@code @ComponentScan}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 1.2.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

   /**
    * Exclude specific auto-configuration classes such that they will never be applied.
    * @return the classes to exclude
    */
   @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")
   Class<?>[] exclude() default {};

   /**
    * Exclude specific auto-configuration class names such that they will never be
    * applied.
    * @return the class names to exclude
    * @since 1.3.0
    */
   @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
   String[] excludeName() default {};

   /**
    * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
    * for a type-safe alternative to String-based package names.
    * @return base packages to scan
    * @since 1.3.0
    */
   @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
   String[] scanBasePackages() default {};

   /**
    * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
    * scan for annotated components. The package of each class specified will be scanned.
    * <p>
    * Consider creating a special no-op marker class or interface in each package that
    * serves no purpose other than being referenced by this attribute.
    * @return base packages to scan
    * @since 1.3.0
    */
   @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
   Class<?>[] scanBasePackageClasses() default {};

}

8 启动Spring Boot应用   

    将应用程序打包为jar并使用内嵌的HTTP服务器的最大优点之一就是您可以像运行其他应用程序一样运行应用程序。 调试Spring Boot应用程序也很容易; 你不需要任何特殊的IDE插件或扩展。

8.1 从IDE启动Spring Boot应用

    您可以从IDE运行Spring Boot应用程序作为一个简单的Java应用程序,但是,首先您需要导入您的项目。 导入步骤取决于您的IDE和构建系统。 大多数IDE可以直接导入Maven项目。

    如果您不小心运行了两次Web应用程序,则会看到“端口已被使用”错误。 STS用户可以使用“重新启动”按钮而不是“运行”来确保关闭任何现有的实例。

Description:

The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.

8.2 运行打包的Spring Boot应用

    如果您使用Spring Boot Maven或Gradle插件创建可执行jar,则可以使用java -jar运行应用程序。 例如:

    假设现在打了一个jar包:

执行以下命令行:java -jar target/demo-0.0.1-SNAPSHOT.jar

ps -ef | grep spring

可以看到jar包已运行

8.3 使用Maven插件运行Spring Boot应用

    Spring Boot Maven插件包含一个可用于快速编译和运行应用程序的运行目标。 应用程序以分解形式运行,就像在IDE中一样。

mvn spring-boot:run

如果还想使用一些的操作系统环境变量可以如下操作:

export MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=128M

8.4 使用Gradle插件运行Spring Boot应用

        Spring Boot Gradle插件也包含一个bootRun任务,可用于以分解形式运行您的应用程序。 只要导入spring-boot-gradle-plugin,都会添加bootRun任务:

gradle bootRun

如果还想使用一些的操作系统环境变量可以如下操作:

export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M

8.5 热转换技术

    由于Spring Boot应用程序只是普通的Java应用程序,所以JVM可以提供开箱即用热插拔技术 JVM热交换在某种程度上受限于它可以替换的字节码,为了获得更完整的解决方案,可以使用JRebel或Spring Loaded项目。 spring-boot-devtools模块包括了对快速应用程序重新启动的支持。

9 开发者工具

        Spring Boot包含一组额外的工具,可以使应用程序开发体验更愉快。 spring-boot-devtools模块可以包含在任何项目中以节省开发时间。 要包含devtools支持,只需将模块依赖关系添加到您的版本:

Maven.

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

Gradle.

dependencies {
    compile("org.springframework.boot:spring-boot-devtools")
}

        运行完整打包的应用程序时,开发者工具会自动禁用。如果您的应用程序是使用java -jar启动的,或者如果它是使用特殊的类加载器启动的,那么它就被认为是“生产应用程序”。 将开发者工具依赖关系标记为可选项是一种最佳实践,可以防止devtools通过项目传递到其他模块。 Gradle不支持可选的依赖关系,因此您可能需要查看一下propdeps插件。

    如果您想使用某些远程devtools功能,则需要禁用excludeDevtools构建属性。 该属性Maven和Gradle插件都支持。

9.1 自动重启

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

    由于DevTools监视类路径资源,触发重启的唯一方法是更新类路径。 导致类路径更新的方式取决于您使用的IDE。 在Eclipse中,保存修改后的文件将导致类路径更新并触发重启。 在IntelliJ IDEA中,构建项目(Build - > Make Project)将具有相同的效果。

    DevTools在重新启动期间依靠应用程序上下文的shutdown钩子发挥作用 如果您禁用了shutdown钩子SpringApplication.setRegisterShutdownHook(false)),它将无法正常工作。

    Spring Boot提供的重启技术通过使用两个类加载器来工作。 没有变更的类(例如来自第三方jar的类)被加载到基类加载器中。 您正在开发的类将加载到重启类加载器中。 当应用程序重新启动时,重启类加载器将被丢弃,并创建一个新的。 这种方法意味着应用程序重新启动通常比“冷启动”快得多,因为基类加载器已经可用并且已经加载了一些类。

    如果您发现重新启动对于您的应用程序来说不够快,或者遇到类加载问题,则可以考虑从ZeroTurnaround中寻找重新加载技术,例如JRebel。 这些技术通过重写被加载的类,使他们更容易重新加载。 Spring Loaded也是一种选择方式,但是它支持的框架不多,并且没有商业支持。

9.1.1 排除一部分文件修改导致重启

    某些资源不一定需要在更改时触发重新启动。 例如,Thymeleaf模板可以就地编辑。 默认情况下,更改/ META-INF / maven,/ META-INF / resources,/ resources,/ static,/ public或/ templates中的资源不会触发重新启动,但会触发实时重新加载。 如果你想自定义排除一些资源,你可以使用spring.devtools.restart.exclude属性。 例如,要仅排除/ static和/ public,您可以设置以下内容:

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

如果要保留这些默认值并添加其他排除项,请改为使用spring.devtools.restart.additional-exclude属性。

9.1.2 关闭自动重启

    如果您不想使用重新启动功能,则可以使用spring.devtools.restart.enabled属性将其禁用。 在大多数情况下,你可以在你的application.properties中设置它(这将仍然初始化restart classloader,但它不会监视文件的变化)。

    如果您需要完全禁用重新启动支持,例如,比如它不适用于特定的库,则需要在调用SpringApplication.run(...)之前设置System属性。 例如:

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

        如果您使用编译器的时候频繁的编译更改文件的文件,你可能只希望在特定时间触发重新启动。 要做到这一点,你可以使用“触发文件”,这是一个特殊的文件,当你想要实际触发重新启动检查时必须修改这个文件。更改文件会触发检查,只有Devtools检测到必须执行某些操作时才会重新启动。 触发文件可以手动更新,也可以通过IDE插件进行更新。

    要使用触发器文件,请使用spring.devtools.restart.trigger-file属性。

9.1.3 自动重启类加载器

    重新启动功能是通过使用两个类加载器来实现的。 对于大多数应用程序来说,这种方法运行良好,但有时候会导致类加载问题。

    默认情况下,IDE中的任何打开的项目都将使用重启类加载器加载,任何常规的*.jar文件都将使用基本类加载器加载。 如果您使用多模块项目,而不是将每个模块导入IDE,则可能需要自定义项目。 要做到这一点,你可以创建一个META-INF / spring-devtools.properties文件。

    spring-devtools.properties文件可以包含restart.exclude.restart.include.前缀属性。 include元素是应该被拉入到“重启”类加载器中的项目,exclude元素是应该被下推到“基本”类加载器中的项目。 该属性的值是一个作用于类路径的正则表达式。

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

10 git demo地址

https://github.com/PerseveranceForever/first_spring_demo

猜你喜欢

转载自blog.csdn.net/shixuetanlang/article/details/79313853