IntelliJ IDEA 2023.3 中配置 Spring Boot 项目的热加载

打印 上一主题 下一主题

主题 1022|帖子 1022|积分 3066

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
IntelliJ IDEA 2023.3 中配置 Spring Boot 项目的热加载
在 IntelliJ IDEA 2023.3 中配置 Spring Boot 项目的热加载,可以让你在不重启应用的情况下看到代码修改的效果。以下是详细的配置步骤:

  • 添加 spring-boot-devtools 依赖
  1. 在 pom.xml 文件中添加 spring-boot-devtools 依赖:
  2. xml
  3. 复制
  4. <dependency>
  5.     <groupId>org.springframework.boot</groupId>
  6.     <artifactId>spring-boot-devtools</artifactId>
  7.     <optional>true</optional>
  8. </dependency>
复制代码

  • 配置 application.yml 或 application.properties
  1. 在 application.yml 或 application.properties 文件中配置热加载:
  2. application.yml:
  3. yaml
  4. 复制
  5. spring:
  6.   devtools:
  7.     restart:
  8.       enabled: true  # 设置开启热部署
  9.       additional-paths: src/main/java  # 重启目录
  10.       exclude: static/**,public/**  # 排除文件(不重启项目)
  11.   freemarker:
  12.     cache: false  # 页面不加载缓存,修改即时生效
  13. application.properties:
  14. properties
  15. 复制
  16. spring.devtools.restart.enabled=true
  17. spring.devtools.restart.additional-paths=src/main/java
  18. spring.devtools.restart.exclude=static/**,public/**
  19. spring.freemarker.cache=false
复制代码

  • 配置 IntelliJ IDEA
  1. 开启自动编译项目功能:
  2. 打开 IntelliJ IDEA,进入 File -> Settings(Windows)或 IntelliJ IDEA -> Preferences(macOS)。
  3. 在设置窗口中,选择 Build, Execution, Deployment -> Compiler。
  4. 勾选 Build project automatically。
  5. 配置 Advanced Settings:
  6. 在设置窗口中,选择 Advanced Settings。
  7. 勾选 Allow auto-make to start even if developed application is currently running。
复制代码

  • 配置 IDEA 启动设置
  1. 修改 IDEA 启动设置:
  2. 打开 Run -> Edit Configurations。
  3. 选择你的 Spring Boot 应用配置。
  4. 在 Server 标签下,设置 On frame deactivation 为 Update classes and resources。
复制代码

  • 测试热加载
  1. 创建一个简单的 Controller:
  2. java
  3. 复制
  4. package com.example.demo.controller;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. public class HelloController {
  9.     @GetMapping("/hello")
  10.     public String hello() {
  11.         return "Hello, World!";
  12.     }
  13. }
复制代码
启动项目:
使用 Run 或 Debug 方式启动项目。
访问 http://localhost:8080/hello,看到返回 Hello, World!。
修改 Controller:
修改 HelloController 中的返回值为 Hello, Spring Boot!,生存文件。
切换到欣赏器,刷新页面,看到返回 Hello, Spring Boot!,说明热加载生效。
注意事项
热加载的限制:
热加载仅支持方法块内代码修改,只有在 debug 模式下才生效,并且是在 IDEA 失去焦点时才会触发热加载。
修改方法署名、参数、增加或淘汰类的成员、修改配置文件等操纵不支持热加载。
IDEA 自动生存:
IDEA 会自动生存文件,但有时大概必要手动生存(Ctrl + S)或使用 Ctrl + F9 重新编译修改的类。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

知者何南

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表