平日里开发项目中,修改了Java代码或者配置文件的时候,必须手动重启项目才能生效。所谓的热部署就是在你修改了后端代码后不需要手动重启,工具会帮你快速的自动重启是修改生效。原理就是重启项目,但比手动重启快多了,其深层原理是使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个ClassLoader加载会更改的类,称为restart
ClassLoader,这样在有代码更改的时候,原来的restart ClassLoader 被丢弃,重新创建一个restart
ClassLoader,由于需要加载的类相比较少,所以实现了较快的重启时间。
灵感来源于1948
引入Devtools
假如我们已经搭建一个简单的Spring Boot项目,然后引入Spring-Boot-devtools:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),因为其采用的虚拟机机制,该项重启是很快的。
在IDEA中生效还需要修改spring-boot-maven-plugin插件:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
自动重启
使用spring-boot-devtools的应用程序在类路径更改时自动重新启动。当在IDE中工作时,这可能是一个有用的特性,因为它为代码更改提供了非常快速的反馈循环。默认情况下,指向一个文件夹的类路径上的任何条目都会被监控以进行更改。请注意,某些资源(如静态资产和视图模板)不需要重新启动应用程序
实际开发中不可能每次改动后都手动Build,因此需要设置Idea的自动编译。
File --> Settings --> Compiler --> Build Project automatically
ctrl + shift + alt + / --> Registry --> 勾选Compiler autoMake allow when app running
测试热部署
创建controller
package com.kaleldo.kaleldo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class testController {
@RequestMapping("/index")
public String hello(){
return "hello spring boot" ;
}
}
启动项目
访问http://127.0.0.1:8080/index
修改内容
再次访问
成功,欧耶
DevTools配置信息
# Whether to enable a livereload.com-compatible server.
spring.devtools.livereload.enabled=true
# Server port.
spring.devtools.livereload.port=35729
# Additional patterns that should be excluded from triggering a full restart.
spring.devtools.restart.additional-exclude=
# Additional paths to watch for changes.
spring.devtools.restart.additional-paths=
# Whether to enable automatic restart.
spring.devtools.restart.enabled=true
# Patterns that should be excluded from triggering a full restart.
spring.devtools.restart.exclude=META-INF/maven/**,META-INF/resources/**,resources/**,static/**,public/**,templates/**,**/*Test.class,**/*Tests.class,git.properties,META-INF/build-info.properties
# Whether to log the condition evaluation delta upon restart.
spring.devtools.restart.log-condition-evaluation-delta=true
# Amount of time to wait between polling for classpath changes.
spring.devtools.restart.poll-interval=1s
# Amount of quiet time required without any classpath changes before a restart is triggered.
spring.devtools.restart.quiet-period=400ms
# Name of a specific file that, when changed, triggers the restart check. If not specified, any classpath file change triggers the restart.
spring.devtools.restart.trigger-file=