使用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