項目中引用了SpringBoot Developer tools,修改類后會自動重啟。
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency>
</dependencies>
springboot developer tools的作用
用于提升開發體驗,比如修改類文件自動重啟、修改靜態文件熱加載、提供屬性默認值、遠程debug等。打包時,默認并不會將devleloper tools打入,除非禁用excludeDevtools
。
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludeDevtools>false</excludeDevtools></configuration></plugin></plugins>
</build>
自動重啟的原理
只要ClassPath有文件發生變化就會自動重啟,自動重啟的原理是,有一個BaseClassLoader加載library中的類,有一個RestartClassLoader加載開發的類,開發的類變更了,則創建新的RestartClassLoader加載開發類,丟棄老的RestartClassLoader;有時,修改了注釋、加個空行、都自動重啟,這是不合時宜的,而且使用intellij idea本身就會熱加載,不需要重啟(熱加載和重啟是不同的),禁用SpringBoot Developer tools的自動重啟功能,有兩個辦法
-
在application.yml或application.properties中配置
spring.devtools.restart.enabled
為false,這種RestartClassLoader仍然加載類,但不再監控類變化。 -
在調用
SpringApplication.run
之前,配置System property完全禁用,這種就不會創建RestartClassLoaderpublic static void main(String[] args) {System.setProperty("spring.devtools.restart.enabled", "false");SpringApplication.run(MyApp.class, args); }
順便提一句,SpringBoot Developer tools還提供了默認的屬性值,比如 template engines (FreeMarker、Thymeleaf、Mustache)默認會緩存編譯文件以提高效率,但在開發階段這是不合時宜的,所以SpringBoot Developer tools提供的spring.thymeleaf.cache
是false,完整的屬性默認值可參考DevToolsPropertyDefaultsPostProcessor.