使用spring-boot-devtools热部署


IDEA新建一个Maven项目

pom.xml中加入spring-boot-devtools依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>

注意,还需要加入spring-boot-maven-plugin

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!--如果没有该配置,devtools不会起作用,即应用不会restart-->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

创建启动类和控制器类、页面

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("hello")
public class HelloController {

    @RequestMapping("index")
    public String index(Model model){

        model.addAttribute("who","spring boot");
        return "hello/index.html";
    }
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>spring boot demo</title>
</head>
<body>
    <p th:text="${who}"></p>
</body>
</html>

页面热部署需要在application.yml中配置

 
 
spring:
thymeleaf:
cache: false

代码修改后不能热部署

原因:

Spring Boot Devtools会监控类路径目录,如果类路径下的文件发生了变化(比如重新编译),则Spring Boot Devtools会重新加载和重启Spring Boot应用。

而在Intellij中,默认不会自动编译(auto build),并且默认不会更新正在运行的应用。

这就导致了在Intellj中修改代码后,Spring Boot应用不会重新加载新的类文件。

方法:

手动触发构建,修改代码后,选择 Build / Build project (Win/Linux: CTRL + F9, Mac: COMMAND + F9)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM