简体   繁体   English

JavaCompiler在直接运行main方法时有效,但在运行spring-boot:run时无效

[英]JavaCompiler works when running the main method directly but not when running spring-boot:run

I have a very simple spring-boot project, which is used to compile a .java file programmatically to a .class file. 我有一个非常简单的spring-boot项目,该项目用于以编程方式将.java文件编译为.class文件。 What's mysterious is that, it worked when running the main method in the Applicaiton class, but failed when running spring-boot:run . 神秘的是,它在运行Applicaiton类中的main方法时有效,但在运行spring-boot:run时失败。

First I will illustrate what I have in this project: 首先,我将说明我在这个项目中拥有的东西:

Compiler.java : used to compile .java files to .class files Compiler.java :用于将.java文件编译为.class文件

package com.example.demo;

import java.io.File;
import java.io.IOException;
import javax.tools.*;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;

public class Compiler {
    public static void compileTestClass() throws IOException {
        Compiler.compile("com.example.TestClass", "package com.example;\n" +
                "\n" +
                "import com.google.common.collect.ImmutableMap;\n" +
                "\n" +
                "public class TestClass {\n" +
                "}\n", new File("/tmp"));
    }
    public static void compile(String className, String javaSource, File outputDir) throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        outputDir.mkdirs();
        Iterable<String> options = Arrays.asList("-classpath", System.getProperty("user.home") + "/.m2/repository/com/google/guava/guava/19.0/guava-19.0.jar");
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(outputDir));

        JavaSourceFromString javaSourceFromString = new JavaSourceFromString(className, javaSource);
        Iterable<? extends JavaFileObject> compilationUnits = Collections.singletonList(javaSourceFromString);
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
        boolean success = task.call();
        if (!success) {
            throw new RuntimeException("Compilation failed.");
        }
    }
}

/**
 * A file object used to represent source coming from a string.
 */
class JavaSourceFromString extends SimpleJavaFileObject {
    /**
     * The source code of this "file".
     */
    final String code;

    /**
     * Constructs a new JavaSourceFromString.
     *
     * @param name the name of the compilation unit represented by this file object
     * @param code the source code for the compilation unit represented by this file object
     */
    JavaSourceFromString(String name, String code) {
        super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),
                Kind.SOURCE);
        this.code = code;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
        return code;
    }
}

MainController.java MainController.java

package com.example.demo;

import com.google.common.collect.ImmutableMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@RestController
public class MainController {
    @GetMapping("/compilerTest")
    public Map<String, Object> compilerTest() throws IOException {
        Compiler.compileTestClass();
        return ImmutableMap.of("success", true);
    }
}

I also have a file called DemoApplicaiton.java , which is shipped with SpringBoot Generator 我还有一个名为DemoApplicaiton.java的文件,该文件随SpringBoot Generator一起提供。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

I also added com.google.guava-guava-19.0 to pom.xml because the file to be compiled programmatically needed it. 我还将com.google.guava-guava-19.0添加到pom.xml因为要以编程方式编译的文件需要它。

As we all know, there are two ways to start a spring-boot project: 众所周知,有两种方法可以启动spring-boot项目:

  1. Run the main method in DemoApplication.java 运行DemoApplication.java中的main方法
  2. Run mvn spring-boot:run 运行mvn spring-boot:run

I tried the first method, and try accessing the url localhost:8080/compilerTest after it started, it worked. 我尝试了第一种方法,并在启动后尝试访问url localhost:8080/compilerTest I got a {success: true} . 我得到了{success: true}

Then I tried the second method, and try accessing the same url localhost:8080/compilerTest after it started, I failed this time, I got an error: 然后,我尝试了第二种方法,并尝试在启动后访问相同的URL localhost:8080/compilerTest ,这次失败,出现错误:

/com/example/TestClass.java:3: error: package com.google.common.collect does not exist
import com.google.common.collect.ImmutableMap;
                                ^
1 error
2018-10-02 11:45:06.002 ERROR 43525 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: Compilation failed.] with root cause

java.lang.RuntimeException: Compilation failed.
    at com.example.demo.Compiler.compile(Compiler.java:32) ~[classes/:na]
    at com.example.demo.Compiler.compileTestClass(Compiler.java:12) ~[classes/:na]
    at com.example.demo.MainController.compilerTest(MainController.java:14) ~[classes/:na]
    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.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
    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.34.jar:8.5.34]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]

Why? 为什么? Is there any way to to make it work using spring-boot:run ? 有什么办法可以使它使用spring-boot:run吗?

I don't exactly why, but I found a solution to this problem. 我不完全是为什么,但是我找到了解决这个问题的方法。

In Compiler.java , replace this line: Compiler.java ,替换以下行:

Iterable<String> options = Arrays.asList("-classpath", System.getProperty("user.home") + "/.m2/repository/com/google/guava/guava/19.0/guava-19.0.jar");

with the following one: 与以下之一:

fileManager.setLocation(StandardLocation.CLASS_PATH, System.getProperty("user.home") + "/.m2/repository/com/google/guava/guava/19.0/guava-19.0.jar");

If you want to add multiple class paths, just use a List: 如果要添加多个类路径,请使用列表:

fileManager.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(new File("/tmp/jar1.jar"), new File("/tmp/jar2.jar")));

I guess the rule is, if you use fileManager.setLocation , the -classpath in options will not work in some cases somehow, I'm not sure why. 我猜规则是,如果使用fileManager.setLocationoptions-classpath在某些情况下将无法正常工作,我不确定为什么。

Here is the complete working source code of Compiler.java , for future reference. 这是Compiler.java的完整工作源代码,以供将来参考。

package com.example.demo;

import java.io.File;
import java.io.IOException;
import javax.tools.*;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;

public class Compiler {
    public static void compileTestClass() throws IOException {
        Compiler.compile("com.example.TestClass", "package com.example;\n" +
                "\n" +
                "import com.google.common.collect.ImmutableMap;\n" +
                "\n" +
                "public class TestClass {\n" +
                "}\n", new File("/tmp"));
    }
    public static void compile(String className, String javaSource, File outputDir) throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        outputDir.mkdirs();
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(outputDir));
        fileManager.setLocation(StandardLocation.CLASS_PATH, System.getProperty("user.home") + "/.m2/repository/com/google/guava/guava/19.0/guava-19.0.jar");

        JavaSourceFromString javaSourceFromString = new JavaSourceFromString(className, javaSource);
        Iterable<? extends JavaFileObject> compilationUnits = Collections.singletonList(javaSourceFromString);
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
        boolean success = task.call();
        if (!success) {
            throw new RuntimeException("Compilation failed.");
        }
    }
}

/**
 * A file object used to represent source coming from a string.
 */
class JavaSourceFromString extends SimpleJavaFileObject {
    /**
     * The source code of this "file".
     */
    final String code;

    /**
     * Constructs a new JavaSourceFromString.
     *
     * @param name the name of the compilation unit represented by this file object
     * @param code the source code for the compilation unit represented by this file object
     */
    JavaSourceFromString(String name, String code) {
        super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),
                Kind.SOURCE);
        this.code = code;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
        return code;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 jar 文件运行时出现 Whitelabel 错误,但使用 war 文件以及使用命令 mvn spring-boot:run 运行时工作正常 - Whitelabel error when running with jar file, but works fine with war file and when run with command mvn spring-boot:run 循环依赖只在运行 java -jar 时,而不是 spring-boot:run - Cyclic dependency only when running java -jar, not with spring-boot:run 运行 Jar 时强制启用 spring-boot DevTools - Force enable spring-boot DevTools when running Jar Spring-Boot 运行时。项目的 JAR 无法初始化 JPA - Spring-Boot When running .JAR of project it fails to initialize JPA JavaCompiler API - 在tomcat中运行时编译速度慢 - JavaCompiler API - slow compilation when running in tomcat 运行spring boot jar时找不到或加载主类 - Could not find or load main class, when running spring boot jar No main manifest error when running spring 启动微服务 docker image - No main manifest error when running spring boot microservice docker image 运行spring boot应用程序时找不到或加载主类 - Could not find or load main class, when running spring boot Application Spring-Boot:运行Spring Boot的Restful程序失败 - Spring-Boot: Failure on running of a spring-boot restful program 当我运行我的测试用例时,我的 spring-boot 的主要方法被唤起并且我的 mockito 方法不起作用。 如何解决这个问题? - When I run my test case, my main method of spring-boot gets evoked and my mockito method doesn't work. How to solve this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM