spring為開發者提供了一個名為
spring-boot-devtools
的模塊來使Spring Boot應用支持熱部署,提高開發者的開發效率,無需手動重啟Spring Boot應用。
devtools實現原理:
- 采用雙類加載機制
- base ClassLoader : 加載第三方jar包(很少修改)
- restart ClassLoader :加載自己創建的類文件
應用重啟時只需要重新new一個restart ClassLoader即可,加載jar包的base ClassLoader無需加載,所以devtools重啟速度很快,提升效率
在pom文件中添加devtools依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<!-- optional=true,依賴不會往下傳遞,
如果有項目依賴本項目,並且想要使用devtools,需要重新引入 -->
<optional>true</optional>
<scope>runtime</scope>
</dependency>
idea自動編譯設置
File
->Settings
->Build,Execution,Deplyment
->Compiler
,選中打勾 “Build project automatically”Shift+Ctrl+Alt+/
=> 選擇Registry
=> 找到“compiler.automake.allow.when.app.running”並選中tips : 我設置自動編譯后,devtools在我修改完文件后反應有點遲緩,經常要在修改過后等個幾秒鍾才開始自動編譯,暫時沒找到具體原因,有知道的小伙伴可以在評論區告訴我一下,如果你在設置完后也有這種情況,可以進行手動編譯,修改完內容后按
Ctrl+Shift+F9
編譯文件
說明
- 頁面熱部署
在application.properties文件中配置spring.thymeleaf.cache=false(頁面修改后會立即生效)
- 不會重新啟動的資源
/META-INF/maven, /META-INF/resources ,/resources ,/static ,/public 或者 /templates 不會觸發重新啟動, 但會觸發實時重新加載。
- 關閉devtools
在Application中的
SpringApplication.run()
方法之前添加System.setProperty("spring.devtools.restart.enabled", "false")