Spring Boot在IDEA中使用devtools热部署配置不生效的解决办法
背景介绍
spring-boot-devtools是一个为开发者服务的模块,最重要的功能是自动实现把更新的应用代码更改到最新的APP上。其工作原理是在发现代码有更改之后,自动重新启用应用。更新层次的原理是使用了两个ClassLoader,一个ClassLoaderr加载那些不会改变的类,另一个ClassLoader加载会更改的类,成为RestartClassLoader。
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.xzpang.devtooltest</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Devtools</name>
<description>Devtool test project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<!-- optional=true,依赖不会往下传递,如果有项目依赖本项目,并且想要使用devtools,需要重新引入 -->
<optional>true</optional>
<scope>true</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 如果没有该项配置,devtools不会起作用,即应用不会restart -->
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
问题
如果是Eclipse,配置到这里,只要重启服务,热部署就会生效了。但是IDEA的话,热部署还不会生效,因为devTools只会在类路径上的文件发生更改时才会自动重启,而IDEA默认不会自动编译。
解决办法
- 设置application.properties
##############################################################################
### 热部署配置
##############################################################################
spring.devtools.restart.enabled=true
- 开启自动编译
- Ctrl+Alt+S打开配置
- 设置自动编译
- Ctrl+Shift+Alt+? 选择Registry
- 勾选 compiler.automake.allow.when.app.running