摘要:Spring项目又大又重,依赖多,编译启动慢,怎么提高研发效率呢?方法之一==热部署
==!
概念
Spring Boot DevTools
- 依赖名称: Spring Boot DevTools
- 功能描述: Provides fast application restarts, LiveReload, and configurations for enhanced development experience.
- 中文释义:提供快速应用程序重启、LiveReload 和配置,以增强开发体验。
要在 IntelliJ IDEA 中创建一个 Spring Boot 项目,并集成 Spring Boot DevTools
实现热部署,您可以按照以下步骤操作。Spring Boot DevTools
可以在开发时自动重新加载应用程序,从而提高开发效率。
1. 创建 Spring Boot 项目
打开 IntelliJ IDEA。
新建项目并添加添加
Spring Boot DevTools
依赖打开
pom.xml
文件。在
<dependencies>
部分,添加以下依赖:<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
或者,如果您使用的是 Gradle,请在
build.gradle
文件中添加:dependencies { developmentOnly 'org.springframework.boot:spring-boot-devtools' }
刷新 Maven/Gradle 项目以确保依赖下载并生效。
2. 配置 IntelliJ IDEA 支持热部署
启用自动编译:
- 打开
File
->Settings
->Build, Execution, Deployment
->Compiler
->Build project automatically
。 - 确保勾选
Build project automatically
。
- 打开
启用热部署:
- 在 Mac 上按下
Command + Shift + A
或者按两下shift键,windows上Ctrl + Shift + A
,弹窗出来来后,搜索Registry
关键词。
- 在 Mac 上按下
- 搜索并勾选启用
compiler.automake.allow.when.app.running
。
3. 编写简单的 Spring Boot 应用
创建一个简单的
Controller
类来测试热部署:package com.dependencies.springbootdevtools; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author zhizhou 2024/8/29 12:40 */ @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, I'm ok !"; } }
创建主类 SpringBootDevtoolsApplication:
package com.dependencies.springbootdevtools; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDevtoolsApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDevtoolsApplication.class, args); } }
4. 运行和测试热部署
- 运行SpringBootDevtoolsApplication入口类
- 在浏览器中访问
http://localhost:8080/hello
,您应该会看到 “Hello, I’m ok !”。 - 测试热部署:不需要停止运行的应用程序,直接在
HelloController
中修改返回的字符串为 “Hello, World!”。 - 保存文件,然后刷新浏览器,您应该会看到更新后的内容。
5. 总结
通过集成 Spring Boot DevTools
,我们可以在开发时自动重新加载应用程序,而无需手动重启。这样可以极大地提高开发效率,尤其是在需要频繁修改代码并查看效果时。