Spring boot devtools 热部署
当我们使用IDEA编辑工具进行java开发时,需要面临一个项目重启的问题。每次更改完代码时,项目必须手动重启,这将耗费很多的时间。此时devtools工具给这个问题带来了转机。
1.devtools介绍
spring-boot-devtools会检测类路径的变化,当类路径内容发生变化后会自动重启应用程序。Spring Boot的重启技术通过使用两个类加载器。由于使用的是双类加载机制重启会非常快,如果启动比较慢,那就只能使用重新加载技术JRebel了。
(1)base classloader (Base类加载器):加载不改变的Class,例如:第三方提供的jar包。
(2)restart classloader(Restart类加载器):加载正在开发的Class。
到这里相信大家知道了,为什么重启很快,因为重启的时候只是加载了在开发的Class,没有重新加载第三方的jar包。
2.devtools使用
1.在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
2.在pom.xml中添加插件
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
3.更改配置
1.打开项目自动构建设置
File – > settings – > Build,Execution,Deployment–> Compiler
2.配置自动加载
(1)勾选compiler.automake.allow.when.app.running
Ctrl+shift+Alt+/ -> Registry
选中打勾 “compiler.automake.allow.when.app.running”
由于IDEA 2021版本之后,compiler.automake.allow.when.app.running就在上述方式找不到了,这里是迁移到了settings中。
File – > settings – >Advanced Settings
部署工作就算是完成了,重启IDEA即可。
注意
Devtools热部署工具,只是在开发阶段使用,方面代码的更改操作,在实际的项目运行时,一定要关闭,避免资源的浪费。关闭方法如下:
1.在application.properties文件中加入属性:spring.devtools.restart.exclude=false
2.或者通过编程式禁用代码如下:
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(MyApp.class, args);
}
热部署介绍完毕,如有错误,请评论修订,谢谢!