- 安装与操作系统相匹配的graal-vm(建议最新版本),并将graal-vm设为系统默认java运行环境。
- 创建一个spring-boot3项目,项目sdk版本设为graal-vm,只引入web包,
pom.xml如下(尤其需要追加maven的graalvm编译插件,可以从spring-boot-starter-parent项目的pom拷贝):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-boot-three</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-three</name>
<description>spring-boot-three</description>
<properties>
<java.version>19</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 编写一个简单的测试接口,返回当前运行时属性:
package com.example.springbootthree;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Properties;
@SpringBootApplication
public class SpringBootThreeApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootThreeApplication.class, args);
}
}
@RestController
@RequestMapping("/test")
class Test {
@GetMapping("/go")
public Properties go() {
return System.getProperties();
}
}
- 先以源码方式运行,确保没问题
- 找到idea的maven插件,点击命令:Plugins -> native -> native:compile-no-fork,若报gu插件相关的错,直接在项目目录下执行:
mvn -e -Pnative native:compile
命令。
AOT编译时间较长,大概一分半钟(新短板),成功之后会在target目录多生成一个,系统原生的可执行程序spring-boot-three,比传统jar包大不少。
执行:./target/spring-boot-three,可以看到启动耗时在几十毫秒,源码启动则在几百毫秒。 - 在浏览器请求原测试接口:localhost:8080/test/go,同样会返回RunTime信息,但与源码方式返回的信息有所不同。