You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GraalVM生成可执行文件遇No awt in java.library.path错误

问题解决:GraalVM原生镜像AWT依赖缺失与PrintService查找失败

问题1:GraalVM构建原生镜像时抛出UnsatisfiedLinkError: No awt in java.library.path

背景

应用未使用Swing/JavaFX,但因依赖PrintLookupService间接用到sun.awt.AppContext,导致原生镜像构建后缺失AWT相关库。

解决方案

1. 手动补充AWT可达性元数据

在META-INF/native-image目录下创建reflect-config.json,添加sun.awt.AppContext的反射配置:

[
  {
    "name": "sun.awt.AppContext",
    "allDeclaredConstructors": true,
    "allPublicConstructors": true,
    "allDeclaredMethods": true,
    "allPublicMethods": true,
    "allDeclaredFields": true,
    "allPublicFields": true
  }
]

2. 修改native-image构建命令

添加-Djava.awt.headless=true(无需GUI,仅使用AWT上下文),命令如下:

native-image --no-fallback -H:ConfigurationFileDirectories=META-INF/native-image -Djava.awt.headless=true -jar "myapplication-1.0-SNAPSHOT-jar-with-dependencies.jar" "myapplication"

问题2:Liberica Native Image Kit构建后无法找到PrintService

解决方案

1. 重新运行Tracing Agent并触发打印服务逻辑

确保在运行应用时实际执行一次PrintServiceLookup的查找操作,让Tracing Agent完整捕获打印服务相关的依赖配置。重新执行agent命令:

java -agentlib:native-image-agent=config-output-dir=META-INF/native-image -Djava.awt.headless=true -jar "myapplication-1.0-SNAPSHOT-jar-with-dependencies.jar"

2. 手动补充打印服务相关配置

如果agent仍未捕获,在META-INF/native-image下添加以下配置:

  • reflect-config.json(追加内容):
[
  {
    "name": "javax.print.PrintServiceLookup",
    "allDeclaredMethods": true,
    "allPublicMethods": true
  },
  {
    "name": "sun.print.ServiceDialog",
    "allDeclaredConstructors": true,
    "allPublicConstructors": true
  },
  {
    "name": "javax.print.attribute.PrintRequestAttributeSet",
    "allDeclaredMethods": true,
    "allPublicMethods": true
  }
]
  • resource-config.json(创建或追加):
{
  "resources": [
    {"pattern": "\\Qjavax/print/printservice.properties\\E"}
  ]
}

3. 调整构建命令参数

添加打印服务相关系统属性,确保类加载正常:

native-image --no-fallback -H:ConfigurationFileDirectories=META-INF/native-image -Djava.awt.headless=true -Dsun.print.disableProxyClassLoader=false -jar "myapplication-1.0-SNAPSHOT-jar-with-dependencies.jar" "myapplication"

内容的提问来源于stack exchange,提问作者hoomb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 09:07:32