springboot自动编译和热部署设置

一.热部署的目的

IDEA 编写传统 web 应用使用外置的 Tomcat 时,前端代码修改后是可以自动编译,页面刷新就能看到效果的。而现在开发 SpringBoot 项目时,因为它使用的是内置的 Tomcat ,所以即使是在 html 页面上修改内容,它也必须重新启动之后才能看到效果,这样开发上很不方便。本文将解决这个问题。

使用热部署前提是idea要开启自动编译功能, eclipse默认开启自动编译

开启热部署步骤:

1. idea开启自动编译功能
2. 引入devtools依赖并生效
3. 项目配置

二.idea开启自动编译

2.1设置自动编译

File-Settings-Compiler-Build Project automatically(勾选)
在这里插入图片描述
2.2 注册自动编译

Ctrl+Shift+Alt+/ 选择Registry

找到选项Compiler autoMake allow when app running打勾,然后close
在这里插入图片描述
在这里插入图片描述

三. 引入devtools

3.1在pom文件中,引入如下依赖:

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <!--optional=true,依赖不会传递,该项目依赖devtools;之后
         依赖boot项目的项目如果想要使用devtools,需要重新引入-->
      <optional>true</optional>
</dependency>

3.2在pom文件中,引入插件中配置按如下配置:让devtools生效

	<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!--fork :  必须配置,否则热部署不会生效,应用不会重置 -->
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

补充:可以在配置文件中进行详细设置

#关闭缓存,即时刷新
#spring.freemaker.cashe=false
spring.thymeleaf.cache=true

#热部署生效
spring.devtools.restart.enable=true
#设置重启的目录,添加那个目录的文件需要restart
spring.devtools.restart.additional-paths=src/main/java
#为mybatis设置,生产环境可删除
#restart.include.mapper=/mapper-[\\w-\\.]+jar
#restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar
#排除那个目录的文件不需要restart
#spring.devtools.restart.exclude=static/**,public/**
#classpath目录下的WEB-INF文件夹内容修改不重启
#spring.devtools.restart.exclude=WEB-INF/**

四.项目设置启动加载方式

菜单栏选择 Run->Edit Configurations…

找到spring boot下的 On ‘Update’ action 和 On frame deactivation ,选择 Update classes and resources
在这里插入图片描述

最后测试热部署,随便修改一个类中的代码,查看idea最下方的提示条,出现 build 后 紧接着 出现 parsing java… 表示正在重新编译,等待项目自动重新启动后就可以看见修改的类生效了

在这里插入图片描述
参考文章