编译并执行一个java文件,该文件具有基于spring-boot的应用程序jar文件的导入语句

问题描述 投票:0回答:1

下面是我们想要通过基于 spring-boot 的应用程序在运行时编译和执行的代码。下面的代码将由我们的系统管理员通过我们的 UI 提供,该代码将以字符串格式传递到我们的后端应用程序。现在作为 spring-boot 应用程序运行的后端必须编译并执行它。

鉴于此动态代码将包含来自 2 个 jar 文件的导入语句: 1> 一个外部 jar,仅包含数据模型,不包含逻辑。 2> 当前的 spring-boot 应用程序本身,它在类中定义了一些逻辑。

此动态代码的目标是利用数据模型类并调用 spring-boot 应用程序中可用的公共方法,从我们想要编译/执行动态代码的地方。

package ai.myapps.service.triggers;

import ai.myapps.config.WebClientConfig;
import ai.myapps.service.DynamicCode;
import ai.myapps.dao.transaction.Student;
import ai.myapps.dao.transaction.Employee;
import org.springframework.http.MediaType;
import java.util.List;

public class MyDynamicCode extends WebInterface implements DynamicCode {
public <T> T execute(List<T> args) {
    Student student= (Student) args.get(0);
    Employee employee= new Employee();
    employee.setId(student.getId());
    employee.setName(student.getName());
    employee.setContractStartDate(student.getLastWorkingDate());
    return (T) employee;
}

}

假设上面的代码是字符串格式,我们从rest控制器触发以下方法来编译并执行该代码:

private Class<?> compileJavaCode(String javaCode) throws Exception {
    SimpleCompiler compiler = new SimpleCompiler();
    compiler.setParentClassLoader(getClass().getClassLoader()); // Set the parent class loader

    ByteArrayOutputStream errStream = new ByteArrayOutputStream();
    compiler.setCompileErrorHandler(new ErrorHandler() {
        @Override
        public void handleError(String message, Location location) {
            // Handle compilation error
           log.error("Compilation error: " + message+"  "+ location.getLineNumber());
            // You can also write the error to the error stream
            try {
                errStream.write(("Compilation error: " + message + "\n").getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    });

    compiler.cook(javaCode);
}

问题是,在编译期间,动态代码没有被编译,因为编译器没有识别当前应用程序(spring-boot)或数据模型 jar 的路径,失败并出现错误

MyDynamicCode.java:1: error: package  ai.myapps.config does not exist
。鉴于 data-model.jar 也作为库打包在 spring-boot 应用程序中。

    ai.myapps.dao       -- this package is in data-model.jar
     ai.myapps.service   -- is with in the current application
    ai.myapps.config    -- is with in the current application`

屏幕截图显示了我的 spring-boot 应用程序的展开视图

屏幕截图显示了我的 spring-boot 应用程序的展开视图,以帮助理解包结构。

请让我知道我在这里缺少什么。

java spring-boot runtime
1个回答
0
投票

您是否尝试正确加载类路径

© www.soinside.com 2019 - 2024. All rights reserved.