nnnnyyyy 2022-03-17 15:43 采纳率: 0%
浏览 36

使用Spring Boot动态调用外部Jar包,抛java.lang.ClassNotFoundException?

问题发生背景

一、用Idea创建一个Maven工程,编译一个Jar包:atiot-driver-collection(称之为子Jar包);子Jar包里面有一个类DriverService,类里面有一个方法getDriveConfig(),它返加了一个字符串。功能相对简单。

二、用Idea创建了另一个Maven工程(称之为父工程),想在这个父工程中通过Java反射机制,动态加载atiot-driver-collection.jar包,执行DriverService类的getDriveConfig()方法。
执行抛错,java.lang.ClassNotFoundException: com.antai.iot.collection.service.DriverService

问题相关代码

1.1、子工程代码

package com.antai.collection.service;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * //查询日志
 * //查询配置
 * //发送心跳包
 */
public class DriverService {

    //日志
    Logger logger = LogManager.getLogger("DriverLogger");

    /**
     * 查询配置
     *
     * @return
     */
    public String getDriveConfig() {

        String configFile = "DriveConfig";

        return configFile;
    }

    /**
     * 获取日志
     *
     * @return
     */
    public String getLog() {

        String logPath = System.getProperty("user.dir") + "\\src\\main\\resources\\";

        return logPath;
    }

    /**
     * 发送心跳包
     */
    public String sendHeartBeaten() {

        return "Hello,I`m a  Heart Beaten";
    }
}

1.2、子工程POM

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.antai</groupId>
  <artifactId>atiot-driver-collection</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>atiot-driver-collection</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!--日志-->
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.17.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.17.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</artifactId>
      <version>2.6.4</version>
    </dependency>

  </dependencies>

  <build>
    <!-- 指定打包文件名 -->
    <finalName>atiot-driver-collection</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>2.2.6.RELEASE</version>
        <configuration>
          <mainClass>com.antai.DriverServiceApplication</mainClass>
          <includeSystemScope>true</includeSystemScope>
        </configuration>
        <executions>
          <execution>
            <id>repackage</id>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!--在这里修改版本-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.0.2</version>
      </plugin>
    </plugins>
  </build>
</project>

1.3、生成jar包:atiot-driver-collection.jar

2.1、父工程调用

package com.antai.atiotmaster;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class DriverTest {

    //子jar包位置
    private final static String jarPath =  "D:\\package\\antai-iot\\driver\\atiot-driver-collection\\atiot-driver-collection.jar";

    public static void main(String[] args) throws IOException {

        executeDriver();
    }

    //执行驱动
    public static void executeDriver() {

        URL url = null;
        Object result = null;

        try {
            url = new URL("file:" + jarPath);

            //自己定义的classLoader类,把外部路径也加到load路径里,使系统去该路经load对象
            URLClassLoader loader = new URLClassLoader(new URL[]{url});

            Class<?> clazz = loader.loadClass("com.antai.iot.collection.service.DriverService");      

            //创建对象
            Object o = clazz.newInstance();

            //加载方法
            Method m = clazz.getDeclaredMethod("getDriveConfig", null);

            //执行方法
            result = m.invoke(o);

            System.out.println(result);
        } catch (MalformedURLException e) {
            //"包地址错误"
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            //"未注册类";
            e.printStackTrace();
        } catch (InstantiationException e) {
            //"创建对象错误"
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            //"非法访问";
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            //"未注册方法";
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            //"调用方法失败";
            e.printStackTrace();
        }
    }
}
运行结果及报错内容

java.lang.ClassNotFoundException: com.antai.iot.collection.service.DriverService
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.antai.atiotmaster.DriverTest.executeDriver(DriverTest.java:39)
at com.antai.atiotmaster.DriverTest.main(DriverTest.java:20)

我想要达到的结果
        //执行方法
        result = m.invoke(o);

        System.out.println(result);
   
        //期望输出结果
        DriveConfig
     
  • 写回答

1条回答 默认 最新

  • Tomshidi 2022-03-17 16:15
    关注

    你需要把atiot-driver-collection.jar包加到父工程的依赖里(maven依赖,或者直接外部jar依赖)

    评论

报告相同问题?

问题事件

  • 创建了问题 3月17日

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么