Files
blog-press/docs/Web-Backend/SpringBoot/SpringBoot3-GraalVM.md
2025-12-16 18:07:42 +08:00

77 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: SpringBoot3原生镜像
date: 2025-11-27
---
# 一、原生镜像
  传统 Java 应用基于 JVM 运行,需要加载完整的类库和 JVM 运行时环境,导致启动时间长、内存占用高。而**原生镜像技术通过提前编译AOT将 Java 应用直接编译为本地机器码,无需 JVM 即可运行**,具有以下核心优势:
1. 启动速度极快:毫秒级启动,相比传统 JVM 应用提升 10-100 倍、
2. 内存占用低:仅包含应用运行所需的最小资源集合
3. 部署体积小:通常为传统 JAR 包的 1/10 左右
4. 适合云原生场景:尤其适合 Kubernetes 等容器化环境
# 二、安装使用
## 2.1 基础软件
1. GraalVM类似于JAVA JDK下载[官网](https://www.graalvm.org/downloads/),下载完成后需要配置环境变量
2. native-image安装cmd运行gu install native-image
3. Visual Studio Community2022 选择使用C++的桌面开发
## 2.2 结合Springboot3 项目
1. IDEA创建Springboot3项目
2. Project Structure选择GraalVM JDK
3. 配置pom打包
```xml
<plugins>
<!-- 将项目打包成可执行的 JAR/WAR 文件 -->
<!-- repackage目标会替换 Maven 默认的打包行为 -->
<!-- 使 JAR/WAR 文件包含所有依赖项,成为一个独立运行的应用 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
<!-- 执行 AOT 编译 -->
<goal>process-aot</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- GraalVM Native Maven 插件 -->
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.10.2</version>
<configuration>
<buildArgs combine.children="append">
<!-- 支持 http 协议 -->
<buildArg>--enable-url-protocols=http</buildArg>
<!-- 用于解决数据库中文乱码问题 -->
<buildArg>-H:+AddAllCharsets</buildArg>
</buildArgs>
</configuration>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>compile-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
```
4. 选择Maven->Lifecycle->clean和package或者输入命令mvn -Pnative native:compile
5. 在target目录下可以看到生成的.exe文件打开运行即可。
## 三、注意事项
&emsp;&emsp;实际体验下来发现主要存在以下几个问题
1. 编译打包的速度非常慢
2. 目前有些第三方库并不支持Mybatis已支持Mybatis Plus暂不支持
# 四、参考资料
1. [使用 Spring Boot 和 GraalVM 构建原生镜像](https://springdoc.cn/spring-native-intro/)
2. [GraalVM 原生镜像支持](https://docs.springframework.org.cn/spring-boot/reference/native-image/introducing-graalvm-native-images.html)