[spring-projects/spring-boot]Kotlin 的 JSR223 脚本引擎在被 fat jar 使用时不起作用

2024-05-09 250 views
3

现在我的项目使用 java 和 kotlin 以及 spring boot m6 和 kotlin 1.1.51。该项目有一个app.kts使用 kotlin 渲染模板的文件。然后我使用控制器调用渲染 kotlin 模板的操作。控制器用Java编写。

  • 我使用IDEA运行应用程序并调用控制器,它成功了。
  • 我使用maven将项目构建为exec jar,然后运行它并调用控制器,出现错误
    ERROR: Cannot load extensions/common.xml from /Users/kanner/workspace/project/dataman/nemo/nemo-svr/nemo-svr-kafka/target/nemo-svr-kafka-master-SNAPSHOT-exec.jar
    java.lang.Throwable
    at com.intellij.openapi.diagnostic.Logger.error(Logger.java:132)
    at com.intellij.ide.plugins.PluginManagerCore.registerExtensionPointAndExtensions(PluginManagerCore.java:1355)
    at com.intellij.core.CoreApplicationEnvironment.registerExtensionPointAndExtensions(CoreApplicationEnvironment.java:326)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment$Companion.registerApplicationExtensionPointsAndExtensionsFrom(KotlinCoreEnvironment.kt:498)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment$Companion.createApplicationEnvironment(KotlinCoreEnvironment.kt:457)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment$Companion.getOrCreateApplicationEnvironmentForProduction(KotlinCoreEnvironment.kt:427)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment$Companion.createForProduction(KotlinCoreEnvironment.kt:377)
    at org.jetbrains.kotlin.cli.jvm.repl.GenericReplChecker.<init>(GenericReplChecker.kt:63)
    at org.jetbrains.kotlin.cli.jvm.repl.GenericReplCompiler.<init>(GenericReplCompiler.kt:49)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine$replCompiler$2.invoke(KotlinJsr223JvmLocalScriptEngine.kt:47)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine$replCompiler$2.invoke(KotlinJsr223JvmLocalScriptEngine.kt:37)
    at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:130)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine.getReplCompiler(KotlinJsr223JvmLocalScriptEngine.kt)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine$localEvaluator$2.invoke(KotlinJsr223JvmLocalScriptEngine.kt:54)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine$localEvaluator$2.invoke(KotlinJsr223JvmLocalScriptEngine.kt:37)
    at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:130)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine.getLocalEvaluator(KotlinJsr223JvmLocalScriptEngine.kt)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine.getReplEvaluator(KotlinJsr223JvmLocalScriptEngine.kt:56)
    at org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine.createState(KotlinJsr223JvmLocalScriptEngine.kt:60)
    at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.createState$default(KotlinJsr223JvmScriptEngineBase.kt:46)
    at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.getCurrentState(KotlinJsr223JvmScriptEngineBase.kt:53)
    at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.nextCodeLine(KotlinJsr223JvmScriptEngineBase.kt:44)
    at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compile(KotlinJsr223JvmScriptEngineBase.kt:72)
    at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compile(KotlinJsr223JvmScriptEngineBase.kt:35)
    at com.dataman.nemo.core.script.ScriptEngineKt.render(ScriptEngine.kt:15)
    at com.dataman.nemo.core.service.template.KotlinEngineService.render(KotlinEngineService.java:23)
    at com.dataman.nemo.core.service.cloud.k8s.K8sService.createOrUpdateApp(K8sService.java:192)
    at com.dataman.nemo.core.service.cloud.k8s.K8sService.createApp(K8sService.java:67)
    at com.dataman.nemo.kafka.controller.KafkaController.createKafka(KafkaController.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.dataman.nemo.core.auth.token.JwtAuthenticationFilter.doFilter(JwtAuthenticationFilter.java:50)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:119)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterWithMetrics(WebMvcMetricsFilter.java:95)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:72)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.dataman.nemo.kafka.filter.TraceFilter.doFilter(TraceFilter.java:23)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

有什么解决办法吗?

回答

4

我之前没有见过有人在 Boot 应用程序中使用基于 Kotlin 的视图模板,所以我不确定解决方案是什么(如果有的话)。您能否提供一个重现问题的小样本以便我们进行调查?

/cc @sdeleuze

3

事实上,考虑到有多种方法可以实现这一目标,一个小样本确实会有所帮助,其中之一就是我在kotlin-script-templated上所做的(需要相当多的设置,所以我认为目前这是实验性的)。

