繁体   English   中英

我如何创建对象类以执行从Maven存储库下载.jar依赖项

[英]How can i create an object class to perform downloading of .jar dependencies from maven repository

根据上面的标题,我需要有关如何创建对象类以执行从maven存储库下载.jar依赖项的帮助。 我有一个JAR文件,其中包含三个类,其中包括: CommandHandler.class ; KeyStroke.classMain.class以及每个类都有其依赖项,需要下载免费的Maven存储库。 现在,我的问题是如何在我的主程序逻辑开始执行之前,创建一个对象来执行下载依赖项所需的所有必要任务。 因为我相信如果没有依赖项,我的上述类实现可能会遇到严重的异常...请高度赞赏任何帮助/建议/提示。 提前致谢。

如果要在运行时动态加载jar,可以执行以下操作。在下面的示例中,我假设从属jar是spring-context ,如下所示:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.1.RELEASE</version>
        <scope>provided</scope>
    </dependency>

我得到了那个罐子的URL, http://maven.aliyun.com/nexus/content/groups/public/org/springframework/spring-context/4.3.1.RELEASE/spring-context-4.3.1.RELEASE.jar?spm=0.0.0.0.kG1Pdw&file=spring-context-4.3.1.RELEASE.jar

然后,有一个类Target取决于spring-context包含的DateFormatter类,并且有一个名为start的方法。

import org.springframework.format.datetime.DateFormatter;

public class Target {

private static DateFormatter dateFormatter;

public void start(){
    System.out.println(this.getClass().getClassLoader());
    dateFormatter=new DateFormatter();
    System.out.println(dateFormatter);
    }
}

接下来,我们将上述代码编译并打包为一个名为target.jar的jar,并将其存储在D:\\\\test\\\\target.jar

接下来,我们应该在另一个jar中声明一个名为BootStrap的类,该类将调用Target实例的方法start BootStarp类将通过同一classloaderURLClassLoader实例)动态加载target.jarspring-context jar文件,因为这样,在Target实例中start的方法可以访问spring-context定义的DateFormatter类。

public class BootStrap {


public static void main(String[] args) throws Exception{
    URL url = new URL("http://maven.aliyun.com/nexus/content/groups/public/org/springframework/spring-context/4.3.1.RELEASE/spring-context-4.3.1.RELEASE.jar?spm=0.0.0.0.kG1Pdw&file=spring-context-4.3.1.RELEASE.jar");
    URL url2= (new File("D:\\test\\target.jar").toURI().toURL());
    URLClassLoader classLoader = new URLClassLoader(new URL[]{url,url2});
    Class<?> clz = classLoader.loadClass("com.zhuyiren.Target");
    Object main = clz.newInstance();
    Method test = clz.getMethod("start");
    test.invoke(main);
    }
}

最后,运行BootStrap main方法。有两点很重要:

  1. BootStrap类和Target类不属于同一个jar文件。
  2. target.jar未存储在CLASSPATH路径中。

我们可以看到结果:

java.net.URLClassLoader@e9e54c2
org.springframework.format.datetime.DateFormatter@4dd8dc3

这样就可以成功访问在spring-context jar文件中定义的DateFormatter实例,并且spring-context不存储在CLASSPATH ,甚至不存储在本地文件系统中。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM