原理:
- 在class字节码发生变动时,可以让classloader重新加载,而达到不重启应用的效果。
- 以下介绍的两种工具都使用了相同的手段:更换了类加载器!!!
devtools.restart.classloader.RestartClassLoader
而不是
sun.misc.Launcher$AppClassLoader - 日志中的变化:
如果日志出现了 [ restartedMain] ,即表示更换成功!
2019-08-22 13:05:59.761 INFO 3504 --- [ restartedMain] cn.johnyu.demo02.Demo02Application :
工具:
一、 springloaded
1. 配置方法 pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
2. 启动方法:
mvn spring-boot:run
3. 缺点:
只能使用maven方式启动,否则无法达到目的。
二、spring-boot-devtools
1. 配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
2. 启动:
无限制
3. 需要注意:
(1)在application.properties中加入[可选操作]:
#禁止thymeleaf缓存(建议:开发环境设置为false,生成环境设置为true)
spring.thymeleaf.cache=false
#添加那个目录的文件需要restart
spring.devtools.restart.additional-paths=src/main/java
#排除那个目录的文件不需要restart
spring.devtools.restart.exclude=static/**,public/**
(2)在idea进行配置【必选】:
打开自动自动构建功能
Preferences -> Build, Execution, Deployment -> Compiler,勾选Build project automatically
运行期自动编译(不重启动应用):
进入Registry...中(Mac使用快捷键shift+option+command+/,window上的快捷键是Shift+Ctrl+Alt+/)
勾选:compiler.automake.allow.when.app.running
4. 禁用此功能:
硬编码:System.setProperty("spring.devtools.restart.enabled", "false");
application.properties: spring.devtools.restart.enabled 注意原因不明,不起作用
较全的pom.xml中的片段:
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>