6

如果您希望我们查看此问题,请提供所需的信息。如果在接下来的 7 天内未提供信息,此问题将被关闭。

9

感谢您提供样品。

问题的第一部分是,PluginManagerCore捆绑kotlin-compiler 假设它将被打包在可直接在文件系统上使用的 jar 中。从 Spring Boot fat jar 运行时情况并非如此(在禁用 war 解包的情况下在 Tomcat 中运行时也不会出现这种情况,因此这不是 Spring Boot 特有的问题)。 Spring Boot 包含一个逃生舱口来处理做出这种假设的库。您可以配置可执行 jar 启动器以从可执行存档中解压 jar,以便可以直接在文件系统上使用它。对于提供的示例,需要对 Boot 的 Maven 插件的配置进行此修改:

diff --git a/pom.xml b/pom.xml
index cfbe625..c898740 100644
--- a/pom.xml
+++ b/pom.xml
@@ -207,6 +207,12 @@
                 <configuration>
                     <classifier>exec</classifier>
                     <executable>true</executable>
+                    <requiresUnpack>
+                        <dependency>
+                            <groupId>org.jetbrains.kotlin</groupId>
+                            <artifactId>kotlin-compiler</artifactId>
+                        </dependency>
+                    </requiresUnpack>
                 </configuration>
                 <executions>
                     <execution>

@ckanner 你能打开一个问题来向 JetBrains 报告这部分问题吗?有问题的代码实际上是 IDEA 的一部分,但考虑到通过 Kotlin 使用时会出现问题,因此提出Kotlin 问题希望是一个合理的起点。

完成上述更改后,事情变得更进一步,但仍然失败:

 exception is javax.script.ScriptException: Error: error: unresolved reference: kanner
import com.kanner.sample.script.*
           ^
error: unresolved reference: user
username: ${user.username}
            ^
error: unresolved reference: user
age: ${user.age}
       ^
error: unresolved reference: user
address: ${user.address}
           ^
] with root cause

javax.script.ScriptException: Error: error: unresolved reference: kanner
import com.kanner.sample.script.*
           ^
error: unresolved reference: user
username: ${user.username}
            ^
error: unresolved reference: user
age: ${user.age}
       ^
error: unresolved reference: user
address: ${user.address}
           ^

    at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compile(KotlinJsr223JvmScriptEngineBase.kt:77) ~[kotlin-compiler-1.1.51.jar:1.1.51]
    at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compile(KotlinJsr223JvmScriptEngineBase.kt:35) ~[kotlin-compiler-1.1.51.jar:1.1.51]
    at com.kanner.sample.script.ScriptEngineKt.render(ScriptEngine.kt:13) ~[classes!/:master-SNAPSHOT]
    at com.kanner.sample.service.KotlinEngineService.render(KotlinEngineService.java:21) ~[classes!/:master-SNAPSHOT]
    at com.kanner.sample.controller.SampleController.getTemplateInfo(SampleController.java:31) ~[classes!/:master-SNAPSHOT]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) ~[spring-webmvc-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:119) ~[spring-boot-actuator-2.0.0.M6.jar!/:2.0.0.M6]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterWithMetrics(WebMvcMetricsFilter.java:95) ~[spring-boot-actuator-2.0.0.M6.jar!/:2.0.0.M6]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:72) ~[spring-boot-actuator-2.0.0.M6.jar!/:2.0.0.M6]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar!/:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar!/:8.5.23]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]

我的猜测是使用了错误的类加载器,但这只是目前的猜测。我会继续调查。

1

我对 ClassLoader 的预感似乎是正确的,尽管我缺乏 Kotlin 专业知识使得遵循代码比我想象的要困难一些。KotlinJsr223JvmScriptEngineBase.compile 打电话replCompiler.compile,这就是失败的原因。ReplCompiler 包含一些设置类路径的逻辑。我相信,这就是问题所在。

@ckanner 我建议针对问题的第二部分提出一个单独的 Kotlin 问题。请链接到您在此处打开的两个问题,以便我们可以跟踪它们并在需要时发表评论。

不幸的是,我认为我们在 Spring Boot 中无法做任何事情来解决这个问题,所以我现在将关闭这个问题。如果一个或其他 Kotlin 问题确定需要对 Boot 进行一些更改,那么我们可以重新打开它。

0

@wilkinsona 我无权向 JetBrains 报告该问题。

4

@ckanner AFAIK,只要您拥有 JetBrains 帐户,任何人都可以向 JetBrains 报告问题。您可以登录 YouTrack,并在必要时通过单击本页右上角的“登录...”创建一个新帐户。

5

kotlin-scripting-bug.zip

仅供参考,Kotlin 项目尚未从头开始优先考虑这个问题。提供的附件中提供了一个解决方案,该解决方案大部分可行,但有一个限制:(由于某种原因)kotlin 无法从项目自己的类中解析顶级函数。附加的代码还演示了我如何为了 DSL 的目的而解决这个问题。

解决方案的本质就在SpringBootSupport.kt里面

package com.example.demo.engine

import java.io.File
import java.io.FileInputStream
import java.nio.file.Files
import java.util.jar.JarInputStream
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContextOrStlib

val springBootFatJar: File? by lazy {
    Thread.currentThread().contextClassLoader.getResource("BOOT-INF/classes")?.path?.substringBefore("!/")?.substringAfter("file:").toFile()
}

val springBootClassPath: List<File> by lazy {
    if (springBootFatJar == null) {
        scriptCompilationClasspathFromContextOrStlib("kotlin-script-util.jar", wholeClasspath = true)
    } else {
        val unpackDir = Files.createTempDirectory("boot-").toFile().apply {
            Runtime.getRuntime().addShutdownHook(Thread {
                deleteRecursively()
            })
        }
        ArrayList<File>().apply {
            JarInputStream(FileInputStream(springBootFatJar)).use { jarInputStream ->
                add(File("$unpackDir/BOOT-INF/classes"))
                do {
                    val entry = jarInputStream.nextJarEntry
                    if (entry != null) {
                        try {
                            if (!entry.isDirectory) {
                                val file = File("$unpackDir/${entry.name}")
                                if (entry.name.startsWith("BOOT-INF/lib")) {
                                    add(file)
                                }
                                println("extracting $file")
                                Files.createDirectories(file.parentFile.toPath())
                                file.outputStream().use { outputStream ->
                                    jarInputStream.copyTo(outputStream)
                                    outputStream.flush()
                                }
                            }
                        } finally {
                            jarInputStream.closeEntry()
                        }
                    }
                } while (entry != null)
            }
        }
    }
}

private fun String?.toFile(): File? {
    return if (this == null) null else File(this)
}

然后可以springBootClassPath使用如下KotlinScriptEngineFactory所示:

package com.example.demo.engine

import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase
import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineFactoryBase
import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
import org.jetbrains.kotlin.script.jsr223.KotlinStandardJsr223ScriptTemplate
import javax.script.Bindings
import javax.script.ScriptContext
import javax.script.ScriptEngine
import javax.script.ScriptEngineFactory

/**
 * Configures a [ScriptEngineFactory] that produces a JSR-223 [ScriptEngine] that is configured with entries from the
 * Spring Boot fat jar.
 */
internal class KotlinScriptEngineFactory : KotlinJsr223JvmScriptEngineFactoryBase() {

    override fun getScriptEngine(): KotlinJsr223JvmScriptEngineBase {
        return KotlinScriptEngine(
            this,
            springBootClassPath,
            KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
            { ctx, types ->
                ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray())
            },
            arrayOf(Bindings::class)
        )
    }
}

最后,包含的脚本引擎是从源代码复制的,KotlinJsr223JvmLocalScriptEngine并进行了一些细微的调整:

package com.example.demo.engine

import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.common.repl.*
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots
import org.jetbrains.kotlin.cli.jvm.config.addJvmSdkRoots
import org.jetbrains.kotlin.cli.jvm.repl.GenericReplCompiler
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import java.net.URLClassLoader
import java.util.concurrent.locks.ReentrantReadWriteLock
import javax.script.ScriptContext
import javax.script.ScriptEngine
import javax.script.ScriptEngineFactory
import kotlin.reflect.KClass

/**
 * Creates a JSR-223 [ScriptEngine] that is configured with Spring Boot fat jar classpath information.
 *
 * Based on [org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine]
 *
 * @see [KotlinScriptEngineFactory]
 */
internal class KotlinScriptEngine(
    factory: ScriptEngineFactory,
    val templateClasspath: List<File>,
    templateClassName: String,
    val getScriptArgs: (ScriptContext, Array<out KClass<out Any>>?) -> ScriptArgsWithTypes?,
    val scriptArgsTypes: Array<out KClass<out Any>>?
) : KotlinJsr223JvmScriptEngineBase(factory), KotlinJsr223JvmInvocableScriptEngine {

    override val replCompiler: ReplCompiler by lazy {
        GenericReplCompiler(
            makeScriptDefinition(templateClassName),
            makeCompilerConfiguration(),
            PrintingMessageCollector(System.out, MessageRenderer.WITHOUT_PATHS, false))
    }

    private val localEvaluator by lazy { GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader, getScriptArgs(getContext(), scriptArgsTypes)) }

    override val replEvaluator: ReplFullEvaluator get() = localEvaluator

    override val state: IReplStageState<*> get() = getCurrentState(getContext())

    override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock)

    override fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? = getScriptArgs(context, scriptArgsTypes)

    private fun makeScriptDefinition(templateClassName: String): KotlinScriptDefinition {
        val cls = this.javaClass.classLoader.loadClass(templateClassName)
        return KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, emptyMap())
    }

    private fun makeCompilerConfiguration() = CompilerConfiguration().apply {
        val regex = Regex("""kotlin-compiler(-embeddable)?-(\d+\.)+jar""")
        addJvmSdkRoots(PathUtil.getJdkClassesRootsFromCurrentJre())
        addJvmClasspathRoots(templateClasspath)
        put(CommonConfigurationKeys.MODULE_NAME, "kotlin-script")
        put(CLIConfigurationKeys.INTELLIJ_PLUGIN_ROOT, templateClasspath.first { it.name.matches(regex) }.path)
        languageVersionSettings = LanguageVersionSettingsImpl(
            LanguageVersion.LATEST_STABLE,
            ApiVersion.LATEST_STABLE,
            mapOf(AnalysisFlags.skipMetadataVersionCheck to true)
        )
    }

    private val classloader = URLClassLoader(templateClasspath.map { it.toURI().toURL() }.toTypedArray(), this.javaClass.classLoader)
}
7

根据 Kotlin 票证上的评论,我的印象是 Kotlin 维护者认为此功能特定于 Spring Boot 的自定义打包,并且他们似乎认为该解决方案应该属于 Spring Boot 自己的 kotlin 支持范围。

2

不幸的是,他们并没有真正解释原因。 Spring Boot 的自定义类加载器是一个URLClassLoader.如果 Kotlin 确实使用该类加载器的 URL 来加载自己的类,那么只要它们不对指向文件系统上直接可用的 jar 的 URL 做出任何假设,它就应该可以工作。

我们的 jar 布局没有任何特定于 Spring Boot 的内容,这一点也毫无价值。例如,如果您将 Tomcat 配置为不解压已部署到其中的 war 文件,那么您最终会遇到类似的情况,类路径上的 URL 指向嵌套在app.war!/WEB-INF/lib.

6

我倾向于同意@wilkinsona,我添加了一条评论,向 Ilya Chernikov 询问更多详细信息。

3

@wilkinsona 我们可以重新讨论这个问题吗?经过更多调查,我发现问题是由于 Spring Boot Maven 插件未META-INF/<module-name>.kotlin-module正确重新打包文件造成的。该文件应该在 下重新打包BOOT-INF/classes/META-INF/<module-name>.kotlin-module*,否则包级函数将无法正确解析。

3

如果 Spring Boot Maven 插件能够

  1. 解压classes目录以及指定的jar包
  2. 像 gradle 插件一样接受 groupId 和 artifactId 的通配符模式
8
  1. 解压classes目录以及指定的jar包

我们有一个单独的问题正在跟踪:https://github.com/spring-projects/spring-boot/issues/6742。请随意发表评论,解释为什么您认为应该重新考虑关闭它。

  1. 像 gradle 插件一样接受 groupId 和 artifactId 的通配符模式

我不清楚你在这里具体指的是什么。请随意打开一个单独的问题,准确描述您希望看到的内容以及原因。

8

经过更多调查,我发现问题是由于 Spring Boot Maven 插件未META-INF/<module-name>.kotlin-module正确重新打包文件造成的。该文件应该在 下重新打包BOOT-INF/classes/META-INF/<module-name>.kotlin-module*,否则包级函数将无法正确解析。

感谢您追踪到这一点。我刚刚仔细检查过,我们使用 Gradle 解决了这个问题。我已经打开https://github.com/spring-projects/spring-boot/issues/15890来纠正 Maven 插件的行为。

6

正如Ilia 在 JetBrains bug tracker 上提到的,KT-27956将通过使用类加载器而不是类路径来进行脚本编译来解决这个问题,所以如果您关心的话,请为其投票。