# SpringBoot devtools集成
## 简介
Spring Boot 提供了一组开发工具 `spring-boot-devtools` 可以提高开发者的工作效率,开发者可以将该模块包含在任何项目中,[spring-boot-devtools](https://so.csdn.net/so/search?q=spring-boot-devtools&spm=1001.2101.3001.7020) 最方便的地方莫过于热部署了。
**SpringBoot devtools实现热部署说明:**
1 自动重启
spring-boot-devtools热部署是对修改的类和配置文件进行重新加载,所以在重新加载的过程中会看到项目启动的过程,其本质上只是对修改类和配置文件的重新加载,所以速度极快。
原理:引入devtools之后,项目会用一个base类加载器来加载不改变的类,而会用restart类加载器来加载改变的类。当项目产生修改时,base类加载器不变化,而restart类会重建。类修改时,只对修改过的类重新加载,使得项目重新启动时速度极快。
2 缓存禁用
spring-boot-devtools 对于前端使用模板引擎的项目,能够自动禁用缓存,在页面修改后,只需要刷新浏览器器页面即可。
原理:缓存可以提高性能,但在有模板引擎的开发中,模板引擎会缓存编译过的模板,防止重复解析模板,这会导致修改页面内容时,模板引擎不去重新解析模板,看不到修改过的内容,但devtools在开发环境中默认关闭模板引擎的缓存功能。devtools不会被打包进jar包或war包中,在生产环境中,模板引擎的缓存功能就可以正常使用了。
## devtools 实战
### 部署
**步骤1**
创建maven项目
**步骤2**
pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.guangjun.spring.boot2</groupId>
<artifactId>springboot2-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>springboot2-devtools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot2-devtools</name>
<description>springboot2-devtools</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
<finalName>springboot2-devtools</finalName>
</build>
</project>
```
**步骤3**
application.yaml
```
server:
port: 9000
servlet:
context-path: /
spring:
devtools:
restart:
enabled: true
additional-paths:
- src/main/java
exclude: WEB-INF/**
livereload:
enabled: true
```
新版本迁至
package cn.guangjun.spring.boot2.devtools;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Springboot2DevtoolsApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot2DevtoolsApplication.class, args);
}
}