[英]How can i create an object class to perform downloading of .jar dependencies from maven repository
根據上面的標題,我需要有關如何創建對象類以執行從maven存儲庫下載.jar依賴項的幫助。 我有一個JAR文件,其中包含三個類,其中包括: CommandHandler.class ; KeyStroke.class和Main.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
類將通過同一classloader
即URLClassLoader
實例)動態加載target.jar
和spring-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方法。有兩點很重要:
BootStrap
類和Target
類不屬於同一個jar文件。 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.