java 项目部署不加载jar包_web项目部署后动态编译无法找到依赖的jar包

在Java项目部署后遇到动态编译问题,服务器上编译失败,原因是无法找到依赖的jar包。通过使用Apache Commons IO和Java Compiler API,动态构建类并指定-classpath选项来解决此问题。关键在于手动组装类路径,确保包含所有依赖的jar包路径。
摘要由CSDN通过智能技术生成

很纳闷的一个问题,通过配置文件生成的java源码在本地动态编译没有问题,但是部署服务器后编译不通过,找不到依赖的jar包。

通过网上查资料,找到一个兄弟提供的方法,问题解决了;下面贴出代码以供参考:

package com.songxingzhu.utils.compile;

import org.apache.commons.io.FileUtils;

import com.songxingzhu.utils.context.AppContext;

import javax.tools.JavaCompiler;

import javax.tools.JavaFileManager;

import javax.tools.JavaFileObject;

import javax.tools.ToolProvider;

import java.io.File;

import java.io.IOException;

import java.net.URL;

import java.net.URLClassLoader;

import java.util.ArrayList;

import java.util.List;

public class ClassBuilder {

public static Class> buildClass(String fullClassName, String codeFilePath) throws IOException, ClassNotFoundException {

return buildClass(fullClassName, codeFilePath, "UTF-8", AppContext.baseDirectory());

}

public static Class> buildClass(String fullClassName, String codeFilePath, String charsetName, String buildOutput) throws IOException, ClassNotFoundException {

try {

String code = FileUtils.readFileToString(FileUtils.getFile(codeFilePath), charsetName);

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

JavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

List files = new ArrayList<>();

files.add(new JavaSourceFromCodeString(fullClassName, code));

List options = new ArrayList<>();

options.add("-classpath");

StringBuilder sb = new StringBuilder();

URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();

for (URL url : urlClassLoader.getURLs()) {

sb.append(url.getFile()).append(File.pathSeparator);

}

options.add(sb.toString());

options.add("-d");

options.add(buildOutput);

// execute the compiler

boolean isok = compiler.getTask(null, fileManager, null, options, null, files).call();

if (isok) {

File root = new File(buildOutput);

if (!root.exists()) root.mkdirs();

URL[] urls = new URL[]{root.toURI().toURL()};

ClassLoader classLoader = ClassBuilder.class.getClassLoader();

Class> clazz = Class.forName(fullClassName, true, classLoader);

return clazz;

}

return null;

} catch (Exception ex) {

throw ex;

}

}

}

个人理解:部署后不像eclipse编译有.classpath指向依赖的所有的jar,需要自己组装类似classpath,指定jar包路劲。重点是设置option,不懂option的可以通过cmd命令查看javac的参数介绍。

其中,option.add("-classpath");就是类似直接运行javac -classpath 类文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值