springboot項目jar包通過java-jar啟動原理


springboot項目打成的jar包一般通過 java-jar  xxx.jar命令啟動,原理:

    原理:查看解壓后的demo/target/demo/META-INF/MANIFEST.MF

 

 

 通過java-jar的方式啟動 springboot項目時,首先找到    上圖 文件中的  Main-Class    jarLauncher主類,查看JarLauncher源碼:

依賴:

  

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-loader -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-loader</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>


執行JarLauncher.java 中 的main方法:
public static void main(String[] args) throws Exception {
(new JarLauncher()).launch(args);
}

Launcher.java 的 launch()方法:
protected void launch(String[] args) throws Exception {
if (!this.isExploded()) {
JarFile.registerUrlProtocolHandler();
}

ClassLoader classLoader = this.createClassLoader(this.getClassPathArchivesIterator());
String jarMode = System.getProperty("jarmode");
String launchClass = jarMode != null && !jarMode.isEmpty() ? "org.springframework.boot.loader.jarmode.JarModeLauncher" : this.getMainClass();
this.launch(args, launchClass, classLoader);
}

查看 getMainClass()方法:(實現類中 PropertiesLauncher)
protected String getMainClass() throws Exception {
  //加載 jar包 target目錄下的 MANIFEST.MF 文件中 Start-Class配置,找到springboot的啟動類
    String mainClass = this.getProperty("loader.main", "Start-Class");
if (mainClass == null) {
throw new IllegalStateException("No 'loader.main' or 'Start-Class' specified");
} else {
return mainClass;
}
}

繼續執行Launcher.java的 launch()方法:執行run方法
protected void launch(String[] args, String launchClass, ClassLoader classLoader) throws Exception {
Thread.currentThread().setContextClassLoader(classLoader);
this.createMainMethodRunner(launchClass, args, classLoader).run();
}

run()方法:
public void run() throws Exception {
   //獲取springboot項目啟動類
Class<?> mainClass = Class.forName(this.mainClassName, false, Thread.currentThread().getContextClassLoader());
   //獲取啟動方法 main方法:
Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
mainMethod.setAccessible(true);
  //反射運行main方法
mainMethod.invoke((Object)null, this.args);
}

以上就是springboot項目通過 java-jar啟動 jar包的 原理。


























免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM