在 Spring Boot 应用程序中使用 JavaCompiler API - 无法正确设置编译类路径

ron*_*nif 5 java-compiler-api spring-boot

我们有一个应用程序,它已从传统的 WAR Spring Web 应用程序迁移到我们希望成为现代 Spring Boot 可执行 Jar 的应用程序。

应用程序模块之一使用JavaCompilerAPI 生成 Java 代码并在运行时对其进行编译。
生成的代码需要驻留在 Web 应用程序类路径中的依赖项,因此我们大致有以下代码:

StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);

List<String> optionList = new ArrayList<String>();

    // set compiler's classpath to be same as the runtime's
    String classpathString = System.getProperty("java.class.path");
    optionList.addAll(Arrays.asList("-nowarn",
                                    "-classpath",
                                    classpathString,
                                    "-g",
                                    "-source",
                                    javaVersion,
                                    "-target",
                                    javaVersion));

    Collection classpathFiles = getClasspathJars(classpathString);
    addPreviousCompiledClassesToClasspathFiles(rootClassPath, classpathFiles);

    try {
        File file = new File(getTargetRoot(tempClassPath));
        file.mkdirs();
        standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Lists.newArrayList(file));
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles);

        // adding current dir to the source path, to find the compiled DV
        if (generateSeparateJarsForEachDecision.equals(NO_JAR)) {
            standardFileManager.setLocation(StandardLocation.SOURCE_PATH, Lists.newArrayList(file));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }


        List<CharSequenceJavaFileObject> compilationUnits = Lists
                .newArrayList(new CharSequenceJavaFileObject(   StringUtils.capitalize(filename),
                                                                toString(javaCode)));
        JavaCompiler.CompilationTask task = compiler
                .getTask(writer, standardFileManager, listener, optionList, null, compilationUnits);
        status = task.call();
Run Code Online (Sandbox Code Playgroud)

``

但是,这不适用于 Boot。类路径仅包含my-app.jar,并且我无法将任何嵌套的 jar 添加到-cp任务的 中 - 它不会添加那些嵌套的 jar。我还尝试手动将-cp它们添加到参数中,如下所示:{absolute-path}/my-app.jar!/BOOT-INF/lib/my-dep.jar {absolute-path}/my-app.jar!/BOOT-INF/lib/*.jar

这些都没有用。也考虑<requiresUnpack>过在构建时使用标记,但这似乎没有帮助,因为我无法获取扩展目录以将其添加到类路径中。

小智 0

面临类似的问题。

看起来像是 Spring Boot 的限制。

因此创建了一个嵌入 Jersey 和 Tomcat 的独立应用程序。

现在 jar 包含所有库并且能够将其设置为 Java 编译器的类路径