天天看点

Spring-Boot-Devtools使用

一、简介

开发热部署,更新文件后,不需要重启即可见到效果。

二、使用

说明:此处开发工具为idea,springboot版本为2.2.2.RELEASE。搭建一个简单的web项目进行测试。

package com.tab343.devtools.devtools.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

import java.util.Map;

//Controller示例代码,我们通过更改v2为v3,然后刷新页面测试效果

@Controller

public class MyController {

    @GetMapping("/hello")

    @ResponseBody

    public Map<String,String> hello(){

        return new HashMap<String, String>(){{

            put("k1","v1");

            put("k2","v2");

        }};

    }

}

1.添加依赖

Maven

<dependencies>

   <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-devtools</artifactId>

          <!--可选的,设置为true,打包时不会进入项目-->

          <optional>true</optional>

   </dependency>

</dependencies>

Gradle

dependencies {

         compile("org.springframework.boot:spring-boot-devtools")

2.配置开发工具

参考:

SpringBoot2.X (十二):使用 devtools 热部署

(1)File ——> Settings ——> Complier ——> 选中 Build project automatically

Spring-Boot-Devtools使用

(2)Shift+ALT+Ctrl+/ ---->选择 Registry---->勾选 "complier.automake.allow.when.app.running"

Spring-Boot-Devtools使用

3.效果

Spring-Boot-Devtools使用

修改MyController中map的v2为v3,保存后刷新页面。结果为{"k1":"v1","k2":"v3"}

可能马上刷新页面值还是未改变,因为类加载器还未重新加载MyController,所以内存中还是v2。这里此插件的工作机制有关,说明见如下引用。使用ctrl+f9(Build->Build Project)重新编译项目后,再次刷新,即可看到效果。

默认情况下,当devtools检测到classpath下有文件内容变更时,它会对当前Spring Boot应用进行重新启动。但它的重新启动并不是完整的重启整个应用。它的应用的重启是基于两个不同的ClassLoader进行的,根ClassLoader将负责加载第三方jar包中的内容,而当前应用中的Class、配置文件等资源则使用一个可重新加载的ClassLoader进行加载,叫RestartClassLoader。

springboot官网说明-20.2 Automatic Restart

Triggering a restart

As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath. The way in which you cause the classpath to be updated depends on the IDE that you are using. In Eclipse, saving a modified file causes the classpath to be updated and triggers a restart. In IntelliJ IDEA, building the project (Build -> Build Project) has the same effect.

4.一些配置

application.properties配置 说明
spring.devtools.restart.enabled=true

是否开启插件功能。

当值为false时,idea在debug模式下,ctrl+f9重新编译还是会热部署

spring.devtools.restart.log-condition-evaluation-delta=true 更改文件后控制台是否显示更改日志
spring.devtools.restart.exclude=static/**,public/**

不需要热加载的文件

idea在debug模式下重新编译还是会热部署

继续阅读