使用spring-pug4j的GraalJsExpressionHandler时遇ClassNotFoundException求助
问题场景
我是spring-pug4j的新手,按照官方文档配置了如下PugConfig类:
package com.xxxx.xxx.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import de.neuland.pug4j.PugConfiguration; import de.neuland.pug4j.spring.template.SpringTemplateLoader; import de.neuland.pug4j.spring.view.PugViewResolver; @Configuration public class PugConfig { @Bean public SpringTemplateLoader templateLoader() { SpringTemplateLoader templateLoader = new SpringTemplateLoader(); templateLoader.setTemplateLoaderPath("classpath:/templates"); templateLoader.setEncoding("UTF-8"); templateLoader.setSuffix(".pug"); return templateLoader; } @Bean public PugConfiguration pugConfiguration() { PugConfiguration configuration = new PugConfiguration(); configuration.setCaching(false); configuration.setTemplateLoader(templateLoader()); configuration.setExpressionHandler(new GraalJsExpressionHandler()); return configuration; } @Bean public ViewResolver viewResolver() { PugViewResolver viewResolver = new PugViewResolver(); viewResolver.setConfiguration(pugConfiguration()); return viewResolver; } }
项目依赖配置:
<dependency> <groupId>de.neuland-bfi</groupId> <artifactId>spring-pug4j</artifactId> <version>3.2.0</version> </dependency>
编译时抛出核心异常:
... Caused by: java.lang.ClassNotFoundException: jdk.vm.ci.services.Services ...
注释掉configuration.setExpressionHandler(new GraalJsExpressionHandler())后程序可正常运行。
问题原因
GraalJsExpressionHandler是基于GraalVM实现的表达式处理器,它依赖GraalVM专属的jdk.vm.ci.services.Services类,而标准OpenJDK/Oracle JDK默认不包含此类。当前项目使用的是标准JDK而非GraalVM,因此运行时无法找到该类,触发ClassNotFoundException。
另外,spring-pug4j的基础依赖包中并未包含GraalJS相关组件,即便要使用GraalJS表达式处理器,也需要手动引入对应依赖。
解决方案
方案1:使用默认表达式处理器(无需额外配置)
如果没有必须使用GraalJS的业务需求,直接移除configuration.setExpressionHandler(new GraalJsExpressionHandler())代码即可。spring-pug4j会自动使用默认的JexlExpressionHandler,该处理器仅依赖标准JDK,无需额外环境或依赖支持。
方案2:配置GraalVM环境并引入对应依赖(需GraalJS支持时)
切换至GraalVM运行环境:
下载并安装GraalVM,将系统的JAVA_HOME环境变量指向GraalVM的安装目录,确保项目构建和运行时使用GraalVM作为JDK。添加GraalJS依赖:
在pom.xml中加入GraalJS相关依赖包,注意版本需与你的GraalVM版本保持一致:<dependency> <groupId>org.graalvm.js</groupId> <artifactId>js</artifactId> <version>21.3.0</version> <!-- 版本需匹配你的GraalVM版本 --> </dependency> <dependency> <groupId>org.graalvm.js</groupId> <artifactId>js-scriptengine</artifactId> <version>21.3.0</version> </dependency>
内容的提问来源于stack exchange,提问作者Francisco M

